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 // Reduced-color chrome never recolors or fades pane content; focus is
161 // shown by the title bar and dividers.
162 blitPaneFrame(frame, pl.Content, pane.frame, !pane.focused && !state.theme.DimByAttribute, inactivePaneDimmer)
163 }
164 for _, d := range pane.damage {
165 if d.Kind != renderer.DamageFullRedraw {
166 d.Y += contentY
167 }
168 damage = append(damage, d)
169 }
170 }
171 // Keep the committed cache unadorned. Toasts are composed first so floating
172 // terminals and scoped modals dim them with the rest of the complete frame.
173 baseFrame := frame
174 overlaysActive := state.overlays.active()
175 toastsVisible := len(state.overlays.notices) > 0 || state.overlays.noticeOverflow > 0
176 var toastFootprints []domain.Rect
177 if toastsVisible {
178 frame = baseFrame.Clone()
179 toastFootprints = composeCapturedNotices(state.overlays, frame, state.styles)
180 }
181 if state.floating.visible {
182 var floatingDamage []renderer.Damage
183 frame, floatingDamage = composeCapturedFloatingFrame(floatingComposeInput{
184 baseFrame: frame,
185 baseDamage: damage,
186 floating: state.floating,
187 content: content,
188 theme: state.theme,
189 borderMuted: styles.BorderMuted,
190 borderActive: styles.BorderActive,
191 cache: in,
192 full: full || overlaysActive,
193 })
194 damage = floatingDamage
195 }
196 copyOnly := state.overlays.copyMode != nil && state.overlays.copyActive &&
197 !state.overlays.copySearchActive &&
198 !state.overlays.paletteActive && !state.overlays.promptActive &&
199 !state.overlays.noticesOverlayActive && !state.overlays.resizeActive && !state.floating.visible
200 var copyViewport copyViewportState
201 var scrollDamage []renderer.Damage
202 if copyOnly && !toastsVisible {
203 copyViewport = captureCopyViewport(state, content)
204 if !full {
205 scrollDamage = copyViewportDamage(in.copyViewport, copyViewport, frame)
206 }
207 }
208 if overlaysActive {
209 if scrollDamage != nil && in.copyViewport.frame.Width == width && in.copyViewport.frame.Height == frameHeight {
210 frame = composeScrolledCopyViewport(state, baseFrame, in.copyViewport, copyViewport, scrollDamage)
211 } else {
212 if !toastsVisible && !state.floating.visible {
213 frame = baseFrame.Clone()
214 }
215 frame, damage = composeCapturedCopyMode(state, frame, damage, content)
216 }
217 frame, damage = composeCapturedOverlays(state, frame, damage)
218 }
219 for x := range width {
220 topBar[x] = baseFrame.Cell(x, 0)
221 bottomBar[x] = baseFrame.Cell(x, rows+1)
222 }
223 if !full {
224 if !sameCells(in.bars.top, topBar) {
225 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: 0, Y: 0, Width: width, Height: 1})
226 }
227 if !sameCells(in.bars.bottom, bottomBar) {
228 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: 0, Y: rows + 1, Width: width, Height: 1})
229 }
230 }
231 // The cache stays toast-free. The terminal shadow, in contrast, includes
232 // toasts, so every render damages both the last and current toast coverage.
233 // This restores cells exposed by dismissal and redraws a stable toast over
234 // any underlying pane update without promoting either case to a full frame.
235 if full || overlaysActive {
236 damage = []renderer.Damage{renderer.FullRedraw()}
237 } else {
238 damage = appendToastDamage(damage, in.toastFootprints)
239 damage = appendToastDamage(damage, toastFootprints)
240 }
241 cursorInputs := state.cursor
242 cursorInputs.hiddenByOverlay = cursorInputs.hiddenByOverlay || overlaysActive
243 cursor := desiredCapturedCursor(cursorInputs, contentY)
244 // A plain copy viewport is painted on a clone, never into baseFrame. Keep
245 // that unadorned base reusable between wheel events. Modal/floating paths
246 // retain their conservative invalidation, and copy exit requests a reset.
247 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}
248 outCache.bars = barCache{top: topBar, bottom: bottomBar}
249 if copyViewport.document != nil {
250 copyViewport.frame = frame
251 outCache.copyViewport = copyViewport
252 }
253 if scrollDamage != nil {
254 damage = scrollDamage
255 }
256 // A copy viewport is ordinary terminal content, not a new output epoch.
257 // Keep conservative resets for other overlays and explicit resynchronization.
258 return composedRenderFrame{frame: frame, damage: damage, cursor: cursor, cache: outCache, reset: state.reset || (overlaysActive && !copyOnly)}
259}
260
261func drawCapturedPaneTitleBar(frame renderer.Frame, pl layout.Placement, title string, focused bool, styles themeui.Styles, neutralBorder renderer.Style, dimmer themeui.Dimmer) {
262 if pl.TitleBar.Y < 0 || pl.TitleBar.Y >= frame.Height {
263 return
264 }
265 style := styles.StatusBar
266 if !focused {
267 style = dimmer.Dim(neutralBorder)
268 }
269 for x := max(pl.TitleBar.X, 0); x < min(pl.TitleBar.X+pl.TitleBar.Width, frame.Width); x++ {
270 frame.Set(x, pl.TitleBar.Y, renderer.Cell{Rune: ' ', Style: style})
271 }
272 ui.DrawText(frame, max(pl.TitleBar.X, 0), pl.TitleBar.Y, min(pl.TitleBar.X+pl.TitleBar.Width, frame.Width), title, style)
273}
274
275func desiredCapturedCursor(c capturedCursorInputs, contentY int) cursorOut {
276 if !c.renderable || c.hiddenByOverlay || !c.visible {
277 return cursorOut{hidden: true}
278 }
279 style := c.style
280 if !c.hasStyle {
281 style = 1
282 }
283 return cursorOut{valid: true, row: c.content.Y + contentY + c.row, col: c.content.X + c.col, style: style, hasStyle: true}
284}
285
286func captureOverlayLayers(state *capturedRenderState, snap *overlayRenderSnapshot, paletteCfg domain.PaletteConfig) {
287 if state == nil || snap == nil {
288 return
289 }
290 o := &state.overlays
291 o.copyActive, o.copySearchActive, o.paletteActive, o.promptActive = snap.copyActive, snap.copySearchModel != nil, snap.paletteActive, snap.promptActive
292 o.noticesOverlayActive = snap.noticesOverlayActive
293 o.copyMode = snap.copyMode
294 o.notices, o.noticeOverflow = snap.notices, snap.noticeOverflow
295 if snap.copyPane != nil {
296 o.copyPaneID = snap.copyPane.id
297 }
298 styles := state.styles
299 if styles == (themeui.Styles{}) {
300 styles = fallbackChromeStyles
301 }
302 rows := state.layout.area.Height
303 rows += tabChromeRows
304 size := domain.Size{Cols: state.layout.area.Width, Rows: rows}
305 if snap.copySearchModel != nil {
306 presentation := copySearchModal.Resolve(size)
307 o.copySearch = capturedModal{active: true, title: copySearchModal.Title, presentation: presentation, focused: true}
308 o.copySearch.inner = snap.copySearchModel.RenderStyled(rectSize(presentation.Inner), visualsearch.RenderStyles{Base: styles.PromptBase, Selection: styles.SearchSelection})
309 }
310 if snap.noticesOverlayActive && snap.noticesOverlayModel != nil {
311 presentation := noticesModal.Resolve(size)
312 o.noticesOverlay = capturedModal{active: true, title: noticesModal.Title, presentation: presentation, focused: true}
313 renderStyles := notices.RenderStyles{Background: styles.PickerBase, Base: styles.PickerBase, Selection: styles.PickerSelection, Text: styles.PickerBase, SelectionText: styles.PickerSelectionName, Muted: styles.PickerDescription, SelectionMuted: styles.PickerSelectionMuted}
314 o.noticesOverlay.inner = snap.noticesOverlayModel.Render(rectSize(presentation.Inner), renderStyles)
315 }
316 if snap.paletteActive && snap.paletteModel != nil {
317 modal := paletteModalFor(paletteCfg)
318 presentation := modal.Resolve(size)
319 o.palette = capturedModal{active: true, title: modal.Title, presentation: presentation, focused: true}
320 guidance := ""
321 if snap.paletteHints != nil {
322 guidance = snap.paletteHints.Feedback
323 }
324 o.paletteGuidance = snap.paletteFeedback
325 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})
326 }
327 if snap.promptActive && snap.promptModel != nil {
328 modal := promptModalFor(snap.promptModel.Title())
329 presentation := modal.Resolve(size)
330 o.prompt = capturedModal{active: true, title: modal.Title, presentation: presentation, focused: true}
331 o.prompt.inner = snap.promptModel.RenderStyled(rectSize(presentation.Inner), prompt.RenderStyles{Base: styles.PromptBase, Selection: styles.SurfaceActive})
332 }
333 state.cursor.hiddenByOverlay = o.active()
334}
335
336func composeCapturedCopyMode(state capturedRenderState, frame renderer.Frame, damage []renderer.Damage, content domain.Rect) (renderer.Frame, []renderer.Damage) {
337 o := state.overlays
338 if !o.copyActive {
339 return frame, damage
340 }
341 target := capturedCopyTarget(state, content)
342 return composeCopyClientFrame(o.copyMode, target, frame, state.styles)
343}
344
345func capturedCopyTarget(state capturedRenderState, content domain.Rect) domain.Rect {
346 o := state.overlays
347 target := domain.Rect{}
348 if state.floating.visible && (o.copyPaneID == "" || o.copyPaneID == state.floating.pane.id) {
349 target = state.floating.geometry.translate(content.X, content.Y).Inner
350 }
351 if target.Width == 0 {
352 id := o.copyPaneID
353 if id == "" {
354 id = state.layout.focus
355 }
356 for _, p := range state.panes {
357 if p.id == id && !p.placement.Collapsed {
358 target = p.placement.Content
359 target.Y += content.Y
360 break
361 }
362 }
363 }
364 return target
365}
366
367func composeCapturedOverlays(state capturedRenderState, frame renderer.Frame, damage []renderer.Damage) (renderer.Frame, []renderer.Damage) {
368 o := state.overlays
369 // Paint in reverse keyboard priority so the same layer that owns input is
370 // visually topmost: prompt > palette > notices > copy search.
371 for _, modal := range []capturedModal{o.copySearch, o.noticesOverlay, o.palette, o.prompt} {
372 if !modal.active {
373 continue
374 }
375 applyOverlayBackdrop(frame, state.theme)
376 border := state.styles.BorderMuted
377 if modal.focused {
378 border = state.styles.BorderActive
379 }
380 (ui.Modal{Title: modal.title}).CompositePresentation(frame, modal.presentation, border, state.styles.PickerBase)
381 copyModalInner(frame, modal.presentation.Inner, modal.inner)
382 damage = []renderer.Damage{renderer.FullRedraw()}
383 }
384 return frame, damage
385}
386
387// copyModalInner copies a captured model frame into its resolved destination.
388// Both source and destination are clipped so degenerate presentations remain
389// safe immutable composition inputs.
390func copyModalInner(dst renderer.Frame, target domain.Rect, src renderer.Frame) {
391 left := max(target.X, 0)
392 top := max(target.Y, 0)
393 right := min(target.X+target.Width, dst.Width)
394 bottom := min(target.Y+target.Height, dst.Height)
395 if left >= right || top >= bottom {
396 return
397 }
398
399 sourceX := left - target.X
400 sourceY := top - target.Y
401 width := min(right-left, src.Width-sourceX)
402 height := min(bottom-top, src.Height-sourceY)
403 if width <= 0 || height <= 0 {
404 return
405 }
406 for y := range height {
407 for x := range width {
408 dst.Set(left+x, top+y, src.Cell(sourceX+x, sourceY+y))
409 }
410 }
411}
412
413func composeCapturedNotices(overlays capturedOverlayRenderState, frame renderer.Frame, styles themeui.Styles) []domain.Rect {
414 if len(overlays.notices) == 0 && overlays.noticeOverflow == 0 {
415 return nil
416 }
417 views := make([]ui.NoticeView, len(overlays.notices))
418 for i, n := range overlays.notices {
419 views[i] = ui.NoticeView{Severity: n.Severity, Title: n.Code.String(), Message: n.Message, Count: n.Count}
420 }
421 return ui.ComposeNotices(frame, views, overlays.noticeOverflow, noticeStylesFrom(styles))
422}
423
424func appendToastDamage(damage []renderer.Damage, footprints []domain.Rect) []renderer.Damage {
425 for _, footprint := range footprints {
426 if footprint.Width > 0 && footprint.Height > 0 {
427 damage = append(damage, renderer.Damage{Kind: renderer.DamageText, X: footprint.X, Y: footprint.Y, Width: footprint.Width, Height: footprint.Height})
428 }
429 }
430 return damage
431}
432
433// noticeStylesFrom picks the toast box color per severity from the theme's
434// chrome roles. Warn uses the dedicated BorderWarn role so it reads as
435// distinct from Info instead of sharing BorderMuted with it.
436func noticeStylesFrom(styles themeui.Styles) ui.NoticeStyles {
437 return ui.NoticeStyles{
438 Text: styles.PickerBase,
439 BoxError: styles.BorderActive,
440 BoxWarn: styles.BorderWarn,
441 BoxInfo: styles.BorderMuted,
442 }
443}
444
445// commitDamageReceipts acknowledges only snapshots that reached the client.
446// sendMu serializes attachment transactions; panes are locked individually so
447// no pane lock is held while another is acquired. A stale generation is
448// intentionally acknowledged too: Screen conservatively leaves FullRedraw for
449// the next transaction.
450func commitDamageReceipts(receipts []damageReceipt) {
451 for _, receipt := range receipts {
452 if receipt.pane != nil {
453 receipt.pane.mu.Lock()
454 receipt.pane.screen.AcknowledgeDamage(receipt.generation)
455 receipt.pane.mu.Unlock()
456 continue
457 }
458 }
459}
460
461// frameFollowUp is the work a frame publication leaves for after the
462// attachment's sendMu is released: notices, repaints, and send-error cleanup
463// may re-enter rendering or take session locks, so they never run under it.
464type frameFollowUp struct {
465 prepareErr error
466 sendErr error
467 sendTr ports.ServerConnection
468 warnGraphics bool
469}
470
471// publishFrameLocked is the sole side-effecting half of the pipeline: it
472// revalidates ownership, prepares, sends, and commits or aborts one captured
473// frame. The caller holds ac.sendMu for the complete capture/compose/publish
474// transaction; publishFrameLocked never releases it. It reports false when the
475// frame was rejected before preparation. The returned follow-up must be passed
476// to settleFrame after sendMu is released.
477func (d *Daemon) publishFrameLocked(entry *session, ac *attachedClient, state *capturedRenderState, composed composedRenderFrame, marks *runtimeMarkBatch) (frameFollowUp, bool) {
478 if entry == nil || entry.core() == nil || ac == nil || state == nil {
479 return frameFollowUp{}, false
480 }
481 entry.core().mu.Lock()
482 _, owned := entry.core().attachments[ac]
483 position := protocol.RoutePosition{
484 Target: state.route.Target,
485 ActiveTabID: state.view.tabID,
486 }
487 entry.core().mu.Unlock()
488 if marks.attachmentEffect != nil {
489 if !marks.attachmentEffect.current() || state.attachment != ac {
490 return frameFollowUp{}, false
491 }
492 } else {
493 if !owned || state.attachment != ac || ac.currentAttachmentSession() != entry {
494 return frameFollowUp{}, false
495 }
496 if state.lease != nil {
497 rc := attachmentRenderCoordinator(entry)
498 if rc == nil || state.lease.attachment != ac || !rc.leaseCurrent(state.lease, true) {
499 return frameFollowUp{}, false
500 }
501 }
502 }
503 endDiff := marks.span(ports.RuntimeDiffStart, ports.RuntimeDiffEnd, 0)
504 prepared, err := ac.output.prepareFrame(d, state, composed.frame, composed.damage, composed.reset, composed.cursor)
505 var data []byte
506 if prepared != nil {
507 data = prepared.data
508 }
509 endDiff(0, err == nil)
510 if err != nil {
511 return frameFollowUp{prepareErr: err}, true
512 }
513 var sendTr ports.ServerConnection
514 var sendErr error
515 rc := attachmentRenderCoordinator(entry)
516 confirmUIFence := rc != nil && rc.needsUIFence(state.lease, state.uiFence)
517 suppressedGraphics := state.suppressedGraphics && !ac.terminalCapabilities.SupportsKittyGraphics()
518 if len(data) > 0 || prepared.ansi.context != nil {
519 sendTransport := ac.transportSnapshot()
520 sendTr = sendTransport.transport
521 endEmit := marks.span(ports.RuntimeEmitStart, ports.RuntimeEmitEnd, uint64(len(data)))
522 if sendTr == nil {
523 sendErr = errors.New("client transport is nil")
524 } else {
525 send := sendTr.SendOutput
526 if sendTr.Capabilities().AsyncSend {
527 send = sendTr.SendOutputAsync
528 }
529 interruptible := false
530 if marks.attachmentEffect != nil {
531 interruptible = marks.attachmentEffect.beginTransportSend(sendTransport)
532 if !interruptible {
533 sendErr = errAttachmentTransition
534 }
535 }
536 if sendErr == nil {
537 if len(data) > 0 {
538 sendErr = prepared.send(ac.echoAck.Load(), send)
539 } else {
540 sendErr = prepared.publishNoBytes(confirmUIFence, func(update protocol.UIViewUpdate) error {
541 if sendTr.Capabilities().AsyncSend {
542 return sendTr.SendServerAsync(update)
543 }
544 return sendTr.SendServer(update)
545 })
546 }
547 }
548 if marks.attachmentEffect != nil && interruptible {
549 if sendErr != nil {
550 marks.attachmentEffect.reportTransportFailure(sendTransport)
551 }
552 marks.attachmentEffect.endTransportSend()
553 }
554 }
555 emitted := sendErr == nil && prepared.sent()
556 endEmit(uint64(len(data)), emitted)
557 if sendErr == nil && !emitted {
558 return frameFollowUp{}, true
559 }
560 if sendErr != nil {
561 prepared.abort()
562 }
563 }
564 if sendErr == nil {
565 if len(data) == 0 {
566 prepared.commitNoSend()
567 if !prepared.sent() {
568 return frameFollowUp{}, true
569 }
570 }
571 ac.afterFrame.emitted(state.frameCapture)
572 // Publish only after output preparation and transport emission both
573 // succeed. A cross-session transition may publish concurrently, but its
574 // mandatory first-paint rebase waits for sendMu and therefore follows this
575 // completed output transaction.
576 ac.render.commitComposition(composed.cache)
577
578 // A successful no-byte emission also commits: its renderer shadow still
579 // represents the captured frame. Lock panes only under sendMu and with no
580 // session guard held.
581 commitDamageReceipts(state.receipts)
582 if ac.renderStages.emit != nil {
583 ac.renderStages.emit()
584 }
585
586 if position.ActiveTabID != "" && position != ac.output.lastRoutePosition {
587 if positionValidateErr := position.Validate(); positionValidateErr != nil {
588 d.log.Error("validate route position", "err", positionValidateErr)
589 } else {
590 sendTransport := ac.transportSnapshot()
591 sendTr = sendTransport.transport
592 interruptible := false
593 if marks.attachmentEffect != nil {
594 interruptible = marks.attachmentEffect.beginTransportSend(sendTransport)
595 if !interruptible {
596 sendErr = errAttachmentTransition
597 }
598 }
599 if sendErr == nil {
600 if sendTr == nil {
601 sendErr = errors.New("client transport is nil")
602 } else if sendTr.Capabilities().AsyncSend {
603 sendErr = sendTr.SendServerAsync(position)
604 } else {
605 sendErr = sendTr.SendServer(position)
606 }
607 }
608 if marks.attachmentEffect != nil && interruptible {
609 if sendErr != nil {
610 marks.attachmentEffect.reportTransportFailure(sendTransport)
611 }
612 marks.attachmentEffect.endTransportSend()
613 }
614 if sendErr == nil {
615 ac.output.lastRoutePosition = position
616 }
617 }
618 }
619 if sendErr == nil && rc != nil && prepared.ansi.boundary.ViewPublication != 0 &&
620 (marks.attachmentEffect == nil || marks.attachmentEffect.current()) {
621 if pending := rc.retireUIFence(state.lease, state.uiFence); pending != nil {
622 receipt := prepared.ansi.boundary
623 receipt.ActionID = pending.actionID
624 sendTransport := ac.transportSnapshot()
625 sendTr = sendTransport.transport
626 sendErr = sendUIReceiptLocked(marks.attachmentEffect, sendTransport, receipt)
627 if sendErr == nil {
628 rc.finishUIFence(state.lease, pending)
629 } else {
630 rc.failUIFence(state.lease, pending)
631 }
632 }
633 }
634 }
635 return frameFollowUp{sendErr: sendErr, sendTr: sendTr, warnGraphics: suppressedGraphics}, true
636}
637
638// settleFrame runs a publication's follow-up with sendMu released and no
639// attachment, session, tab, or pane lock held.
640func (d *Daemon) settleFrame(entry *session, ac *attachedClient, marks *runtimeMarkBatch, f frameFollowUp) {
641 if f.prepareErr != nil {
642 core := entry.core()
643 core.mu.Lock()
644 sessionName := core.name
645 core.mu.Unlock()
646 d.log.Error("render draw failed", "err", f.prepareErr, "session", sessionName)
647 // Without a coordinator reportError repaints synchronously. Suppress only
648 // that nested notice repaint; leave the guard before returning so a later,
649 // independent failed transaction can still notify the user.
650 if entry.renderCoordinator() == nil {
651 if !ac.prepareFailureFallback.CompareAndSwap(false, true) {
652 return
653 }
654 d.reportError(entry, domain.UserErr(domain.NoticeInternal, "display update failed", f.prepareErr))
655 ac.prepareFailureFallback.Store(false)
656 return
657 }
658 d.reportError(entry, domain.UserErr(domain.NoticeInternal, "display update failed", f.prepareErr))
659 // Notices are session-scoped, while the attachment repaint still needs
660 // to redraw its chrome after a failed transaction.
661 d.invalidateRender(entry, ac, true, "render_pipeline.go:prepare-failed")
662 return
663 }
664 if f.warnGraphics && d.warnUnsupportedGraphics(ac) {
665 d.repaintForNotice(ac)
666 }
667 if f.sendErr != nil {
668 // A transport failure may invalidate the role gate. Release this render's
669 // admission first. Detachment freezes the gate and therefore cannot mutate
670 // ownership until any enclosing admitted operation has also ended.
671 if marks.attachmentEffect == nil {
672 d.detachOnSendError(entry, ac, f.sendTr)
673 } else {
674 // Capture the exact admitted capability, including its coordinator
675 // lease, before End permits a new attachment publication. Reserve
676 // cleanup accounting before End so terminal Wait cannot race a later Add.
677 capability := marks.attachmentEffect.capability()
678 launchCleanup := d.reserveAttachmentSendErrorCleanup(capability, f.sendTr)
679 marks.attachmentEffect.End()
680 launchCleanup()
681 }
682 }
683}