opencode icon indicating copy to clipboard operation
opencode copied to clipboard

TUI: session list scrolls to the top on the first navigation after a delete

Open jmmon opened this issue 1 week ago • 2 comments

Description

In the Sessions dialog, after deleting a session the list stays correctly positioned and the selection falls up as expected. But the next navigation key (ctrl+n or ctrl+p, or the arrow keys) scrolls the viewport to the top of the list, leaving the highlighted row off-screen entirely. The selection index is right; the viewport is not, so the row you are on disappears from view.

It takes a second navigation keypress for the view to come back to the selection.

This is the viewport, not the selection. The older reports (#5466, #9236) are about the selection jumping when you arm the delete in v1; here the selection is correct and the scroll offset is lost.

Environment

  • opencode v2.3.2 (opencode --version)
  • Arch Linux, kernel 7.2.11-arch1-1, x86_64
  • Interactive TUI, TERM=xterm-256color
  • Reproduced identically in a clean instance with an empty data directory and no sessions other than the ones created for the test, so no user config or plugin is involved

Repro

The list only has to be long enough to scroll. At a 100x24 terminal the Sessions dialog shows 5 rows, so 12 sessions is plenty.

  1. Start with enough sessions that the Sessions dialog scrolls. Either create them normally, or with a simulated model the way #63761's script does, or use the DB seeding shortcut in the appendix. Give them distinguishable titles (SESS-01 … SESS-12). Spreading time_updated over several days is not required, it just makes the list scroll with fewer sessions because each date header costs a row.
  2. Open the Sessions dialog: ctrl+x then l.
  3. Press ctrl+n 8 times. Selection is on SESS-09, and the viewport has scrolled with it, showing SESS-07 … SESS-11.
  4. Press ctrl+d twice to delete SESS-09. Viewport is still SESS-07, SESS-08, SESS-10, SESS-11, SESS-12 and SESS-10 is highlighted. This is all correct.
  5. Press ctrl+n once.

Expected: SESS-11 is highlighted and stays in view; the viewport does not move.

Actual: the viewport jumps to the top of the list and shows SESS-01 … SESS-05. The highlight is on SESS-11, which is now off-screen. Nothing on screen indicates where you are.

Pressing ctrl+n again brings the viewport back to the selection, which is why it reads as a one-frame hiccup that then half-recovers.

ctrl+p instead of ctrl+n in step 5 does the same thing.

Evidence

Captured frames from a scripted run (each >> marks the highlighted row, visible is what the terminal shows). Reproduced 3/3 with identical output, and re-checked after a 2.5 s settle so this is not scroll animation:

step                 visible                        selected
baseline             SESS-01..05                    SESS-01
ctrl+n x8            SESS-07..11                    SESS-09
ctrl+d ctrl+d        SESS-07,08,10,11,12            SESS-10     <- correct
ctrl+n               SESS-01..05                    SESS-11 (off-screen)
ctrl+n               SESS-08,10,11,12               SESS-12     <- recovers

Control, same build, same data: deleting a row while the list is not scrolled (offset already 0) shows no jump at all, and the following navigation is normal. So the reset is specific to a non-zero scroll offset surviving a delete.

Likely cause

packages/tui/src/ui/dialog-select.tsx. The Sessions dialog renders through DialogSelect with focusCurrent={false} and no preserveSelection, so when the options array changes — which is what a delete does, dialog-session-list.tsx filters the cached list — the options effect takes this branch:

if (!props.preserveSelection && ((props.focusTarget ?? props.current) === undefined || props.focusCurrent === false)) {
  const count = flat().length
  if (count === 0) return
  const next = reconcileSelection(store.selected, count)
  if (next !== store.selected) setStore("selected", next)
  return                       // selection repaired, scroll never restored
}

It repairs the index and returns without going through scrollAfterLayout, which exists precisely to defer scrolling until the next CliRenderEvents.FRAME. The rows themselves are rebuilt — <For each={grouped()}> re-renders because the options memo mints new objects — so when the next navigation calls scrollToSelection, it reads target.y from children that have not been laid out yet:

const target = scroll.getChildren()[index]
const y = target.y - scroll.y
if (center) scrollBy(y - Math.floor(scroll.height / 2))   // y ~ 0 -> scrolls up to the top

That produces exactly the observed "jump to top, then recover on the next keypress". Flagging this as analysis, not proof — the behaviour above is the finding.

Appendix: deterministic setup

Seeding the sessions directly makes the repro exact. Insert into session_v2 in a test data directory (XDG_DATA_HOME=/tmp/x opencode --standalone creates one), then restart:

insert into session_v2
  (id, project_id, parent_id, slug, directory, path, title, version,
   cost, time_created, time_updated, time_archived, resume_attempts)
values ('ses_<26 chars>', '<project id>', null, 'probe-01', '<cwd>', '',
        'SESS-01', '2.3.2', 0, <ms>, <ms>, null, 0);

project_id is the row in project; its worktree column holds the directory.

Related

  • #5466 (closed, v1) — selection jumps to the active session when arming a delete. Different: that is the selection at arm-time, this is the viewport after the delete.
  • #9236 (closed, v1) — reported the same as #5466 as a regression. Same distinction.
  • #55699 / #55114 (open) — scroll position lost on session switch, desktop not TUI. Same family of "viewport not preserved", different surface.

jmmon avatar Nov 20 '26 18:11 jmmon

Thanks for the detailed report. I reproduced this on v2.3.2, and it still happens on the latest dev (fe8def6).

The script below creates 12 sessions (SESS-01…SESS-12) at a 100x24 viewport, opens Sessions with ctrl+x l, presses ctrl+n 8 times, then ctrl+d twice to delete SESS-09:

  • After the delete: SESS-10 is highlighted and the view is still scrolled (SESS-06, 07, 08, 10, 11, 12), as expected.
  • First ctrl+n: the view jumps to the top (Today, SESS-01…05) and the highlighted row is off-screen.
  • Second ctrl+n: the view comes back with SESS-12 highlighted.

The recording and screenshots below show it. Each capture was taken 1.5 s after the key press, so this is not scroll animation.

https://github.com/user-attachments/assets/99215f82-3f17-4d71-88ef-46b2f97314d3

Screenshot

Screenshot

Screenshot

Reproduction script (drive.ts)
// Repro for anomalyco/opencode#65250: after deleting a session in the Sessions dialog
// while the list is scrolled, the next ctrl+n scrolls the viewport to the top.
import { Effect } from "effect"
import { OpenCodeDriver } from "opencode-drive"

const N = 12
const title = (i: number) => `SESS-${String(i).padStart(2, "0")}`

export default OpenCodeDriver.use(
  {
    ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
    tui: { recording: true, keypressOverlay: true, viewport: { cols: 100, rows: 24 } },
  },
  ({ ui, opencode, artifacts }) =>
    Effect.gen(function* () {
      // Create SESS-12 first so SESS-01 is the most recent (top of the list).
      for (let i = N; i >= 1; i--) {
        yield* opencode.session.create({ title: title(i), location: { directory: `${artifacts}/files` as any } })
        yield* Effect.sleep(30)
      }

      const report = (step: string) =>
        Effect.gen(function* () {
          yield* Effect.sleep(1500)
          const frame = yield* ui.capture()
          const text = frame.lines.map((l) => l.spans.map((s) => s.text).join(""))
          const visible = text.flatMap((l) => l.match(/SESS-\d\d/g) ?? [])
          console.log(`STEP ${step.padEnd(16)} visible=[${visible.join(",")}]`)
          yield* ui.screenshot(step.replace(/[^a-z0-9]+/gi, "-"))
        })

      yield* Effect.sleep(1000)
      yield* ui.press("x", { ctrl: true })
      yield* ui.press("l")
      yield* ui.waitFor("SESS-01")
      yield* report("baseline")
      for (let i = 0; i < 8; i++) {
        yield* ui.press("n", { ctrl: true })
        yield* Effect.sleep(150)
      }
      yield* report("ctrl+n x8")
      yield* ui.press("d", { ctrl: true })
      yield* Effect.sleep(300)
      yield* ui.press("d", { ctrl: true })
      yield* report("after delete")
      yield* ui.press("n", { ctrl: true })
      yield* report("ctrl+n #1")
      yield* ui.press("n", { ctrl: true })
      yield* report("ctrl+n #2")
    }),
)

Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.

opencodejr[bot] avatar Nov 20 '26 18:11 opencodejr[bot]

Taking this.

Source audit matches the reported split (selection right, viewport wrong): after a delete, DialogSelect's options effect repairs the selected index in its fall-through branch and returns without scheduling a frame, while <For> has already rebuilt every row because options() mints new objects. The next navigation then calls scrollToSelection and reads target.y from rows inserted after the last layout pass, so the computed offset is negative and the viewport clamps to the top.

Plan: defer the scroll restore to the next frame (the existing scrollAfterLayout path the other branches use) and add a regression test that deletes a row from a scrolled list, then presses the next/previous key. I will open a PR against dev once it is verified locally.

ccclucky avatar Nov 20 '26 18:11 ccclucky