szn

Bug 546 — Main-screen sixel images destroyed by alt-screen ESC[2J, ESC[3J, and resetHard

546. Sixel erasure ignores img.alt_screen, treats CSI 3 J like CSI 2 J, and frees the saved main grid on resetHard

Severity: CRITICAL
Status: ✅ RESOLVED
Files: src/screen.zig:1242-1276, src/screen.zig:1656-1720

Problem

  1. Alt-screen ESC[2J destroys main-screen sixel images (src/screen.zig:1250-1275): Screen.eraseDisplay loops over 0..MAX_SIXEL_IMAGES and frees matching images without checking if (img.alt_screen != self.mode.alt_screen) continue;. When a user displays a sixel image on the main screen and then opens vim, less, or htop (which enters alt_screen via ?1049h and immediately sends ESC[2J), eraseDisplay(2):
    • Frees every main-screen SixelImage in self.sixel_images;
    • Calls self.clearSixelMarkerCells(img.id), which only clears self.grid (the alt grid) and leaves dangling sixel marker cells (cell.attr.sixel = true) in self.alt_grid (the saved main grid).
  2. CSI 3 J (eraseDisplay(3)) deletes visible active-screen sixel images (src/screen.zig:1260):
    const should_remove = switch (mode) {
        0 => img_bottom > cy and img.anchor_row < h,
        1 => img.anchor_row <= cy and img_bottom > 0,
        2, 3 => true,
        else => false,
    };
    

    Mode 3 (CSI 3 J) is defined by xterm/VT to clear scrollback history only, leaving the visible screen intact (self.grid.clearHistory() at line 1246). By grouping 3 with 2, eraseDisplay(3) deletes all visible sixel images on the active screen.

  3. Screen.resetHard in alt_screen frees the saved main screen (src/screen.zig:1676-1679): When self.mode.alt_screen is true, self.alt_grid holds the saved main grid while self.grid is the temporary alternate grid. resetHard executes:
    if (self.alt_grid) |*ag| {
        ag.deinit();
        self.alt_grid = null;
    }
    

    destroying the saved main screen and its scrollback history instead of exiting alt-screen first. In addition, resetHard and clearScreen (src/screen.zig:1709-1720) call self.grid.clear() without clearing sixel markers in self.grid.history, leaving orphaned marker cells in scrollback whose registry entries were just freed.

Proposed Fix

  1. In Screen.eraseDisplay, skip images from the other screen buffer:
    if (img.alt_screen != self.mode.alt_screen) continue;
    
  2. For mode == 3 in Screen.eraseDisplay, only remove images that lie entirely in scrollback (img_bottom <= 0) or are no longer referenced after self.grid.clearHistory(), and for mode == 2 only clear visible-row markers rather than scrollback markers.
  3. In Screen.resetHard, if self.mode.alt_screen is true, call self.useAltScreen(false) (or swap self.alt_grid back into self.grid and deinit the alt grid) and clear history sixel markers before freeing all sixel_images.