1package daemon
2
3import (
4 "errors"
5 "slices"
6
7 renderer "github.com/bnema/vev-vt"
8 "github.com/bnema/vev/internal/domain"
9 "github.com/bnema/vev/internal/ports"
10 "github.com/bnema/vev/internal/protocol"
11 "github.com/bnema/vev/internal/usecase/layout"
12 "github.com/bnema/vev/internal/usecase/notices"
13 "github.com/bnema/vev/internal/usecase/palette"
14 "github.com/bnema/vev/internal/usecase/prompt"
15 themeui "github.com/bnema/vev/internal/usecase/theme"
16 "github.com/bnema/vev/internal/usecase/ui"
17 "github.com/bnema/vev/internal/usecase/visualsearch"
18)
19
20// composeCacheInput is an attachment-local value snapshot. composeFrame never
21// retains or accesses the attachment that owns it.
22// renderStageHooks are optional observability hooks. capture and compose run
23// after their result is available, and emit after prepare plus transport success
24// (including a successful no-byte emission); those hooks run while sendMu is
25// held. Failed attempts count for capture/compose but never for emit.
26// handoffRebase marks the boundary immediately before a handoff acquires sendMu
27// to rebase attachment-owned output state, so it intentionally runs unlocked.
28type renderStageHooks struct {
29 capture func()
30 compose func()
31 emit func()
32 handoffRebase func()
33}
34
35type composeCacheInput struct {
36 valid bool
37 frame renderer.Frame
38 layoutFingerprint string
39 titleGenerations map[layout.PaneID]uint64
40 damage []renderer.Damage
41 floatingVisible bool
42 floatingFocused bool
43 floatingGeneration uint64
44 floatingGeometry floatingGeometry
45 floatingTitleGeneration uint64
46 bars barCache
47 toastFootprints []domain.Rect
48 theme themeui.Theme
49 styleGeneration uint64
50 copyViewport copyViewportState
51}
52
53type composedRenderFrame struct {
54 frame renderer.Frame
55 damage []renderer.Damage
56 cursor cursorOut
57 cache composeCacheInput
58 reset bool
59}
60
61// composeFrame is pure with respect to daemon ownership: it consumes only the
62// capture, the last committed cache, and an independent attachment-owned
63// scratch cache. It returns a new cache without mutating committed.
64const inactivePaneForegroundDimming = 55
65
66// clearOutsideLayout blanks the content cells that the shared layout does not
67// cover. A window larger than the shared session geometry reuses its previous
68// frame, so without this the cells of a wider or taller earlier layout stay on
69// screen.
70func clearOutsideLayout(frame renderer.Frame, content, area domain.Rect) {
71 blank := renderer.BlankCell()
72 for y := content.Y; y < content.Y+content.Height; y++ {
73 start := area.Width
74 if y-content.Y >= area.Height {
75 start = 0
76 }
77 frame.FillRow(y, content.X+start, content.X+content.Width, blank)
78 }
79}
80
81func composeFrame(state capturedRenderState, in composeCacheInput, scratchIn ...composeCacheInput) composedRenderFrame {
82 scratch := composeCacheInput{}
83 if len(scratchIn) > 0 {
84 scratch = scratchIn[0]
85 }
86 width, rows := state.layout.area.Width, state.layout.area.Height
87 if state.window.Valid() {
88 window := contentSize(state.window)
89 width, rows = window.Cols, window.Rows
90 }
91 if width <= 0 || rows < 0 {
92 return composedRenderFrame{frame: renderer.NewFrame(0, 0), cursor: cursorOut{hidden: true}, reset: state.reset}
93 }
94 // Compose into the alternate attachment-owned buffer. The committed frame is
95 // copied before incremental drawing so prepare/send failures cannot change it.
96 contentY := 1
97 frameHeight := rows + tabChromeRows
98 canReuseFrame := scratch.frame.Width == width && scratch.frame.Height == frameHeight
99 frame := scratch.frame
100 if !canReuseFrame {
101 frame = renderer.NewFrame(width, frameHeight)
102 }
103 if in.frame.Width == width && in.frame.Height == frameHeight {
104 if state.overlays.copyMode != nil {
105 // Compact Clone preserves page-local style IDs. Re-interning every
106 // cell into scratch costs more than a structural copy while scrolling.
107 // The clone still isolates committed state from failed publications.
108 frame = in.frame.Clone()
109 } else {
110 for y := 0; y < frame.Height; y++ {
111 for x := range frame.Width {
112 frame.Set(x, y, in.frame.Cell(x, y))
113 }
114 }
115 }
116 }
117 styles := state.styles
118 if styles == (themeui.Styles{}) {
119 // Direct/test-only composition has no applied snapshot; production
120 // capture always supplies immutable styles.
121 styles = fallbackChromeStyles
122 }
123 state.styles = styles
124 defaultDimmer := themeui.NewDimmer(state.theme)
125 neutralBorder := styles.NeutralBorder
126 inactivePaneDimmer := themeui.NewDimmer(state.theme, themeui.WithForegroundDimming(inactivePaneForegroundDimming))
127 // The alternate cache owns these rows; the committed cache remains intact
128 // until prepare/send succeeds. Row extraction would allocate on each paint.
129 topBar := slices.Grow(scratch.bars.top[:0], width)[:width]
130 drawTopBarSnapshot(topBar, state.bars.status, state.bars.attentionFrame, state.bars.topRight, styles)
131 frame.WriteRow(0, 0, topBar)
132 bottomBar := slices.Grow(scratch.bars.bottom[:0], width)[:width]
133 drawStatusBarState(bottomBar, state.bars, styles)
134 frame.WriteRow(rows+1, 0, bottomBar)
135 content := domain.Rect{Y: contentY, Width: width, Height: rows}
136 if state.layout.valid {
137 drawDividers(frame, state.layout.dividers, content.Y, defaultDimmer.Dim(neutralBorder))
138 }
139
140 full := state.reset || !in.valid || in.frame.Width != width || in.frame.Height != frameHeight || in.layoutFingerprint != state.layout.fingerprint || in.theme != state.theme || in.styleGeneration != state.styleGeneration || in.floatingVisible != state.floating.visible
141 if full {
142 clearOutsideLayout(frame, content, state.layout.area)
143 }
144 titles := scratch.titleGenerations
145 if titles == nil {
146 titles = make(map[layout.PaneID]uint64, len(state.panes))
147 }
148 clear(titles)
149 damage := scratch.damage[:0]
150 for _, pane := range state.panes {
151 pl := offsetPlacement(pane.placement, 0, contentY)
152 if pl.TitleBar.Height > 0 {
153 drawCapturedPaneTitleBar(frame, pl, pane.title, pane.focused, styles, neutralBorder, defaultDimmer)
154 if !full && in.titleGenerations[pane.id] != pane.titleGeneration {
155 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: pl.TitleBar.X, Y: pl.TitleBar.Y, Width: pl.TitleBar.Width, Height: pl.TitleBar.Height})
156 }
157 titles[pane.id] = pane.titleGeneration
158 }
159 if !pl.Collapsed && pl.Content.Width > 0 && pl.Content.Height > 0 && (full || len(pane.damage) > 0) {
160 blitPaneFrame(frame, pl.Content, pane.frame, !pane.focused, inactivePaneDimmer)
161 }
162 for _, d := range pane.damage {
163 if d.Kind != renderer.DamageFullRedraw {
164 d.Y += contentY
165 }
166 damage = append(damage, d)
167 }
168 }
169 // Keep the committed cache unadorned. Toasts are composed first so floating
170 // terminals and scoped modals dim them with the rest of the complete frame.
171 baseFrame := frame
172 overlaysActive := state.overlays.active()
173 toastsVisible := len(state.overlays.notices) > 0 || state.overlays.noticeOverflow > 0
174 var toastFootprints []domain.Rect
175 if toastsVisible {
176 frame = baseFrame.Clone()
177 toastFootprints = composeCapturedNotices(state.overlays, frame, state.styles)
178 }
179 if state.floating.visible {
180 var floatingDamage []renderer.Damage
181 frame, floatingDamage = composeCapturedFloatingFrame(floatingComposeInput{
182 baseFrame: frame,
183 baseDamage: damage,
184 floating: state.floating,
185 content: content,
186 theme: state.theme,
187 borderMuted: styles.BorderMuted,
188 borderActive: styles.BorderActive,
189 cache: in,
190 full: full || overlaysActive,
191 })
192 damage = floatingDamage
193 }
194 copyOnly := state.overlays.copyMode != nil && state.overlays.copyActive &&
195 !state.overlays.copySearchActive &&
196 !state.overlays.paletteActive && !state.overlays.promptActive &&
197 !state.overlays.noticesOverlayActive && !state.overlays.resizeActive && !state.floating.visible
198 var copyViewport copyViewportState
199 var scrollDamage []renderer.Damage
200 if copyOnly && !toastsVisible {
201 copyViewport = captureCopyViewport(state, content)
202 if !full {
203 scrollDamage = copyViewportDamage(in.copyViewport, copyViewport, frame)
204 }
205 }
206 if overlaysActive {
207 if scrollDamage != nil && in.copyViewport.frame.Width == width && in.copyViewport.frame.Height == frameHeight {
208 frame = composeScrolledCopyViewport(state, baseFrame, in.copyViewport, copyViewport, scrollDamage)
209 } else {
210 if !toastsVisible && !state.floating.visible {
211 frame = baseFrame.Clone()
212 }
213 frame, damage = composeCapturedCopyMode(state, frame, damage, content)
214 }
215 frame, damage = composeCapturedOverlays(state, frame, damage)
216 }
217 for x := range width {
218 topBar[x] = baseFrame.Cell(x, 0)
219 bottomBar[x] = baseFrame.Cell(x, rows+1)
220 }
221 if !full {
222 if !sameCells(in.bars.top, topBar) {
223 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: 0, Y: 0, Width: width, Height: 1})
224 }
225 if !sameCells(in.bars.bottom, bottomBar) {
226 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: 0, Y: rows + 1, Width: width, Height: 1})
227 }
228 }
229 // The cache stays toast-free. The terminal shadow, in contrast, includes
230 // toasts, so every render damages both the last and current toast coverage.
231 // This restores cells exposed by dismissal and redraws a stable toast over
232 // any underlying pane update without promoting either case to a full frame.
233 if full || overlaysActive {
234 damage = []renderer.Damage{renderer.FullRedraw()}
235 } else {
236 damage = appendToastDamage(damage, in.toastFootprints)
237 damage = appendToastDamage(damage, toastFootprints)
238 }
239 cursorInputs := state.cursor
240 cursorInputs.hiddenByOverlay = cursorInputs.hiddenByOverlay || overlaysActive
241 cursor := desiredCapturedCursor(cursorInputs, contentY)
242 // A plain copy viewport is painted on a clone, never into baseFrame. Keep
243 // that unadorned base reusable between wheel events. Modal/floating paths
244 // retain their conservative invalidation, and copy exit requests a reset.
245 outCache := composeCacheInput{valid: !overlaysActive || copyOnly, frame: baseFrame, layoutFingerprint: state.layout.fingerprint, theme: state.theme, styleGeneration: state.styleGeneration, titleGenerations: titles, damage: damage, toastFootprints: append(scratch.toastFootprints[:0], toastFootprints...), floatingVisible: state.floating.visible, floatingFocused: state.floating.focused, floatingGeneration: state.floating.generation, floatingGeometry: state.floating.geometry.translate(content.X, content.Y), floatingTitleGeneration: state.floating.titleGeneration, bars: scratch.bars}
246 outCache.bars = barCache{top: topBar, bottom: bottomBar}
247 if copyViewport.document != nil {
248 copyViewport.frame = frame
249 outCache.copyViewport = copyViewport
250 }
251 if scrollDamage != nil {
252 damage = scrollDamage
253 }
254 // A copy viewport is ordinary terminal content, not a new output epoch.
255 // Keep conservative resets for other overlays and explicit resynchronization.
256 return composedRenderFrame{frame: frame, damage: damage, cursor: cursor, cache: outCache, reset: state.reset || (overlaysActive && !copyOnly)}
257}
258
259func drawCapturedPaneTitleBar(frame renderer.Frame, pl layout.Placement, title string, focused bool, styles themeui.Styles, neutralBorder renderer.Style, dimmer themeui.Dimmer) {
260 if pl.TitleBar.Y < 0 || pl.TitleBar.Y >= frame.Height {
261 return
262 }
263 style := styles.StatusBar
264 if !focused {
265 style = dimmer.Dim(neutralBorder)
266 }
267 for x := max(pl.TitleBar.X, 0); x < min(pl.TitleBar.X+pl.TitleBar.Width, frame.Width); x++ {
268 frame.Set(x, pl.TitleBar.Y, renderer.Cell{Rune: ' ', Style: style})
269 }
270 ui.DrawText(frame, max(pl.TitleBar.X, 0), pl.TitleBar.Y, min(pl.TitleBar.X+pl.TitleBar.Width, frame.Width), title, style)
271}
272
273func desiredCapturedCursor(c capturedCursorInputs, contentY int) cursorOut {
274 if !c.renderable || c.hiddenByOverlay || !c.visible {
275 return cursorOut{hidden: true}
276 }
277 style := c.style
278 if !c.hasStyle {
279 style = 1
280 }
281 return cursorOut{valid: true, row: c.content.Y + contentY + c.row, col: c.content.X + c.col, style: style, hasStyle: true}
282}
283
284func captureOverlayLayers(state *capturedRenderState, snap *overlayRenderSnapshot, paletteCfg domain.PaletteConfig) {
285 if state == nil || snap == nil {
286 return
287 }
288 o := &state.overlays
289 o.copyActive, o.copySearchActive, o.paletteActive, o.promptActive = snap.copyActive, snap.copySearchModel != nil, snap.paletteActive, snap.promptActive
290 o.noticesOverlayActive = snap.noticesOverlayActive
291 o.copyMode = snap.copyMode
292 o.notices, o.noticeOverflow = snap.notices, snap.noticeOverflow
293 if snap.copyPane != nil {
294 o.copyPaneID = snap.copyPane.id
295 }
296 styles := state.styles
297 if styles == (themeui.Styles{}) {
298 styles = fallbackChromeStyles
299 }
300 rows := state.layout.area.Height
301 rows += tabChromeRows
302 size := domain.Size{Cols: state.layout.area.Width, Rows: rows}
303 if snap.copySearchModel != nil {
304 presentation := copySearchModal.Resolve(size)
305 o.copySearch = capturedModal{active: true, title: copySearchModal.Title, presentation: presentation, focused: true}
306 o.copySearch.inner = snap.copySearchModel.RenderStyled(rectSize(presentation.Inner), visualsearch.RenderStyles{Base: styles.PromptBase, Selection: styles.SearchSelection})
307 }
308 if snap.noticesOverlayActive && snap.noticesOverlayModel != nil {
309 presentation := noticesModal.Resolve(size)
310 o.noticesOverlay = capturedModal{active: true, title: noticesModal.Title, presentation: presentation, focused: true}
311 renderStyles := notices.RenderStyles{Background: styles.PickerBase, Base: styles.PickerBase, Selection: styles.PickerSelection, Text: styles.PickerBase, SelectionText: styles.PickerSelectionName, Muted: styles.PickerDescription, SelectionMuted: styles.PickerSelectionMuted}
312 o.noticesOverlay.inner = snap.noticesOverlayModel.Render(rectSize(presentation.Inner), renderStyles)
313 }
314 if snap.paletteActive && snap.paletteModel != nil {
315 modal := paletteModalFor(paletteCfg)
316 presentation := modal.Resolve(size)
317 o.palette = capturedModal{active: true, title: modal.Title, presentation: presentation, focused: true}
318 guidance := ""
319 if snap.paletteHints != nil {
320 guidance = snap.paletteHints.Feedback
321 }
322 o.paletteGuidance = snap.paletteFeedback
323 o.palette.inner = snap.paletteModel.Render(rectSize(presentation.Inner), palette.RenderOptions{Styles: palette.RenderStyles{Base: styles.PickerBase, Row: styles.PickerBase, Selection: styles.PickerSelection, Description: styles.PickerDescription, SelectionDescription: styles.PickerSelectionMuted}, Guidance: guidance, Preview: snap.palettePreview, Feedback: snap.paletteFeedback})
324 }
325 if snap.promptActive && snap.promptModel != nil {
326 modal := promptModalFor(snap.promptModel.Title())
327 presentation := modal.Resolve(size)
328 o.prompt = capturedModal{active: true, title: modal.Title, presentation: presentation, focused: true}
329 o.prompt.inner = snap.promptModel.RenderStyled(rectSize(presentation.Inner), prompt.RenderStyles{Base: styles.PromptBase, Selection: styles.SurfaceActive})
330 }
331 state.cursor.hiddenByOverlay = o.active()
332}
333
334func composeCapturedCopyMode(state capturedRenderState, frame renderer.Frame, damage []renderer.Damage, content domain.Rect) (renderer.Frame, []renderer.Damage) {
335 o := state.overlays
336 if !o.copyActive {
337 return frame, damage
338 }
339 target := capturedCopyTarget(state, content)
340 return composeCopyClientFrame(o.copyMode, target, frame, state.styles)
341}
342
343func capturedCopyTarget(state capturedRenderState, content domain.Rect) domain.Rect {
344 o := state.overlays
345 target := domain.Rect{}
346 if state.floating.visible && (o.copyPaneID == "" || o.copyPaneID == state.floating.pane.id) {
347 target = state.floating.geometry.translate(content.X, content.Y).Inner
348 }
349 if target.Width == 0 {
350 id := o.copyPaneID
351 if id == "" {
352 id = state.layout.focus
353 }
354 for _, p := range state.panes {
355 if p.id == id && !p.placement.Collapsed {
356 target = p.placement.Content
357 target.Y += content.Y
358 break
359 }
360 }
361 }
362 return target
363}
364
365func composeCapturedOverlays(state capturedRenderState, frame renderer.Frame, damage []renderer.Damage) (renderer.Frame, []renderer.Damage) {
366 o := state.overlays
367 // Paint in reverse keyboard priority so the same layer that owns input is
368 // visually topmost: prompt > palette > notices > copy search.
369 for _, modal := range []capturedModal{o.copySearch, o.noticesOverlay, o.palette, o.prompt} {
370 if !modal.active {
371 continue
372 }
373 applyOverlayBackdrop(frame, state.theme)
374 border := state.styles.BorderMuted
375 if modal.focused {
376 border = state.styles.BorderActive
377 }
378 (ui.Modal{Title: modal.title}).CompositePresentation(frame, modal.presentation, border, state.styles.PickerBase)
379 copyModalInner(frame, modal.presentation.Inner, modal.inner)
380 damage = []renderer.Damage{renderer.FullRedraw()}
381 }
382 return frame, damage
383}
384
385// copyModalInner copies a captured model frame into its resolved destination.
386// Both source and destination are clipped so degenerate presentations remain
387// safe immutable composition inputs.
388func copyModalInner(dst renderer.Frame, target domain.Rect, src renderer.Frame) {
389 left := max(target.X, 0)
390 top := max(target.Y, 0)
391 right := min(target.X+target.Width, dst.Width)
392 bottom := min(target.Y+target.Height, dst.Height)
393 if left >= right || top >= bottom {
394 return
395 }
396
397 sourceX := left - target.X
398 sourceY := top - target.Y
399 width := min(right-left, src.Width-sourceX)
400 height := min(bottom-top, src.Height-sourceY)
401 if width <= 0 || height <= 0 {
402 return
403 }
404 for y := range height {
405 for x := range width {
406 dst.Set(left+x, top+y, src.Cell(sourceX+x, sourceY+y))
407 }
408 }
409}
410
411func composeCapturedNotices(overlays capturedOverlayRenderState, frame renderer.Frame, styles themeui.Styles) []domain.Rect {
412 if len(overlays.notices) == 0 && overlays.noticeOverflow == 0 {
413 return nil
414 }
415 views := make([]ui.NoticeView, len(overlays.notices))
416 for i, n := range overlays.notices {
417 views[i] = ui.NoticeView{Severity: n.Severity, Title: n.Code.String(), Message: n.Message, Count: n.Count}
418 }
419 return ui.ComposeNotices(frame, views, overlays.noticeOverflow, noticeStylesFrom(styles))
420}
421
422func appendToastDamage(damage []renderer.Damage, footprints []domain.Rect) []renderer.Damage {
423 for _, footprint := range footprints {
424 if footprint.Width > 0 && footprint.Height > 0 {
425 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: footprint.X, Y: footprint.Y, Width: footprint.Width, Height: footprint.Height})
426 }
427 }
428 return damage
429}
430
431// noticeStylesFrom picks the toast box color per severity from the theme's
432// chrome roles. Warn uses the dedicated BorderWarn role so it reads as
433// distinct from Info instead of sharing BorderMuted with it.
434func noticeStylesFrom(styles themeui.Styles) ui.NoticeStyles {
435 return ui.NoticeStyles{
436 Text: styles.PickerBase,
437 BoxError: styles.BorderActive,
438 BoxWarn: styles.BorderWarn,
439 BoxInfo: styles.BorderMuted,
440 }
441}
442
443// commitDamageReceipts acknowledges only snapshots that reached the client.
444// sendMu serializes attachment transactions; panes are locked individually so
445// no pane lock is held while another is acquired. A stale generation is
446// intentionally acknowledged too: Screen conservatively leaves FullRedraw for
447// the next transaction.
448func commitDamageReceipts(receipts []damageReceipt) {
449 for _, receipt := range receipts {
450 if receipt.pane != nil {
451 receipt.pane.mu.Lock()
452 receipt.pane.screen.AcknowledgeDamage(receipt.generation)
453 receipt.pane.mu.Unlock()
454 continue
455 }
456 }
457}
458
459// frameFollowUp is the work a frame publication leaves for after the
460// attachment's sendMu is released: notices, repaints, and send-error cleanup
461// may re-enter rendering or take session locks, so they never run under it.
462type frameFollowUp struct {
463 prepareErr error
464 sendErr error
465 sendTr ports.ServerConnection
466 warnGraphics bool
467}
468
469// publishFrameLocked is the sole side-effecting half of the pipeline: it
470// revalidates ownership, prepares, sends, and commits or aborts one captured
471// frame. The caller holds ac.sendMu for the complete capture/compose/publish
472// transaction; publishFrameLocked never releases it. It reports false when the
473// frame was rejected before preparation. The returned follow-up must be passed
474// to settleFrame after sendMu is released.
475func (d *Daemon) publishFrameLocked(entry *session, ac *attachedClient, state *capturedRenderState, composed composedRenderFrame, marks *runtimeMarkBatch) (frameFollowUp, bool) {
476 if entry == nil || entry.core() == nil || ac == nil || state == nil {
477 return frameFollowUp{}, false
478 }
479 entry.core().mu.Lock()
480 _, owned := entry.core().attachments[ac]
481 position := protocol.RoutePosition{
482 Target: state.route.Target,
483 ActiveTabID: state.view.tabID,
484 }
485 entry.core().mu.Unlock()
486 if marks.attachmentEffect != nil {
487 if !marks.attachmentEffect.current() || state.attachment != ac {
488 return frameFollowUp{}, false
489 }
490 } else {
491 if !owned || state.attachment != ac || ac.currentAttachmentSession() != entry {
492 return frameFollowUp{}, false
493 }
494 if state.lease != nil {
495 rc := attachmentRenderCoordinator(entry)
496 if rc == nil || state.lease.attachment != ac || !rc.leaseCurrent(state.lease, true) {
497 return frameFollowUp{}, false
498 }
499 }
500 }
501 endDiff := marks.span(ports.RuntimeDiffStart, ports.RuntimeDiffEnd, 0)
502 prepared, err := ac.output.prepareFrame(d, state, composed.frame, composed.damage, composed.reset, composed.cursor)
503 var data []byte
504 if prepared != nil {
505 data = prepared.data
506 }
507 endDiff(0, err == nil)
508 if err != nil {
509 return frameFollowUp{prepareErr: err}, true
510 }
511 var sendTr ports.ServerConnection
512 var sendErr error
513 rc := attachmentRenderCoordinator(entry)
514 confirmUIFence := rc != nil && rc.needsUIFence(state.lease, state.uiFence)
515 suppressedGraphics := state.suppressedGraphics && !ac.terminalCapabilities.SupportsKittyGraphics()
516 if len(data) > 0 || prepared.ansi.context != nil {
517 sendTransport := ac.transportSnapshot()
518 sendTr = sendTransport.transport
519 endEmit := marks.span(ports.RuntimeEmitStart, ports.RuntimeEmitEnd, uint64(len(data)))
520 if sendTr == nil {
521 sendErr = errors.New("client transport is nil")
522 } else {
523 send := sendTr.SendOutput
524 if sendTr.Capabilities().AsyncSend {
525 send = sendTr.SendOutputAsync
526 }
527 interruptible := false
528 if marks.attachmentEffect != nil {
529 interruptible = marks.attachmentEffect.beginTransportSend(sendTransport)
530 if !interruptible {
531 sendErr = errAttachmentTransition
532 }
533 }
534 if sendErr == nil {
535 if len(data) > 0 {
536 sendErr = prepared.send(ac.echoAck.Load(), send)
537 } else {
538 sendErr = prepared.publishNoBytes(confirmUIFence, func(update protocol.UIViewUpdate) error {
539 if sendTr.Capabilities().AsyncSend {
540 return sendTr.SendServerAsync(update)
541 }
542 return sendTr.SendServer(update)
543 })
544 }
545 }
546 if marks.attachmentEffect != nil && interruptible {
547 if sendErr != nil {
548 marks.attachmentEffect.reportTransportFailure(sendTransport)
549 }
550 marks.attachmentEffect.endTransportSend()
551 }
552 }
553 emitted := sendErr == nil && prepared.sent()
554 endEmit(uint64(len(data)), emitted)
555 if sendErr == nil && !emitted {
556 return frameFollowUp{}, true
557 }
558 if sendErr != nil {
559 prepared.abort()
560 }
561 }
562 if sendErr == nil {
563 if len(data) == 0 {
564 prepared.commitNoSend()
565 if !prepared.sent() {
566 return frameFollowUp{}, true
567 }
568 }
569 ac.afterFrame.emitted(state.frameCapture)
570 // Publish only after output preparation and transport emission both
571 // succeed. A cross-session transition may publish concurrently, but its
572 // mandatory first-paint rebase waits for sendMu and therefore follows this
573 // completed output transaction.
574 ac.render.commitComposition(composed.cache)
575
576 // A successful no-byte emission also commits: its renderer shadow still
577 // represents the captured frame. Lock panes only under sendMu and with no
578 // session guard held.
579 commitDamageReceipts(state.receipts)
580 if ac.renderStages.emit != nil {
581 ac.renderStages.emit()
582 }
583
584 if position.ActiveTabID != "" && position != ac.output.lastRoutePosition {
585 if positionValidateErr := position.Validate(); positionValidateErr != nil {
586 d.log.Error("validate route position", "err", positionValidateErr)
587 } else {
588 sendTransport := ac.transportSnapshot()
589 sendTr = sendTransport.transport
590 interruptible := false
591 if marks.attachmentEffect != nil {
592 interruptible = marks.attachmentEffect.beginTransportSend(sendTransport)
593 if !interruptible {
594 sendErr = errAttachmentTransition
595 }
596 }
597 if sendErr == nil {
598 if sendTr == nil {
599 sendErr = errors.New("client transport is nil")
600 } else if sendTr.Capabilities().AsyncSend {
601 sendErr = sendTr.SendServerAsync(position)
602 } else {
603 sendErr = sendTr.SendServer(position)
604 }
605 }
606 if marks.attachmentEffect != nil && interruptible {
607 if sendErr != nil {
608 marks.attachmentEffect.reportTransportFailure(sendTransport)
609 }
610 marks.attachmentEffect.endTransportSend()
611 }
612 if sendErr == nil {
613 ac.output.lastRoutePosition = position
614 }
615 }
616 }
617 if sendErr == nil && rc != nil && prepared.ansi.boundary.ViewPublication != 0 &&
618 (marks.attachmentEffect == nil || marks.attachmentEffect.current()) {
619 if pending := rc.retireUIFence(state.lease, state.uiFence); pending != nil {
620 receipt := prepared.ansi.boundary
621 receipt.ActionID = pending.actionID
622 sendTransport := ac.transportSnapshot()
623 sendTr = sendTransport.transport
624 sendErr = sendUIReceiptLocked(marks.attachmentEffect, sendTransport, receipt)
625 if sendErr == nil {
626 rc.finishUIFence(state.lease, pending)
627 } else {
628 rc.failUIFence(state.lease, pending)
629 }
630 }
631 }
632 }
633 return frameFollowUp{sendErr: sendErr, sendTr: sendTr, warnGraphics: suppressedGraphics}, true
634}
635
636// settleFrame runs a publication's follow-up with sendMu released and no
637// attachment, session, tab, or pane lock held.
638func (d *Daemon) settleFrame(entry *session, ac *attachedClient, marks *runtimeMarkBatch, f frameFollowUp) {
639 if f.prepareErr != nil {
640 core := entry.core()
641 core.mu.Lock()
642 sessionName := core.name
643 core.mu.Unlock()
644 d.log.Error("render draw failed", "err", f.prepareErr, "session", sessionName)
645 // Without a coordinator reportError repaints synchronously. Suppress only
646 // that nested notice repaint; leave the guard before returning so a later,
647 // independent failed transaction can still notify the user.
648 if entry.renderCoordinator() == nil {
649 if !ac.prepareFailureFallback.CompareAndSwap(false, true) {
650 return
651 }
652 d.reportError(entry, domain.UserErr(domain.NoticeInternal, "display update failed", f.prepareErr))
653 ac.prepareFailureFallback.Store(false)
654 return
655 }
656 d.reportError(entry, domain.UserErr(domain.NoticeInternal, "display update failed", f.prepareErr))
657 // Notices are session-scoped, while the attachment repaint still needs
658 // to redraw its chrome after a failed transaction.
659 d.invalidateRender(entry, ac, true, "render_pipeline.go:prepare-failed")
660 return
661 }
662 if f.warnGraphics && d.warnUnsupportedGraphics(ac) {
663 d.repaintForNotice(ac)
664 }
665 if f.sendErr != nil {
666 // A transport failure may invalidate the role gate. Release this render's
667 // admission first. Detachment freezes the gate and therefore cannot mutate
668 // ownership until any enclosing admitted operation has also ended.
669 if marks.attachmentEffect == nil {
670 d.detachOnSendError(entry, ac, f.sendTr)
671 } else {
672 // Capture the exact admitted capability, including its coordinator
673 // lease, before End permits a new attachment publication. Reserve
674 // cleanup accounting before End so terminal Wait cannot race a later Add.
675 capability := marks.attachmentEffect.capability()
676 launchCleanup := d.reserveAttachmentSendErrorCleanup(capability, f.sendTr)
677 marks.attachmentEffect.End()
678 launchCleanup()
679 }
680 }
681}