1// Package daemon holds vev's server-side session multiplexer use case.
2package daemon
3
4import (
5 "context"
6 cryptorand "crypto/rand"
7 "encoding/binary"
8 "errors"
9 "log/slog"
10 "math"
11 "os"
12 "reflect"
13 "sort"
14 "sync"
15 "sync/atomic"
16 "time"
17
18 "github.com/bnema/vev/internal/domain"
19 "github.com/bnema/vev/internal/domain/terminalcap"
20 "github.com/bnema/vev/internal/ports"
21 "github.com/bnema/vev/internal/protocol"
22 "github.com/bnema/vev/internal/usecase/keys"
23 recoveryusecase "github.com/bnema/vev/internal/usecase/recovery"
24)
25
26// Scheduler debounce bounds. Idle updates use the minimum for low latency;
27// sustained floods step toward the maximum to reduce frame/syscall pressure.
28const (
29 minDebounceInterval = 2 * time.Millisecond
30 maxSyncUpdateDuration = 500 * time.Millisecond
31)
32
33const debounceInterval = minDebounceInterval
34
35// ptyReadBufSize is the PTY reader's read buffer.
36const ptyReadBufSize = 32 * 1024
37
38// New and restored panes have independent line and uncompressed logical-byte
39// ceilings. Visible primary and alternate screens are outside this budget.
40const (
41 defaultScrollbackRows = domain.DefaultScrollbackLines
42 defaultScrollbackBytes = domain.DefaultScrollbackMegabytes * 1_000_000
43)
44
45// detachNotifyTimeout bounds the best-effort Detached notification on the
46// detach/kill/shutdown paths: if a wedged client (full kernel send buffer)
47// blocks the write for this long, its transport is force-closed, which fails
48// the in-flight send. Teardown is never gated on a client draining its socket.
49const detachNotifyTimeout = time.Second
50
51// maxUnackedOutputStates caps how many output states may be in flight (sent but
52// not yet acked by the client) before paint defers rather than composing
53// another diff. It bounds the daemon's paint rate to the client's ack rate, so
54// heavy output degrades to lower fps on a slow link instead of overflowing the
55// transport. It must stay well under the datagram carriage's 32-frame client
56// window so its reliable queue never fills from painting alone.
57const maxUnackedOutputStates = protocol.MaxOutputWindow
58
59// normalizeOutputWindow bounds the untrusted Hello value. Zero deliberately
60// means the legacy/default window, so malformed or absent values remain safe.
61func normalizeOutputWindow(window uint8) uint8 {
62 if window == 0 || window > maxUnackedOutputStates {
63 return maxUnackedOutputStates
64 }
65 return window
66}
67
68const defaultResumeParkGrace = 15 * time.Minute
69
70// defaultSuspendedSafetyExpiry bounds how long the daemon retains a suspended
71// attachment. Suspension keeps transport ownership and session membership but
72// removes interactive authority, so a client that never returns must not keep
73// the underlying process alive indefinitely. Expiry is a terminal, no-notice
74// eviction that never mints a resume credential.
75const defaultSuspendedSafetyExpiry = 24 * time.Hour
76
77// defaultSize is retained for headless layout helpers that have no client
78// window; Hello routing rejects invalid dimensions instead of using it.
79var defaultSize = domain.Size{Cols: 80, Rows: 24}
80
81type Daemon struct {
82 mu sync.Mutex
83 sessions map[domain.SessionID]*session
84 inactive map[string]inactiveSession
85 // creating reserves names while durable creation I/O runs without mu.
86 creating map[string]struct{}
87 nextID uint64
88 // lastAllocatedCreatedAt is the named-session lifecycle timestamp high-water
89 // mark. It is guarded by mu and prevents a wall-clock regression from
90 // reusing a lifecycle identity.
91 lastAllocatedCreatedAt int64
92 mruSeq atomic.Uint64
93 creationRequestSeq atomic.Uint64
94 // closing marks that explicit daemon shutdown (KillDaemon/process
95 // cancellation) has irreversibly begun. It is set under mu when
96 // shutdownAll starts, and checked by route under the same mutex — so a Hello
97 // racing shutdown can never insert a new session that nobody would tear
98 // down. Neither an empty registry (final session removal) nor a KillAll
99 // purge sets it: the daemon survives empty→occupied→empty and survives a
100 // purge, and only an explicit stop/process cancellation ends it.
101 closing bool
102
103 // moveLifecycleMu is the daemon-level admission gate for transferable
104 // ownership changes. It is acquired before any session teardownMu, and is
105 // never held while a move, teardown, or external operation runs.
106 moveLifecycleMu sync.Mutex
107 moveLifecycleClosing bool
108 moveLifecycleActive uint
109 moveLifecycleChanged chan struct{}
110 // paneProcessCtx roots transferable pane processes outside any one session.
111 // Shutdown cancels it only after the global move gate drains.
112 paneProcessCtx context.Context
113 paneProcessCancel context.CancelFunc
114
115 // purgeAllMu grants one daemon-wide purge (KillAll) owner at a time so two
116 // concurrent kill-all requests never interleave their exact lifecycle sets.
117 // It is not an admission gate; see purgeAdmissionClosing below.
118 purgeAllMu sync.Mutex
119 // purgeAdmissionClosing is the transient KillAll admission gate. Unlike
120 // closing and moveLifecycleClosing it is re-openable: purgeAllSessions sets
121 // it under mu, removes exactly the live and stopped/broken/durable records
122 // captured at that instant, then clears it so the daemon keeps serving.
123 // Creation and restoration wait on the changed channel (a blocked writer
124 // keeps new admissions out), while moves and internal creations reject, so
125 // no transition can be inserted into the purge's exact lifecycle set.
126 // purgeAdmissionActive counts admitted transitions the purge must drain.
127 // purgeEpoch increments once at each purge that acquires the gate (after the
128 // drain) so a restoration worker blocked on admission can detect a purge
129 // that completed while it waited and must not resurrect the records captured
130 // before that purge.
131 // All three fields are guarded by mu.
132 purgeAdmissionClosing bool
133 purgeAdmissionActive uint
134 purgeAdmissionChanged chan struct{}
135 purgeEpoch uint64
136
137 // notifies holds one completion channel per in-flight async Detached
138 // notification (guarded by mu, pruned on insert). Channels rather than a
139 // WaitGroup: notifications are spawned from arbitrary goroutines while
140 // Serve may be waiting, and WaitGroup forbids Add-from-zero concurrent
141 // with Wait.
142 notifies []chan struct{}
143 // resume owns parked and in-flight parking resume credentials. Guarded by mu.
144 resume resumeCredentials
145 // suspended retains one daemon-owned safety expiry per suspended
146 // attachment. Expiry is exact: the record carries the suspension's
147 // lifecycle generation and transport incarnation, so a later activation,
148 // re-suspension, detach, or session teardown can never be retired by a
149 // stale timer. Guarded by mu.
150 suspended map[*attachedClient]*suspendedAttachmentRetention
151 // graphics reserves attachment/session-scoped Kitty ID blocks. Guarded by
152 // mu; see graphicsNamespacePool.
153 graphics graphicsNamespacePool
154
155 attnMu sync.Mutex
156 animFrame int
157 animWake chan struct{}
158
159 // paletteHistory is the daemon-wide recent-command order; its mu is a leaf.
160 paletteHistory paletteHistory
161 // daemonTestHooks holds deterministic test seams; production leaves every
162 // hook nil.
163 daemonTestHooks
164 ptys ports.PTYFactory
165 clock ports.Clock
166 log *slog.Logger
167 runtimeObserver ports.RuntimeObserver
168 baseEnv []string
169 shell string
170 shellArgs []string
171 shellOverride bool
172 persistEnabled bool
173 catalogue ports.Catalogue
174 catalogueRecords []domain.CatalogueRecord
175 catalogueRecordsProvided bool
176 // snapshotRepository is the sole checkpoint storage contract.
177 snapshotRepository ports.SnapshotRepository
178 recovery *recoveryusecase.Coordinator
179 snapshotGarbageCollection bool
180 snapsEnabled bool
181 noticeStore ports.NoticeStore
182 // snapshots owns the snapshot worker, the durable-writer lifecycle
183 // signals, and the global persistence-failure notice state.
184 snapshots snapshotWorker
185 shutdownNoticeMu sync.Mutex
186 shutdownNoticedSessions map[string]struct{}
187 restoreDone chan struct{}
188 restoreOnce sync.Once
189 // proc inspects pane processes (cwd, foreground command, argv). Nil means
190 // no inspection is available; see WithProcessInspector.
191 proc ports.ProcessInspector
192 dirOrHome func(string) string
193 // bindings is read by keys.Router through its own atomic pointer, so it is
194 // published next to (not inside) the runtime config snapshot.
195 bindings atomic.Pointer[keys.Bindings]
196 // config is the immutable runtime configuration snapshot, published with
197 // defaults by New and replaced by every ApplyConfig; read it through
198 // currentRuntimeConfig.
199 config atomic.Pointer[runtimeConfig]
200 barScripts *barScriptState
201 notices *noticeCenter
202 resumeParkGrace time.Duration
203 suspendedSafetyExpiry time.Duration
204 // tempDir overrides os.TempDir() for clipboard-image-transfer writes
205 // (see clipboard.go); empty means use os.TempDir().
206 tempDir string
207
208 serveCtx context.Context
209 serveCancel context.CancelFunc
210
211 // hardCtx force-closes connection transports on shutdown, but only after
212 // shutdownAll has delivered graceful Detached notices — keeping it separate
213 // from serveCtx so a parent-context cancel never races the notice.
214 hardCtx context.Context
215 hardCancel context.CancelFunc
216
217 // done is closed exactly once by an explicit daemon stop (shutdownAll) to
218 // break Serve's accept loop. It is deliberately not closed by final session
219 // removal or by a KillAll purge: an empty registry and a purged registry
220 // both keep the daemon serving.
221 done chan struct{}
222 doneOnce sync.Once
223
224 // sessWg owns attention animation, bar-script polling, CWD sampling,
225 // snapshot save/restore, and floating-session launch goroutines.
226 sessWg sync.WaitGroup
227 connWg sync.WaitGroup // per-connection handler goroutines
228 // attachmentCleanupWg owns replacement transport closes and retired render
229 // worker joins. Only connection handlers add work; Serve waits for those
230 // handlers before joining this group, so no Add races its terminal Wait.
231 attachmentCleanupWg sync.WaitGroup
232}
233
234// daemonTestHooks are deterministic seams that let tests pause or observe the
235// daemon inside narrow concurrency windows. Production never sets them, and no
236// hook may perform external work while locks are held.
237type daemonTestHooks struct {
238 // beforeRecentSessionHandoff is a deterministic test seam for the narrow
239 // interval between JRS validation and its committed hand-off.
240 beforeRecentSessionHandoff func()
241 // beforeCopyModeRevalidate is a deterministic test seam between staging a
242 // copy-mode candidate and revalidating its pane membership.
243 beforeCopyModeRevalidate func()
244 // beforeCopyMouseMap is a deterministic seam after an immutable copy-input
245 // snapshot is captured and before its mapped position is applied.
246 beforeCopyMouseMap func()
247 // beforeSessionResizePublication runs after final external PTY validation
248 // and before coordinator epoch admission. It is a deterministic regression
249 // seam for stale resize publication.
250 beforeSessionResizePublication func()
251 // beforeResizeOwnerPostEffect pauses after a resize's optimistic owner check
252 // and immediately before a post-commit effect is published. Tests use it to
253 // move a pane through the ordered resize fences at the former TOCTOU window.
254 beforeResizeOwnerPostEffect func(resizeOwnerPostEffect)
255 // afterConnectionSessionSnapshot is a deterministic test seam after the
256 // connection loop reads its current session and before it captures that role.
257 afterConnectionSessionSnapshot func(*session)
258 // afterAttachmentFrameDispatch is a deterministic test seam after the
259 // connection loop snapshots a token and before a decoded frame takes effect.
260 afterAttachmentFrameDispatch func(attachmentCapability)
261 // afterAttachmentEffectParticipantsSnapshotted observes immutable role-gate
262 // participants after architecture preflight locks are released and before
263 // the globally ordered freeze begins.
264 afterAttachmentEffectParticipantsSnapshotted func(string, []*attachedClient)
265 // afterAttachmentEffectGateFrozen observes each participant after it is frozen in
266 // immutable identity order and before drain/publication continues.
267 afterAttachmentEffectGateFrozen func(string, *attachedClient)
268 // afterAttachmentEffectsFrozen observes the lock-free boundary after all affected
269 // attachment gates are frozen and drained, before architecture publication.
270 afterAttachmentEffectsFrozen func()
271 // afterPurgeAdmission is a deterministic test seam that runs after a KillAll
272 // purge has closed purge admission and taken the closing fence, while it
273 // still owns purgeAllMu. It lets tests observe purge serialization.
274 afterPurgeAdmission func()
275 // beforePurgeLiveSessionKill is a deterministic test seam that runs after a
276 // KillAll purge's per-unit shutdown precheck and before that live unit
277 // attempts teardown ownership. Tests use it to let an explicit stop win that
278 // exact window, proving a stop-owned unit is never reported as a success.
279 beforePurgeLiveSessionKill func(*session)
280 // afterSessionKillQuarantine is a deterministic test seam that runs while a
281 // teardown owns the session and its snapshot coordinator is quarantined, but
282 // before the pre-publication revalidation. Tests use it to change the
283 // participant set in that window and prove a post-quarantine abort rolls the
284 // quarantine back so a surviving session keeps checkpointing.
285 afterSessionKillQuarantine func(*session)
286 // beforeAttachmentTransitionIdentityAdmission is a deterministic test seam
287 // after a ready transition published its capability and before the committed
288 // route identity is admitted, so tests can supersede that exact capability in
289 // the window before the transition's first paint and completion.
290 beforeAttachmentTransitionIdentityAdmission func(attachmentCapability)
291 // afterAttachmentTransitionCoordinatorsLocked is a deterministic lock-order
292 // seam used by transition validation tests.
293 afterAttachmentTransitionCoordinatorsLocked func()
294 // beforeMoveDispatch, afterMoveLifecycleReserved, and
295 // afterMovePaneSourceSnapshot are test-only seams. They run before dispatch
296 // admission, after lifecycle reservation, and after the pre-fence source
297 // attachment snapshot respectively. beforeMovePaneCommit runs inside the
298 // non-failing publication section. None is set in production, and none may
299 // perform external work while locks are held.
300 beforeMoveDispatch func()
301 afterMoveLifecycleReserved func()
302 afterMoveLifecycleGateBeforeTeardownLocks func()
303 afterMovePaneSourceSnapshot func()
304 afterMoveTabSourceSnapshot func()
305 beforeMovePaneCommit func()
306 beforeMoveTabCommit func()
307 // beforeMoveFollowCompletion is a deterministic test seam after the composite
308 // follow's first paint and before the postcommit admits the capability that
309 // reports completion, so tests can supersede the published capability.
310 beforeMoveFollowCompletion func(attachmentCapability)
311 // afterDetachAttachmentEffectsFrozen observes terminal detach after it wins the
312 // attachment gate but before it checks session ownership.
313 afterDetachAttachmentEffectsFrozen func()
314 // beforeClientGoneDetach pauses clientGone after the stale-transport
315 // precheck and before exact transport/incarnation detach validation.
316 beforeClientGoneDetach func()
317 // beforeMarkParkingInFlight pauses resumeLiveAttachment after the live
318 // credential matches and before markParkingInFlight, so tests can win
319 // explicit detach or session removal before late marker publication.
320 beforeMarkParkingInFlight func()
321 // afterClientGoneDetach pauses finishClientGone after detach won and before
322 // parkAttachment. The parking-in-flight marker must already be published.
323 afterClientGoneDetach func()
324 // afterResumeLiveDetach pauses resumeLiveAttachment after detach won and
325 // before parkAttachment. The parking-in-flight marker must already be
326 // published so a concurrent same-token resume can wait the gap.
327 afterResumeLiveDetach func()
328 // afterParkingWaitArmed observes waitParkingInFlight after it has resolved a
329 // matching in-flight entry and before it blocks on done.
330 afterParkingWaitArmed func()
331 // beforeResumeParkedSendMu pauses resumeParked after the initial parked
332 // lookup and before the attachment send lock, so tests can consume or
333 // replace the credential while the handshake waits.
334 beforeResumeParkedSendMu func()
335 // afterAttachmentEffectAdmitted is a deterministic test seam after a frame/paint
336 // reserves its exact capability and before its first observable mutation.
337 afterAttachmentEffectAdmitted func(attachmentCapability)
338 // beforeFirstPaintSendWait is a test-only seam immediately before a
339 // transition first paint waits for the attachment send lock.
340 beforeFirstPaintSendWait func(attachmentCapability)
341 // afterDelayedKeyEffectAttempt observes whether a timer callback acquired a
342 // fresh exact capability before producing PTY, action, or overlay effects.
343 afterDelayedKeyEffectAttempt func(bool)
344 // afterActionAttachmentEffectEnded observes action-specific admission release. It
345 // is a deterministic seam for proving no role-bound mutation follows release.
346 afterActionAttachmentEffectEnded func(string)
347 // beforeAttachmentSendErrorCleanup pauses asynchronous render-failure retirement
348 // after the render ticket ends and before exact lifecycle validation.
349 beforeAttachmentSendErrorCleanup func(attachmentCapability)
350 afterAttachmentSendErrorCleanup func()
351 // beforeSuspendedExpiryFreeze pauses the safety expiry after its timer fired
352 // and before it freezes the attachment effect gate, so tests can win
353 // activation, disconnect, or replacement first. It is a test-only seam.
354 beforeSuspendedExpiryFreeze func(*attachedClient)
355}
356
357type parkedAttachment struct {
358 sess *session
359 ac *attachedClient
360 pickerGeneration uint64
361 paletteGeneration uint64
362 timer ports.Timer
363 claimed bool
364 done chan struct{}
365 doneOnce sync.Once
366}
367
368// parkingAttachment is the observable detach→park lifecycle for one resume
369// credential. done closes when the token is published into parked or parking
370// is abandoned.
371type parkingAttachment struct {
372 sess *session
373 ac *attachedClient
374 done chan struct{}
375 doneOnce sync.Once
376}
377
378func (p *parkingAttachment) closeDone() {
379 if p == nil || p.done == nil {
380 return
381 }
382 p.doneOnce.Do(func() { close(p.done) })
383}
384
385// inactiveSession is the durable authority for a named session without a live
386// runtime. It remains present while healthy-down, restoring, broken, degraded,
387// or purge-fenced; callers must use its predicates instead of inferring those
388// states from map membership.
389type inactiveSession struct {
390 name string
391 cwd string
392 createdAt int64
393 incarnation domain.IncarnationID
394 lastUsedSeq uint64
395 tabNames []string
396 tabRecords []domain.CatalogueTabRecord
397 purging bool
398 record domain.CatalogueRecord
399 state protocol.SessionState
400 restoreDone chan struct{}
401}
402
403func (s inactiveSession) restorePending() bool {
404 if s.restoreDone == nil {
405 return false
406 }
407 select {
408 case <-s.restoreDone:
409 return false
410 default:
411 return true
412 }
413}
414
415func (s inactiveSession) broken() bool {
416 return s.state == protocol.SessionBroken || s.record.DegradedReason != ""
417}
418
419func (s inactiveSession) visible() bool {
420 return !s.purging
421}
422
423func (s inactiveSession) canResume() bool {
424 return s.visible() && s.state == protocol.SessionDown && !s.broken()
425}
426
427func (s inactiveSession) sameLifecycle(other inactiveSession) bool {
428 return s.name == other.name && s.createdAt == other.createdAt && s.incarnation == other.incarnation
429}
430
431type Option func(*Daemon)
432
433// WithRuntimeObserver accepts only a composition-root serialized observer.
434// The application owns its lifecycle; the daemon never creates or closes a
435// second reporting worker around it.
436func WithRuntimeObserver(observer ports.SerializedRuntimeObserver) Option {
437 return func(d *Daemon) { d.runtimeObserver = observer }
438}
439
440// WithShell overrides the command (and its args) each session spawns. The
441// default is $SHELL (or /bin/sh) with no arguments; tests use this to run a
442// deterministic program.
443func WithShell(cmd string, args []string) Option {
444 return func(d *Daemon) {
445 d.shell = cmd
446 d.shellArgs = args
447 d.shellOverride = true
448 }
449}
450
451// WithCatalogue installs the singular catalogue and the strictly opened
452// records that define the daemon's expected-session registry at startup.
453func WithCatalogue(catalogue ports.Catalogue, records []domain.CatalogueRecord) Option {
454 return func(d *Daemon) {
455 d.catalogue = catalogue
456 d.persistEnabled = catalogue != nil
457 d.catalogueRecords = append([]domain.CatalogueRecord(nil), records...)
458 d.catalogueRecordsProvided = true
459 }
460}
461
462func (d *Daemon) catalogueRecord(name string) (domain.CatalogueRecord, bool, error) {
463 if d == nil || d.catalogue == nil {
464 return domain.CatalogueRecord{}, false, nil
465 }
466 return d.catalogue.Record(name)
467}
468
469// markCatalogueDirty buffers metadata. The periodic catalogue timer, the next
470// identity write, or shutdown provides the durability barrier.
471func (d *Daemon) markCatalogueDirty(update domain.CatalogueMetadataUpdate) {
472 if d == nil || d.catalogue == nil {
473 return
474 }
475 if err := d.catalogue.UpdateMetadata(update); err != nil {
476 d.log.Warn("buffering session metadata failed", "err", err, "session", update.Name)
477 }
478}
479
480func (d *Daemon) flushCatalogue() error {
481 if d == nil || d.catalogue == nil {
482 return nil
483 }
484 return d.catalogue.Sync()
485}
486
487// WithRecoveryCoordinator installs the durable recovery coordinator.
488func WithRecoveryCoordinator(coordinator *recoveryusecase.Coordinator) Option {
489 return func(d *Daemon) {
490 d.recovery = coordinator
491 }
492}
493
494// WithSnapshotRepository enables content-addressed incremental snapshots.
495func WithSnapshotRepository(repository ports.SnapshotRepository) Option {
496 return func(d *Daemon) {
497 if isNilSnapshotRepository(repository) {
498 return
499 }
500 d.snapshotRepository = repository
501 d.snapsEnabled = true
502 }
503}
504
505func isNilSnapshotRepository(repository ports.SnapshotRepository) bool {
506 if repository == nil {
507 return true
508 }
509 value := reflect.ValueOf(repository)
510 switch value.Kind() {
511 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
512 return value.IsNil()
513 default:
514 return false
515 }
516}
517
518// WithNoticeStore enables persisting undeliverable notices across daemon
519// restarts. A nil store keeps the daemon in no-op notice-persistence mode.
520func WithNoticeStore(store ports.NoticeStore) Option {
521 return func(d *Daemon) { d.noticeStore = store }
522}
523
524// WithSnapshotGarbageCollection runs background snapshot GC through the
525// recovery coordinator installed by WithRecoveryCoordinator.
526func WithSnapshotGarbageCollection() Option {
527 return func(d *Daemon) { d.snapshotGarbageCollection = true }
528}
529
530// WithProcessInspector installs the platform process-inspection implementation.
531func WithProcessInspector(ins ports.ProcessInspector) Option {
532 return func(d *Daemon) {
533 if ins == nil {
534 return
535 }
536 d.proc = ins
537 }
538}
539
540// WithDirOrHome installs path fallback behavior from the application layer.
541func WithDirOrHome(fn func(string) string) Option {
542 return func(d *Daemon) {
543 if fn != nil {
544 d.dirOrHome = fn
545 }
546 }
547}
548
549// WithTempDir overrides the directory clipboard-image-transfer writes temp
550// files into (production default: os.TempDir()); tests use this with
551// t.TempDir() so writes are isolated and auto-cleaned.
552func WithTempDir(dir string) Option {
553 return func(d *Daemon) {
554 d.tempDir = dir
555 }
556}
557
558// WithBarScriptCommandRunner installs the shell command runner used by bar scripts.
559func WithBarScriptCommandRunner(runner ports.ShellCommandRunner) Option {
560 return func(d *Daemon) {
561 if runner != nil {
562 d.barScripts.runner = barScriptRunner{runner: runner}
563 }
564 }
565}
566
567// WithResumeParkGrace overrides how long detached resume-capable clients stay
568// parked for reconnection. Non-positive durations keep the default.
569func WithResumeParkGrace(grace time.Duration) Option {
570 return func(d *Daemon) {
571 if grace > 0 {
572 d.resumeParkGrace = grace
573 }
574 }
575}
576
577// WithSuspendedSafetyExpiry overrides how long the daemon retains a suspended
578// attachment before terminal eviction. Non-positive durations keep the default.
579// Fake-clock tests set a short duration so the real timer path stays under test.
580func WithSuspendedSafetyExpiry(expiry time.Duration) Option {
581 return func(d *Daemon) {
582 if expiry > 0 {
583 d.suspendedSafetyExpiry = expiry
584 }
585 }
586}
587
588// WithConfig applies the initial user configuration.
589func WithConfig(cfg domain.Config) Option {
590 return func(d *Daemon) {
591 d.ApplyConfig(cfg)
592 }
593}
594
595// allocateLifecycleCreatedAtLocked returns a unique lifecycle timestamp. Caller
596// holds d.mu. The persisted high-water mark is loaded by New before any named
597// session can be resumed or created.
598func (d *Daemon) allocateLifecycleCreatedAtLocked() (int64, error) {
599 now := d.nowUnixNano()
600 if now <= d.lastAllocatedCreatedAt {
601 if d.lastAllocatedCreatedAt == math.MaxInt64 {
602 return 0, errors.New("daemon: lifecycle identities exhausted")
603 }
604 now = d.lastAllocatedCreatedAt + 1
605 }
606 d.lastAllocatedCreatedAt = now
607 return now, nil
608}
609
610func (d *Daemon) nowUnixNano() int64 {
611 return d.daemonNow().UnixNano()
612}
613
614// daemonNow reports the daemon clock. New defaults a nil clock to the
615// system clock, so the fallback below only serves hand-built fixtures
616// and stays explicit about its provenance instead of hiding a bare
617// wall-clock read.
618func (d *Daemon) daemonNow() time.Time {
619 if d == nil || d.clock == nil {
620 return systemClock{}.Now()
621 }
622 return d.clock.Now()
623}
624
625type systemClock struct{}
626type systemTimer struct{ *time.Timer }
627
628var graphicsNamespaceFallbackSalt atomic.Uint64
629
630func newGraphicsNamespaceSalt() uint64 {
631 var bytes [8]byte
632 if _, err := cryptorand.Read(bytes[:]); err == nil {
633 if salt := binary.BigEndian.Uint64(bytes[:]); salt != 0 {
634 return salt
635 }
636 }
637 for {
638 salt := graphicsNamespaceFallbackSalt.Add(1)
639 if salt != 0 {
640 return salt
641 }
642 }
643}
644
645func (systemClock) Now() time.Time { return time.Now() }
646func (systemClock) NewTimer(delay time.Duration) ports.Timer {
647 return systemTimer{Timer: time.NewTimer(delay)}
648}
649func (t systemTimer) C() <-chan time.Time { return t.Timer.C }
650
651// New constructs a Daemon. ptys spawns PTY-backed children, clock drives the
652// render debounce, and log receives diagnostics (defaults to slog.Default).
653func New(ptys ports.PTYFactory, clock ports.Clock, log *slog.Logger, opts ...Option) *Daemon {
654 if log == nil {
655 log = slog.Default()
656 }
657 if clock == nil {
658 clock = systemClock{}
659 }
660 paneProcessCtx, paneProcessCancel := context.WithCancel(context.Background())
661 d := &Daemon{
662 sessions: make(map[domain.SessionID]*session),
663 inactive: make(map[string]inactiveSession),
664 creating: make(map[string]struct{}),
665 resume: newResumeCredentials(),
666 suspended: make(map[*attachedClient]*suspendedAttachmentRetention),
667 graphics: newGraphicsNamespacePool(),
668 paneProcessCtx: paneProcessCtx,
669 paneProcessCancel: paneProcessCancel,
670 ptys: ptys,
671 clock: clock,
672 log: log,
673 baseEnv: os.Environ(),
674 shell: defaultShellCommand,
675 dirOrHome: dirOrHome,
676 done: make(chan struct{}),
677 restoreDone: make(chan struct{}),
678 animWake: make(chan struct{}, 1),
679 snapshots: snapshotWorker{
680 jobs: make(chan *snapshotCapture, snapshotQueueCapacity),
681 admitted: make(map[*snapshotCapture]struct{}),
682 wake: make(chan struct{}, 1),
683 },
684 notices: newNoticeCenter(),
685 resumeParkGrace: defaultResumeParkGrace,
686 suspendedSafetyExpiry: defaultSuspendedSafetyExpiry,
687 barScripts: &barScriptState{
688 cfg: barConfigFromDomain(domain.Defaults().Bar),
689 outputs: make(map[domain.SessionID]barScriptOutputs),
690 lastRefresh: make(map[domain.SessionID]time.Time),
691 lastContext: make(map[domain.SessionID]barScriptContext),
692 running: make(map[domain.SessionID]bool),
693 reload: make(chan struct{}, 1),
694 },
695 }
696 d.config.Store(defaultRuntimeConfig())
697 for _, o := range opts {
698 o(d)
699 }
700 if d.dirOrHome == nil {
701 d.dirOrHome = dirOrHome
702 }
703 if d.bindings.Load() == nil {
704 d.bindings.Store(keys.DefaultBindings())
705 }
706 records := d.catalogueRecords
707 var maxSeq uint64
708 var maxCreatedAt int64
709 hasCreatedAt := false
710 for _, r := range records {
711 if d.catalogueRecordsProvided {
712 state, done := initialSessionState(r)
713 d.inactive[r.Name] = inactiveSessionFromRecord(r, state, done)
714 } else {
715 d.inactive[r.Name] = inactiveSessionFromRecord(r, protocol.SessionDown, nil)
716 }
717 if !hasCreatedAt || r.CreatedAt > maxCreatedAt {
718 maxCreatedAt = r.CreatedAt
719 hasCreatedAt = true
720 }
721 if r.LastUsedSeq > maxSeq {
722 maxSeq = r.LastUsedSeq
723 }
724 }
725 if hasCreatedAt {
726 d.lastAllocatedCreatedAt = maxCreatedAt
727 }
728 d.mruSeq.Store(maxSeq)
729 return d
730}
731
732// Serve runs the accept loop over l, owning it for the loop's lifetime. It
733// returns only on ctx cancellation or an explicit daemon shutdown request
734// (KillDaemon), never when the session registry drains to empty: final
735// session removal is independent of daemon shutdown so the daemon survives
736// empty→occupied→empty and can accept fresh sessions again. A KillAll purge
737// leaves Serve running too. On the ctx path
738// attached clients are detached with ReasonServerShutdown.
739func (d *Daemon) Serve(ctx context.Context, l ports.ServerListener) error {
740 d.serveCtx, d.serveCancel = context.WithCancel(ctx)
741 defer d.serveCancel()
742 d.hardCtx, d.hardCancel = context.WithCancel(context.Background())
743 defer d.hardCancel()
744
745 d.sessWg.Go(func() {
746 d.attentionAnimator(d.serveCtx)
747 })
748 d.sessWg.Go(func() {
749 d.barScriptPoller(d.serveCtx)
750 })
751 d.sessWg.Go(func() {
752 d.historyMaintenance(d.serveCtx)
753 })
754 if d.persistEnabled {
755 d.sessWg.Go(func() {
756 d.cwdSampler(d.serveCtx)
757 })
758 }
759 if d.snapsEnabled {
760 d.startSnapshotEncodeWorker()
761 d.sessWg.Go(func() {
762 d.snapshotRepositorySaver(d.serveCtx)
763 })
764 d.startSnapshotRestoration()
765 d.startDurableMaintenance()
766 } else {
767 d.closeRestoreDone()
768 }
769 // Break the accept loop only on an explicit shutdown: the parent context
770 // being cancelled or an explicit daemon stop request (d.done). An empty
771 // registry never closes the listener, so the daemon keeps accepting.
772 go func() {
773 select {
774 case <-d.serveCtx.Done():
775 case <-d.done:
776 }
777 _ = l.Close()
778 }()
779
780 for {
781 tr, err := l.Accept()
782 if err != nil {
783 if d.serveCtx.Err() != nil {
784 d.log.Info("accept loop exiting", "err", err, "reason", "context canceled")
785 } else {
786 d.log.Warn("accept loop exiting", "err", err)
787 }
788 break
789 }
790 d.connWg.Go(func() {
791 d.handleConn(tr)
792 })
793 }
794
795 // Tear down. shutdownAll marks the daemon closing (route now rejects any
796 // racing Hello) and kills every session: PTYs are closed and contexts
797 // cancelled unconditionally, with the Detached notices sent asynchronously
798 // under a deadline. Wait for those notices (bounded — a wedged client's
799 // transport is force-closed by the deadline) before hard-closing the
800 // remaining parked connections, so graceful notices are never raced by the
801 // force-close. Finally drain the conn handlers, run one defensive sweep in
802 // case any ordering ever leaves a session behind, and join the session
803 // goroutines (readers unblock via pty.Close, coordinators via ctx cancel).
804 // One deadline owns every terminal checkpoint wait and the final worker
805 // join. A repository is allowed to ignore cancellation, so spending a fresh
806 // interval at either stage would make shutdown exceed its documented bound.
807 var snapshotDeadline *snapshotShutdownDeadline
808 if d.snapsEnabled {
809 snapshotDeadline = newSnapshotShutdownDeadline(d.clock)
810 defer snapshotDeadline.stop()
811 }
812 d.terminateAllForShutdown(protocol.ReasonServerShutdown, snapshotDeadline)
813 d.waitNotifies()
814 d.hardCancel()
815 d.serveCancel()
816 // Wait for handlers before flushing snapshots: a handler that already
817 // entered killSession may still submit its terminal capture after the
818 // registry snapshot has been removed.
819 d.connWg.Wait()
820 d.attachmentCleanupWg.Wait()
821 // Forced terminal checkpoints run before shutdown stops producers or the
822 // worker. StopDurableWriters reports every session whose final capture still
823 // owns work when the shared checkpoint budget expires. Persist one notice per
824 // affected session, then retain ownership until every writer actually exits.
825 stopCtx, stopCancel := snapshotStopContext(snapshotDeadline)
826 timedOutSessions := d.StopDurableWriters(stopCtx)
827 stopCancel()
828 for _, name := range timedOutSessions {
829 d.persistShutdownSnapshotFailure(name, context.DeadlineExceeded)
830 }
831 d.WaitDurableWriters()
832 d.terminateAllForShutdown(protocol.ReasonServerShutdown, snapshotDeadline)
833 d.waitSessionWorkersWithSnapshotDeadline(snapshotDeadline)
834 d.waitNotifies()
835 if err := d.flushCatalogue(); err != nil {
836 d.log.Warn("flushing session catalogue at shutdown failed", "err", err)
837 }
838 if d.catalogue != nil {
839 if err := d.catalogue.Close(); err != nil {
840 d.log.Warn("closing session catalogue failed", "err", err)
841 }
842 }
843 return nil
844}
845
846// shutdownAll is the explicit daemon-stop operation (wire KillDaemon). It is
847// the only caller that irreversibly ends the daemon: it closes move admission,
848// marks closing, reserves shutdown preservation for every live session, then
849// cancels the daemon-wide pane process context, preserves every live session as
850// stopped durable authority, and closes done so Serve returns.
851// KillAll never reaches this path. Setting closing under the same lock as the
852// snapshot guarantees no session can be inserted after the snapshot: route
853// rejects once closing is set, and both run under d.mu. killSession (which
854// relocks) runs after the lock is released.
855func (d *Daemon) shutdownAll(reason uint8) (checkpointIncomplete bool) {
856 return d.terminateAllForShutdown(reason, nil)
857}
858
859// terminateAllForShutdown performs the irreversible daemon teardown shared by
860// shutdownAll and Serve's exit path. It is separate from purgeAllSessions,
861// which leaves every daemon-wide shutdown fact untouched.
862func (d *Daemon) terminateAllForShutdown(reason uint8, deadline *snapshotShutdownDeadline) (checkpointIncomplete bool) {
863 // Stop background GC first so it releases the recovery fence before final
864 // checkpoints are published under the shutdown deadline.
865 d.cancelDurableMaintenance()
866 d.closeMoveLifecycles()
867 d.mu.Lock()
868 d.closing = true
869 // Wake any KillAll waiting on purge admission so it defers to this stop
870 // instead of holding the gate until its bounded drain deadline expires.
871 d.signalPurgeAdmissionChangedLocked()
872 d.purgeAllParkingLocked()
873 parkedRetirements := d.purgeAllParkedLocked()
874 d.purgeAllSuspendedLocked()
875 snapshot := d.sessionsSnapshotLocked()
876 d.mu.Unlock()
877 d.finishParkedAttachmentRetirements(parkedRetirements)
878 // Publish preservation policy for the complete registry snapshot before
879 // cancelling any PTY. Cancellation-driven EOF is allowed to own teardown,
880 // but its disposition must remain daemon shutdown rather than session purge.
881 // closeMoveLifecycles therefore leaves pane processes running; only this
882 // ordering, reserve then cancel, keeps a named session durable.
883 for _, s := range snapshot {
884 s.reserveShutdownTeardown()
885 }
886 d.cancelPaneProcesses()
887 d.log.Info("session termination begin", "reason", reason, "live_sessions", len(snapshot))
888 for _, s := range snapshot {
889 // Cancellation and PTY closure must not wait behind a teardown owner that
890 // is blocked in snapshot publication or purge work.
891 s.mu.Lock()
892 name := s.name
893 ephemeral := s.ephemeral
894 s.mu.Unlock()
895 s.stopInMemoryLifecycle()
896 if err := d.killSessionWithSnapshotDeadline(s, reason, false, deadline, nil); err != nil {
897 checkpointIncomplete = true
898 d.log.Error("closing session with unpersisted terminal state", "err", err)
899 }
900 if !ephemeral && deadline != nil {
901 select {
902 case <-deadline.Done():
903 checkpointIncomplete = true
904 d.persistShutdownSnapshotFailure(name, context.DeadlineExceeded)
905 default:
906 }
907 }
908 }
909 // Signal Serve even when a concurrent role transition made this initial
910 // pass abort; Serve owns the bounded defensive teardown passes.
911 d.doneOnce.Do(func() { close(d.done) })
912 return checkpointIncomplete
913}
914
915// waitSessionWorkersWithSnapshotDeadline joins in-memory workers when possible,
916// but never extends Serve beyond the shared repository shutdown budget. By this
917// point connection handlers are joined and every session has been cancelled, so
918// no new session worker can be registered while the waiter is active.
919func (d *Daemon) waitSessionWorkersWithSnapshotDeadline(deadline *snapshotShutdownDeadline) {
920 done := make(chan struct{})
921 go func() {
922 d.sessWg.Wait()
923 close(done)
924 }()
925 if deadline == nil {
926 <-done
927 return
928 }
929 select {
930 case <-done:
931 case <-deadline.Done():
932 }
933}
934
935// snapshotShutdownDeadline is a single-use shutdown budget shared by forced
936// checkpoints and the final snapshot worker join. Its done channel is never
937// closed by callers, so a detached worker can safely retain session state until
938// an uncooperative repository call returns.
939type snapshotShutdownDeadline struct {
940 done chan struct{}
941 stopCh chan struct{}
942 finished chan struct{}
943 stopOnce sync.Once
944}
945
946func newSnapshotShutdownDeadline(clock ports.Clock) *snapshotShutdownDeadline {
947 deadline := &snapshotShutdownDeadline{done: make(chan struct{}), stopCh: make(chan struct{}), finished: make(chan struct{})}
948 timer := clock.NewTimer(snapshotFinalFlushTimeout)
949 go func() {
950 defer close(deadline.finished)
951 select {
952 case <-timer.C():
953 close(deadline.done)
954 case <-deadline.stopCh:
955 timer.Stop()
956 }
957 }()
958 return deadline
959}
960
961func (d *snapshotShutdownDeadline) stop() {
962 if d != nil {
963 d.stopOnce.Do(func() {
964 close(d.stopCh)
965 <-d.finished
966 })
967 }
968}
969
970func (d *snapshotShutdownDeadline) Done() <-chan struct{} {
971 if d == nil {
972 return nil
973 }
974 return d.done
975}
976
977func snapshotStopContext(deadline *snapshotShutdownDeadline) (context.Context, context.CancelFunc) {
978 ctx, cancel := context.WithCancel(context.Background())
979 if deadline == nil {
980 return ctx, cancel
981 }
982 select {
983 case <-deadline.Done():
984 cancel()
985 return ctx, cancel
986 default:
987 }
988 stop := make(chan struct{})
989 go func() {
990 select {
991 case <-deadline.Done():
992 cancel()
993 case <-stop:
994 }
995 }()
996 var stopOnce sync.Once
997 return ctx, func() {
998 stopOnce.Do(func() { close(stop) })
999 cancel()
1000 }
1001}
1002
1003// registerSessionLocked publishes an exact attachment-session identity. Caller
1004// holds d.mu.
1005func (d *Daemon) registerSessionLocked(entry *session) bool {
1006 if entry == nil {
1007 return false
1008 }
1009 core := entry.core()
1010 if core == nil || core.id == "" || d.sessions[core.id] != nil {
1011 return false
1012 }
1013 d.sessions[core.id] = entry
1014 return true
1015}
1016
1017// unregisterSessionLocked removes only the exact registered identity. Caller
1018// holds d.mu.
1019func (d *Daemon) unregisterSessionLocked(entry *session) bool {
1020 if entry == nil {
1021 return false
1022 }
1023 core := entry.core()
1024 if core == nil || d.sessions[core.id] != entry {
1025 return false
1026 }
1027 delete(d.sessions, core.id)
1028 return true
1029}
1030
1031func (d *Daemon) sessionsSnapshotLocked() []*session {
1032 return sessionsSnapshot(d.sessions)
1033}
1034
1035// handleConn reads the first typed message off a fresh connection and routes it.
1036// A context watcher closes the connection on cancellation or handshake timeout.
1037func (d *Daemon) handleConn(tr ports.ServerConnection) {
1038 handshakeCtx, timedOut, finishHandshake := d.newHandshakeContext(d.hardCtx, acceptedHandshakeDeadline(tr))
1039 stopTransport := watchHandshakeTransport(handshakeCtx, tr)
1040 defer finishHandshake()
1041 defer stopTransport()
1042
1043 var first protocol.ClientMessage
1044 err := boundedHandshakeOperation(handshakeCtx, tr, func() error {
1045 var receiveErr error
1046 first, receiveErr = tr.ReceiveClient()
1047 return receiveErr
1048 })
1049 if err != nil {
1050 var failure *protocol.DecodeFailure
1051 if errors.As(err, &failure) {
1052 d.handleInitialDecodeFailure(handshakeCtx, tr, failure)
1053 } else {
1054 err = handshakeContextError(d.hardCtx, timedOut, err)
1055 d.log.Warn("connection closed before hello", "err", err)
1056 }
1057 _ = tr.Close()
1058 return
1059 }
1060 switch message := first.(type) {
1061 case protocol.List:
1062 stopTransport()
1063 finishHandshake()
1064 d.handleList(tr)
1065 case protocol.CommandRequest:
1066 stopTransport()
1067 finishHandshake()
1068 if err := d.handleCommand(tr, message); err != nil {
1069 d.log.Warn("command handler failed", "err", err)
1070 }
1071 case protocol.RemotePreviewWatch:
1072 stopTransport()
1073 finishHandshake()
1074 d.serveRemotePreviewWatch(tr, message)
1075 case protocol.NavigationInventoryRequest:
1076 stopTransport()
1077 finishHandshake()
1078 d.handleNavigationInventory(tr, message)
1079 case protocol.Kill:
1080 stopTransport()
1081 finishHandshake()
1082 d.handleKill(tr, message)
1083 case protocol.Hello:
1084 d.handleHelloWithContext(handshakeCtx, timedOut, stopTransport, finishHandshake, tr, message)
1085 default:
1086 d.log.Warn("hello rejected", "err", "expected hello")
1087 _ = boundedHandshakeOperation(handshakeCtx, tr, func() error {
1088 return tr.SendServer(serverError(protocol.ErrInternal, "expected hello"))
1089 })
1090 stopTransport()
1091 finishHandshake()
1092 _ = tr.Close()
1093 }
1094}
1095
1096func (d *Daemon) handleInitialDecodeFailure(ctx context.Context, tr ports.ServerConnection, failure *protocol.DecodeFailure) {
1097 send := func(message protocol.ServerMessage) {
1098 _ = boundedHandshakeOperation(ctx, tr, func() error { return tr.SendServer(message) })
1099 _ = tr.Close()
1100 }
1101 switch failure.Kind {
1102 case protocol.DecodeMessageHello:
1103 if failure.Version != 0 && failure.Version != protocol.Version {
1104 send(serverError(protocol.ErrVersionMismatch, "protocol version mismatch"))
1105 return
1106 }
1107 send(serverError(protocol.ErrInternal, "malformed hello"))
1108 case protocol.DecodeMessageCommand:
1109 if !failure.HasRequestID {
1110 return
1111 }
1112 code, text := protocol.ErrInternal, "malformed command request"
1113 if failure.Version != 0 && failure.Version != protocol.Version {
1114 code, text = protocol.ErrVersionMismatch, "protocol version mismatch"
1115 }
1116 send(protocol.CommandResult{RequestID: failure.RequestID, Outcome: protocol.CommandFailed, Code: code, Text: text})
1117 case protocol.DecodeMessageKill:
1118 send(serverError(protocol.ErrInternal, "malformed kill request"))
1119 case protocol.DecodeMessageRemotePreview:
1120 send(protocol.RemotePreview{Version: protocol.RemotePreviewSchemaVersion, Status: protocol.RemotePreviewMalformed})
1121 case protocol.DecodeMessageNavigationInventory:
1122 if !failure.HasRequestID {
1123 return
1124 }
1125 status := protocol.NavigationInventoryInvalid
1126 if failure.Version != 0 && failure.Version != protocol.Version {
1127 status = protocol.NavigationInventoryVersionMismatch
1128 }
1129 send(protocol.NavigationInventoryResponse{RequestID: failure.RequestID, Operation: protocol.NavigationInventorySnapshot, Status: status})
1130 default:
1131 send(serverError(protocol.ErrInternal, "expected hello"))
1132 }
1133}
1134
1135// handleList replies with the current session listing and closes the (one-shot
1136// control) connection.
1137func (d *Daemon) handleList(tr ports.ServerConnection) {
1138 defer func() { _ = tr.Close() }()
1139
1140 d.mu.Lock()
1141 infos := make([]protocol.SessionInfo, 0, len(d.sessions)+len(d.inactive))
1142 liveNames := make(map[string]struct{}, len(d.sessions))
1143 for _, s := range d.sessions {
1144 if s == nil {
1145 continue
1146 }
1147 s.mu.Lock()
1148 info := protocol.SessionInfo{
1149 SessionID: string(s.id),
1150 Name: s.name,
1151 State: protocol.SessionUp,
1152 Ephemeral: s.ephemeral,
1153 Tabs: uint16(len(s.tabs)),
1154 // Attached means registered interactive presence, not mere transport
1155 // membership: a suspended-only session is headless to observers.
1156 Attached: sessionInteractivelyAttachedLocked(s),
1157 }
1158 liveNames[s.name] = struct{}{}
1159 s.mu.Unlock()
1160 infos = append(infos, info)
1161 }
1162 for name, inactive := range d.inactive {
1163 if _, live := liveNames[name]; live || !inactive.visible() {
1164 continue
1165 }
1166 state := protocol.SessionDown
1167 if inactive.broken() {
1168 state = protocol.SessionBroken
1169 }
1170 infos = append(infos, protocol.SessionInfo{Name: name, State: state})
1171 }
1172 d.mu.Unlock()
1173
1174 sort.Slice(infos, func(i, j int) bool { return infos[i].Name < infos[j].Name })
1175 _ = d.boundedControlSend(tr, serverSessions(infos))
1176}
1177
1178// handleKill terminates the requested live session or stopped named session,
1179// purges every session (KillAll), or accepts daemon shutdown (KillDaemon).
1180// Every normally decoded request receives exactly one correlated result before
1181// the control connection closes. KillAll leaves the daemon active.
1182func (d *Daemon) handleKill(tr ports.ServerConnection, request protocol.Kill) {
1183 defer func() { _ = tr.Close() }()
1184 send := func(result protocol.KillResult) {
1185 result.RequestID = request.RequestID
1186 d.logKillResultSendFailure(result, d.boundedControlSend(tr, result))
1187 }
1188
1189 switch request.Scope {
1190 case protocol.KillAll:
1191 result := d.purgeAllSessions(protocol.ReasonSessionKilled)
1192 if result.Superseded() {
1193 send(protocol.KillResult{Outcome: protocol.KillOutcomeUnknown, Code: protocol.ErrServerShutdown, Text: "daemon is shutting down"})
1194 return
1195 }
1196 if result.Failed() {
1197 failures := make([]protocol.KillFailure, 0, min(len(result.Failures), purgeSummaryFailureLimit))
1198 for _, failure := range result.Failures[:min(len(result.Failures), purgeSummaryFailureLimit)] {
1199 failures = append(failures, protocol.KillFailure{Class: failure.Class.String(), Name: failure.Name, Text: failure.Err.Error()})
1200 }
1201 send(protocol.KillResult{Outcome: protocol.KillFailed, Code: protocol.ErrInternal, Text: result.summary(), Failures: failures})
1202 return
1203 }
1204 send(protocol.KillResult{Outcome: protocol.KillSucceeded})
1205 return
1206 case protocol.KillDaemon:
1207 send(protocol.KillResult{Outcome: protocol.KillSucceeded})
1208 d.shutdownAll(protocol.ReasonServerShutdown)
1209 return
1210 case protocol.KillSession:
1211 default:
1212 send(protocol.KillResult{Outcome: protocol.KillFailed, Code: protocol.ErrInternal, Text: "invalid kill scope"})
1213 return
1214 }
1215
1216 d.mu.Lock()
1217 target := d.findByNameLocked(request.Name)
1218 if target == nil {
1219 if _, ok := d.inactive[request.Name]; ok {
1220 d.mu.Unlock()
1221 // Stopped sessions use the same catalogue-first, incarnation-second
1222 // deletion order as live and offline purges.
1223 if err := d.retryStoppedPurge(request.Name); err != nil {
1224 d.log.Warn("deleting stopped session failed", "err", err, "session", request.Name)
1225 send(protocol.KillResult{Outcome: protocol.KillFailed, Code: protocol.ErrInternal, Text: "deleting stopped session failed"})
1226 return
1227 }
1228 send(protocol.KillResult{Outcome: protocol.KillSucceeded})
1229 return
1230 }
1231 }
1232 d.mu.Unlock()
1233
1234 if target == nil {
1235 send(protocol.KillResult{Outcome: protocol.KillFailed, Code: protocol.ErrNoSuchSession, Text: "no such session: " + request.Name})
1236 return
1237 }
1238 if err := d.killSession(target, protocol.ReasonSessionKilled, true); err != nil {
1239 if errors.Is(err, errSessionKillParticipantsChanged) {
1240 // The exact session was not removed; a concurrent detach or token
1241 // resume invalidated the teardown snapshot. Report the retryable
1242 // outcome instead of a permanent delete failure.
1243 send(protocol.KillResult{Outcome: protocol.KillFailed, Code: protocol.ErrInternal, Text: sessionKillRetryMessage})
1244 return
1245 }
1246 send(protocol.KillResult{Outcome: protocol.KillFailed, Code: protocol.ErrInternal, Text: "deleting persisted session failed"})
1247 return
1248 }
1249 send(protocol.KillResult{Outcome: protocol.KillSucceeded})
1250}
1251
1252// handleHello runs the attach handshake for direct package callers. Accepted
1253// connections use handleConn, which resolves the optional accepted deadline so
1254// one budget also covers the first frame read; handleHello adopts the same seam
1255// when the connection exposes it. A connection without the seam keeps the
1256// ordinary fresh protocol.HandshakeTimeout budget.
1257func (d *Daemon) handleHello(tr ports.ServerConnection, hello protocol.Hello) {
1258 handshakeCtx, timedOut, finishHandshake := d.newHandshakeContext(context.Background(), acceptedHandshakeDeadline(tr))
1259 stopTransport := watchHandshakeTransport(handshakeCtx, tr)
1260 defer finishHandshake()
1261 defer stopTransport()
1262 d.handleHelloWithContext(handshakeCtx, timedOut, stopTransport, finishHandshake, tr, hello)
1263}
1264
1265// handleHelloWithContext runs the attach handshake: version check, intent
1266// routing, Welcome, guaranteed first paint, then the per-connection input loop.
1267func (d *Daemon) handleHelloWithContext(handshakeCtx context.Context, timedOut <-chan struct{}, stopHandshakeTransport, finishHandshake func(), tr ports.ServerConnection, h protocol.Hello) {
1268 if err := handshakeContextError(d.hardCtx, timedOut, handshakeCtx.Err()); err != nil {
1269 _ = tr.Close()
1270 return
1271 }
1272 sendHandshake := func(message protocol.ServerMessage) error {
1273 err := boundedHandshakeOperation(handshakeCtx, tr, func() error { return tr.SendServer(message) })
1274 if err != nil {
1275 return handshakeContextError(d.hardCtx, timedOut, err)
1276 }
1277 return nil
1278 }
1279 if h.Version != protocol.Version {
1280 d.log.Warn("hello rejected", "err", "protocol version mismatch", "version", h.Version, "expected", protocol.Version, "intent", h.Intent, "session", h.Name)
1281 _ = sendHandshake(serverError(protocol.ErrVersionMismatch, "protocol version mismatch"))
1282 _ = tr.Close()
1283 return
1284 }
1285
1286 sess, ac, rerr := d.routeWithContext(handshakeCtx, h, tr)
1287 if rerr != nil {
1288 d.log.Warn("hello rejected", "err", rerr, "intent", h.Intent, "session", h.Name)
1289 if pe, ok := errors.AsType[*protoErr](rerr); ok {
1290 _ = sendHandshake(serverError(pe.code, pe.text))
1291 } else {
1292 _ = sendHandshake(serverError(protocol.ErrInternal, rerr.Error()))
1293 }
1294 _ = tr.Close()
1295 return
1296 }
1297
1298 welcomeSent := false
1299 //nolint:contextcheck // handshakeCtx is intentionally not propagated: cancellation teardown must complete its geometry and ownership cleanup.
1300 failAttachment := func() {
1301 d.failHandshakeAttachment(sess, ac, tr, welcomeSent)
1302 }
1303 if err := handshakeCtx.Err(); err != nil {
1304 failAttachment()
1305 return
1306 }
1307 expected := ac.transportSnapshot()
1308 welcomeToken := sess.captureAttachmentCapability(ac, tr)
1309 welcomeTicket, admitted := ac.beginAttachmentEffect(welcomeToken)
1310 if expected.transport != tr || !admitted || welcomeToken.ac == nil {
1311 if admitted {
1312 welcomeTicket.End()
1313 }
1314 failAttachment()
1315 return
1316 }
1317 if err := handshakeCtx.Err(); err != nil {
1318 welcomeTicket.End()
1319 failAttachment()
1320 return
1321 }
1322 welcomeDone, welcomeErr := boundedHandshakeOperationTracked(handshakeCtx, tr, func() error {
1323 frame, err := serverWelcome(sess, d.resumeTokenSnapshot(ac))
1324 if err != nil {
1325 return err
1326 }
1327 return ac.sendExpectedTransportForAttachment(expected, frame, welcomeTicket)
1328 })
1329 if welcomeErr != nil {
1330 <-welcomeDone
1331 welcomeTicket.End()
1332 failAttachment()
1333 return
1334 }
1335 welcomeSent = true
1336 // Release Welcome's effect before discovering post-handshake authority so a
1337 // replacement blocked behind the send can publish its generation and lease.
1338 welcomeTicket.End()
1339 postWelcomeToken, postWelcomeTicket, admitted := ac.beginCurrentAttachmentEffectContext(handshakeCtx, sess, tr)
1340 if !admitted {
1341 failAttachment()
1342 return
1343 }
1344 postWelcomeLease := postWelcomeToken.lease
1345 if postWelcomeToken.ac == nil {
1346 postWelcomeTicket.End()
1347 failAttachment()
1348 return
1349 }
1350 postWelcomeRC := sess.renderCoordinator()
1351 if postWelcomeLease != nil && (postWelcomeRC == nil || !postWelcomeRC.markAttachmentReady(postWelcomeLease)) {
1352 postWelcomeTicket.End()
1353 // The attachment was detached while Welcome was in flight; never let
1354 // this stale handshake emit an Output frame.
1355 failAttachment()
1356 return
1357 }
1358 paintToken := sess.captureAttachmentCapability(ac, tr)
1359 painted := make(chan bool, 1)
1360 paintDone, paintErr := boundedHandshakeOperationTracked(handshakeCtx, tr, func() error {
1361 //nolint:contextcheck // firstPaintForTransition is capability-bounded; the surrounding handshake operation owns cancellation.
1362 painted <- d.firstPaintForTransition(paintToken)
1363 return nil
1364 })
1365 if paintErr != nil {
1366 <-paintDone
1367 postWelcomeTicket.End()
1368 failAttachment()
1369 return
1370 }
1371 if !<-painted || handshakeCtx.Err() != nil {
1372 postWelcomeTicket.End()
1373 failAttachment()
1374 return
1375 }
1376 if !d.commitResumeClaim(ac) {
1377 postWelcomeTicket.End()
1378 failAttachment()
1379 return
1380 }
1381 postWelcomeTicket.End()
1382 stopHandshakeTransport()
1383 finishHandshake()
1384 d.runConnLoop(ac)
1385 _ = tr.Close()
1386}
1387
1388// protoErr is a session-level rejection carrying a wire ErrorMsg code.
1389type protoErr struct {
1390 code uint16
1391 text string
1392}
1393
1394func (e *protoErr) Error() string { return e.text }
1395
1396// finishAttach completes an attachment prepared while d.mu is held. Every
1397// caller must hold d.mu on entry; finishAttach transfers ownership by
1398// unlocking d.mu before returning, including every error path. It publishes
1399// terminal and role state before releasing d.mu, then defers coordinator
1400// cleanup so obsolete workers never delay the new handshake.
1401func (d *Daemon) finishAttach(sess *session, tr ports.ServerConnection, sz domain.Size, h protocol.Hello) (*attachedClient, error) {
1402 initialTabIndex := -1
1403 if h.SessionTarget != nil {
1404 var ok bool
1405 initialTabIndex, ok = remoteTargetTabIndexLocked(sess, *h.SessionTarget)
1406 if !ok {
1407 if tr != nil {
1408 _ = tr.Close()
1409 }
1410 d.mu.Unlock()
1411 return nil, &protoErr{protocol.ErrNoSuchTarget, "remote tab no longer exists"}
1412 }
1413 }
1414 if h.PreferredTabID != "" {
1415 // Route memory is a best-effort attachment cursor, not attach authority.
1416 // It overrides point-in-time picker tab metadata when still present and
1417 // otherwise falls back to the session's normal first-tab repair.
1418 initialTabIndex = preferredTabIndex(sess, h.PreferredTabID)
1419 }
1420 terminalCapabilities := terminalcap.Resolve(h.Env, h.Color)
1421 // Kitty graphics are enabled only by the explicit direct-terminal
1422 // declaration in Hello. Environment values remain useful for color and
1423 // diagnostics, but cannot authorize terminal-global graphics side effects.
1424 terminalCapabilities.KittyGraphics = h.KittyDirectGraphics
1425 opts := attachClientOptions{
1426 clientID: h.ClientID,
1427 kittyKeyboard: h.KittyKeyboard,
1428 resumeCapable: true,
1429 maxOutputInFlight: normalizeOutputWindow(h.MaxOutputInFlight),
1430 navigationCapabilities: h.NavigationCapabilities,
1431 terminalFocus: h.TerminalFocus,
1432 clientPID: h.ClientPID,
1433 clientEnv: helloClientEnvironment(h),
1434 terminalCapabilities: terminalCapabilities,
1435 capabilitiesSet: true,
1436 }
1437 geometry := h.Geometry()
1438 if geometry.Size != sz {
1439 geometry = domain.Geometry{Size: sz}
1440 }
1441 ac := d.prepareAttachedClientLocked(sess, tr, geometry, opts)
1442 d.mu.Unlock()
1443 result, err := d.transitionAttachment(attachmentTransitionRequest{
1444 target: sess,
1445 next: ac,
1446 expectedTransport: ac.transportSnapshot(),
1447 activateTargetTab: initialTabIndex >= 0,
1448 targetTabIndex: initialTabIndex,
1449 ready: false,
1450 })
1451 if err != nil {
1452 if ac.output != nil && ac.output.graphicsOutput != nil {
1453 d.retireGraphicsOutput(ac, ac.output.graphicsOutput)
1454 }
1455 if tr != nil {
1456 _ = tr.Close()
1457 }
1458 return nil, err
1459 }
1460 d.finishAttachedClient(sess, ac, opts)
1461 d.deferAttachmentTransitionCleanups(result)
1462 return ac, nil
1463}
1464
1465func preferredTabIndex(sess *session, preferred domain.TabStableID) int {
1466 if sess == nil || preferred == "" {
1467 return -1
1468 }
1469 sess.mu.Lock()
1470 defer sess.mu.Unlock()
1471 for i, candidate := range sess.tabs {
1472 if candidate != nil && domain.TabStableID(candidate.stableID) == preferred {
1473 return i
1474 }
1475 }
1476 return -1
1477}
1478
1479func (d *Daemon) waitForTargetRestore(ctx context.Context, name string) error {
1480 d.mu.Lock()
1481 var (
1482 done chan struct{}
1483 stopped inactiveSession
1484 ok bool
1485 )
1486 if sess := d.findByNameLocked(name); sess != nil {
1487 sess.mu.Lock()
1488 done = sess.restoreDone
1489 sess.mu.Unlock()
1490 } else {
1491 stopped, ok = d.inactive[name]
1492 if !ok || !stopped.visible() {
1493 d.mu.Unlock()
1494 return nil
1495 }
1496 if stopped.restorePending() {
1497 done = stopped.restoreDone
1498 }
1499 }
1500 d.mu.Unlock()
1501
1502 if done != nil {
1503 select {
1504 case <-done:
1505 case <-ctx.Done():
1506 return ctx.Err()
1507 }
1508 }
1509
1510 d.mu.Lock()
1511 defer d.mu.Unlock()
1512 if d.findByNameLocked(name) != nil {
1513 return nil
1514 }
1515 stopped, ok = d.inactive[name]
1516 if !ok || stopped.record.Name == "" {
1517 return nil
1518 }
1519 if stopped.broken() {
1520 return &protoErr{protocol.ErrInternal, "session durable state is broken: " + name}
1521 }
1522 if stopped.record.Committed == nil {
1523 return nil
1524 }
1525 return &protoErr{protocol.ErrInternal, "session was not restored into this daemon: " + name}
1526}
1527
1528// route resolves a Hello to a session and a freshly attached client, creating
1529// the session for ephemeral/new intents. Direct package callers retain the
1530// daemon lifetime context; inbound handshakes use routeWithContext.
1531func (d *Daemon) validateExactSessionTargetLocked(target protocol.ExactSessionTarget) error {
1532 if sess := d.findByNameLocked(target.SessionName); sess != nil {
1533 if sess.incarnation != target.LifecycleID {
1534 return &protoErr{protocol.ErrNoSuchSession, "session lifecycle has changed: " + target.SessionName}
1535 }
1536 return nil
1537 }
1538 stopped, ok := d.inactive[target.SessionName]
1539 if !ok || !stopped.visible() || stopped.incarnation != target.LifecycleID {
1540 return &protoErr{protocol.ErrNoSuchSession, "no such session lifecycle: " + target.SessionName}
1541 }
1542 return nil
1543}
1544
1545func (d *Daemon) validateExactSessionTarget(ctx context.Context, target protocol.ExactSessionTarget) error {
1546 if err := target.Validate(); err != nil {
1547 return &protoErr{protocol.ErrNoSuchSession, "invalid exact session target"}
1548 }
1549 if err := d.waitForTargetRestore(ctx, target.SessionName); err != nil {
1550 return err
1551 }
1552
1553 d.mu.Lock()
1554 defer d.mu.Unlock()
1555 return d.validateExactSessionTargetLocked(target)
1556}
1557
1558func (d *Daemon) route(h protocol.Hello, tr ports.ServerConnection) (*session, *attachedClient, error) {
1559 ctx := d.serveCtx
1560 if ctx == nil {
1561 ctx = context.Background()
1562 }
1563 return d.routeWithContext(ctx, h, tr)
1564}
1565
1566func (d *Daemon) routeWithContext(ctx context.Context, h protocol.Hello, tr ports.ServerConnection) (*session, *attachedClient, error) {
1567 if ctx == nil {
1568 ctx = context.Background()
1569 }
1570 if err := ctx.Err(); err != nil {
1571 return nil, nil, err
1572 }
1573 sz := h.Size
1574 if !sz.Valid() {
1575 return nil, nil, &protoErr{protocol.ErrInternal, "invalid terminal size"}
1576 }
1577 // The accepting side's provisioned admission, when present, is the authority
1578 // this Hello is validated against before any restore, creation, resume
1579 // claim, ownership change, or environment mutation. A connection without
1580 // that seam receives the standard Hello validation and gains no admission
1581 // exception, so a forged Hello can never widen what it is allowed to do.
1582 admission, admitted := sessionHelloAdmission(tr)
1583 if admitted {
1584 if err := validateSessionHelloAdmission(h, admission); err != nil {
1585 return nil, nil, err
1586 }
1587 if admission.Admission == ports.BrokerAdmissionExact && h.ResumeToken != 0 {
1588 if err := d.validateResumeAdmittedTarget(h.ResumeToken, admission.Target); err != nil {
1589 return nil, nil, err
1590 }
1591 }
1592 }
1593 if h.Intent == protocol.IntentResume && h.ResumeToken == 0 {
1594 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "resume token is required"}
1595 }
1596 if h.ExactTarget != nil && h.ResumeToken == 0 && h.Name != h.ExactTarget.SessionName {
1597 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "exact session target name mismatch"}
1598 }
1599 // A remote exact-target handoff is an admitted transition like a local
1600 // create/restore: it reserves purge admission before dispatch, so a Hello
1601 // arriving during a KillAll waits on the gate exactly as a local route does
1602 // instead of being rejected outright.
1603 if h.SessionTarget != nil && h.ResumeToken == 0 {
1604 if err := d.acquirePurgeAdmission(ctx); err != nil {
1605 return nil, nil, err
1606 }
1607 defer d.releasePurgeAdmission()
1608 return d.routeRemoteTargetWithContext(ctx, h, tr)
1609 }
1610 if h.ExactTarget != nil && h.ResumeToken == 0 {
1611 if err := d.validateExactSessionTarget(ctx, *h.ExactTarget); err != nil {
1612 return nil, nil, err
1613 }
1614 }
1615
1616 // A non-zero token is an authoritative resume credential. If it is unknown,
1617 // expired, or raced with lifecycle teardown, fail closed instead of routing
1618 // the Hello as an ordinary attach that could create or replace ownership.
1619 // The one legitimate pre-park race is a still-active same-client credential
1620 // for the requested session; hand that into the park/resume lifecycle.
1621 if h.ResumeToken != 0 {
1622 d.mu.Lock()
1623 parkedAtStart := d.resume.parkedFor(h.ResumeToken)
1624 d.mu.Unlock()
1625 if parkedAtStart == nil {
1626 if sess, ac, ok, err := d.resumeLiveAttachment(h, tr, sz); err != nil {
1627 if errors.Is(err, errResumeTokenLifecycleRace) {
1628 // Live recovery parked then lost a competing resumeParked
1629 // race; keep the fail-closed wire response instead of
1630 // leaking the internal sentinel to handleHello as ErrInternal.
1631 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "resume token is no longer valid"}
1632 }
1633 return nil, nil, err
1634 } else if ok {
1635 return sess, ac, nil
1636 }
1637 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "resume token is no longer valid"}
1638 }
1639 if sess, ac, ok, err := d.resumeParked(h, tr, sz); err == nil {
1640 if ok {
1641 return sess, ac, nil
1642 }
1643 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "resume token is no longer valid"}
1644 } else if errors.Is(err, errResumeTokenLifecycleRace) {
1645 // The parked entry was replaced while this handshake waited for
1646 // its send lock. Fail closed on the original credential rather
1647 // than falling through to ordinary attach/create routing.
1648 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "resume token is no longer valid"}
1649 } else {
1650 return nil, nil, err
1651 }
1652 }
1653 if h.Intent == protocol.IntentResume || h.Intent == protocol.IntentAttach {
1654 if err := d.waitForTargetRestore(ctx, h.Name); err != nil {
1655 return nil, nil, err
1656 }
1657 }
1658 // A daemon-owned ephemeral Hello without an exact remote target is refused by the daemon. An authenticated remote admission that names the
1659 // creation is the one exception, and it is granted only under a validated
1660 // remote admission; a connection without one never gains it.
1661 if !admitted && h.EnvironmentPolicy == protocol.EnvironmentPolicyDaemonOwned && h.SessionTarget == nil &&
1662 h.Intent == protocol.IntentEphemeral {
1663 return nil, nil, &protoErr{protocol.ErrNoSuchTarget, "daemon-owned environment requires an exact remote target"}
1664 }
1665 // KillAll admission gate: a purge owns the exact lifecycle set it captured,
1666 // so a Hello arriving during it waits here and is then admitted as a create
1667 // or restore after the purge, never inserted into the set being removed.
1668 // This is transient and re-opened by the purge; it is not daemon closing.
1669 if err := d.acquirePurgeAdmission(ctx); err != nil {
1670 return nil, nil, err
1671 }
1672 defer d.releasePurgeAdmission()
1673 d.mu.Lock()
1674 // Shutdown/create interlock: once an explicit shutdown has begun
1675 // (shutdownAll started) no new session may be created and no attach may
1676 // proceed — the teardown snapshot has already been (or is being) taken, so
1677 // anything inserted now would leak its PTY and hang Serve. An empty registry
1678 // alone is not shutdown, and a KillAll purge is gated by admission above.
1679 if d.closing {
1680 d.mu.Unlock()
1681 return nil, nil, &protoErr{protocol.ErrServerShutdown, "daemon is shutting down"}
1682 }
1683 // The first exact-target check happens before restore I/O. Recheck while
1684 // holding d.mu so a same-name lifecycle replacement cannot slip between
1685 // validation and attachment creation.
1686 if h.ExactTarget != nil && h.ResumeToken == 0 {
1687 if err := d.validateExactSessionTargetLocked(*h.ExactTarget); err != nil {
1688 d.mu.Unlock()
1689 return nil, nil, err
1690 }
1691 }
1692 switch h.Intent {
1693 case protocol.IntentEphemeral:
1694 name := d.allocEphemeralNameLocked()
1695 // A daemon-owned creation (an authenticated remote admission) uses the
1696 // daemon's own environment and home rather than any client value; a
1697 // client-owned creation (local) uses the admitted client environment and
1698 // working directory. The Hello fields are already validated to match the
1699 // admission, so this mirrors the named-creation ownership rule below.
1700 cwd, env := h.Cwd, h.Env
1701 if h.EnvironmentPolicy == protocol.EnvironmentPolicyDaemonOwned {
1702 cwd, env = d.dirOrHome(""), copyEnvironment(d.baseEnv)
1703 }
1704 sess, err := d.createSessionLockedWithMode(name, true, cwd, h.Geometry(), env)
1705 if err != nil {
1706 d.mu.Unlock()
1707 return nil, nil, err
1708 }
1709 ac, err := d.finishRouteAttach(sess, tr, sz, h, true, true)
1710 return sess, ac, err
1711
1712 case protocol.IntentNew:
1713 if h.Name == "" {
1714 d.mu.Unlock()
1715 return nil, nil, &protoErr{protocol.ErrInvalidSessionName, "empty session name"}
1716 }
1717 if err := domain.ValidateSessionName(h.Name); err != nil {
1718 d.mu.Unlock()
1719 return nil, nil, &protoErr{protocol.ErrInvalidSessionName, err.Error()}
1720 }
1721 if d.nameLiveOrStoppedLocked(h.Name) {
1722 d.mu.Unlock()
1723 return nil, nil, &protoErr{protocol.ErrNameTaken, "session name already in use: " + h.Name}
1724 }
1725 cwd, env := h.Cwd, h.Env
1726 if h.EnvironmentPolicy == protocol.EnvironmentPolicyDaemonOwned {
1727 // A remote CNS destination owns shell startup just like a picker
1728 // attach. Client paths may exist here but belong to another user.
1729 cwd, env = d.dirOrHome(""), copyEnvironment(d.baseEnv)
1730 }
1731 sess, err := d.createSessionLockedWithMode(h.Name, false, cwd, h.Geometry(), env)
1732 if err != nil {
1733 d.mu.Unlock()
1734 return nil, nil, err
1735 }
1736 ac, err := d.finishRouteAttach(sess, tr, sz, h, true, true)
1737 return sess, ac, err
1738
1739 case protocol.IntentAttach:
1740 sess := d.findByNameLocked(h.Name)
1741 created := false
1742 if sess == nil {
1743 stopped, ok := d.inactive[h.Name]
1744 if !ok || !stopped.canResume() {
1745 d.mu.Unlock()
1746 return nil, nil, &protoErr{protocol.ErrNoSuchSession, "no such resumable session: " + h.Name}
1747 }
1748 cwd := d.dirOrHome(stopped.cwd)
1749 env := h.Env
1750 daemonOwned := h.EnvironmentPolicy == protocol.EnvironmentPolicyDaemonOwned
1751 if daemonOwned {
1752 env = copyEnvironment(d.baseEnv)
1753 }
1754 var err error
1755 sess, err = d.resumeInactiveSessionLocked(h.Name, cwd, h.Geometry(), env, stopped, stopped.tabNames)
1756 if err != nil {
1757 d.mu.Unlock()
1758 return nil, nil, err
1759 }
1760 if daemonOwned {
1761 // Like a snapshot restore, the resumed session starts from the
1762 // daemon's environment until a local client attaches.
1763 markEnvironmentProvisional(sess)
1764 }
1765 created = true
1766 }
1767 ac, err := d.finishRouteAttach(sess, tr, sz, h, created, false)
1768 return sess, ac, err
1769
1770 default:
1771 d.mu.Unlock()
1772 return nil, nil, &protoErr{protocol.ErrInternal, "unknown intent"}
1773 }
1774}