Skip to content

terminal read cursor pagination reports a fabricated oldestCursor and silently drops already-completed lines after a CUU (cursor-up) redraw, without ever setting truncated #8745

Closed

Description

@eisen0419

Summary

When a TUI redraws by moving the cursor up (CSI n A) and then producing new output, Orca's retained-tail builder unconditionally deletes every already-completed line below the new cursor position — including lines a client may already hold a valid cursor for. The line-numbering counter used to compute oldestCursor is derived from the post-deletion row count, so it silently reassigns a different, older line's content to the cursor value that used to belong to the deleted line. No truncated flag is set on this path. A client paginating with --cursor gets stale content back under a cursor value it has never seen, with no signal that anything was lost.

This directly violates the terminal-model/view contract's invariant 7:

orca terminal read must preserve bounded previews, cursor pagination, partial-line rules, truncation flags, and total counts even if view snapshots change shape.
— docs/reference/terminal-model-view-contract.md:56

and the contract's own definition of what a transcript is supposed to be:

Transcript: The retained output contract for orca terminal read; it is line/cursor oriented and distinct from a screen snapshot.
— docs/reference/terminal-model-view-contract.md:24

Root cause

The destructive splice

CSI n A (cursor-up) handling in the retained-tail builder:

// src/main/runtime/orca-runtime.ts:25607-25609
// inside appendNormalizedToMultilineTailBufferUnwindowed (src/main/runtime/orca-runtime.ts:25504)
if (parsed.final === 'A') {
  cursorRow = Math.max(0, cursorRow - firstParam)
  rows.splice(cursorRow + 1)
}

This unconditionally deletes every row after the new cursor position — including rows already marked completed: true from a prior \n. This is different from the buffer's normal front-eviction path (trimRows(), orca-runtime.ts:25533-25542, and the equivalent step in finalizeRetainedTerminalRows, orca-runtime.ts:25650-25657), both of which explicitly set truncated = true when they drop rows. The CUU branch's own code path sets no such flag — truncated is only touched elsewhere: by those two front-eviction sites, by finalizeRetainedTerminalRows's character-budget and partial/line-cap trims (orca-runtime.ts:25660, :25686), and by two further truncation sites in the windowed wrapper (orca-runtime.ts:25478).

The mislabeling

The line-numbering math treats the retained-row array as if it were always a contiguous suffix of every line ever completed:

// src/main/runtime/orca-runtime.ts:26026-26037
function readTerminalTail(args: {
  handle: string
  status: RuntimeTerminalState
  completedLines: string[]
  partialLine: string
  completedLineCount: number
  bufferTruncated: boolean
  cursor?: number
  limit?: number
}): RuntimeTerminalRead {
  const oldestCursor = Math.max(0, args.completedLineCount - args.completedLines.length)
  const latestCursor = args.completedLineCount
  ...

completedLineCount (pty.tailLinesTotal) monotonically increases between transcript resets — it is incremented every time a \n completes a row and is never decremented when the CUU branch later deletes that same row via rows.splice() (a disconnect resets it to 0 alongside the rest of the retained transcript, via pruneDisconnectedPtyTranscript, orca-runtime.ts:20251 — a distinct lifecycle event, not a counter-example to the in-session claim below). completedLines (pty.tailBuffer) is the current, post-splice row array. So oldestCursor is computed as "how many lines have ever completed, minus how many rows currently survive" — which conflates "aged out of a bounded buffer" (a legitimate reason to advance oldestCursor) with "destroyed mid-buffer by a redraw" (data loss with no legitimate cursor-accounting justification, since the surviving rows were never contiguous with the deleted one to begin with).

Evidence — this is demonstrated by Orca's own test suite, not just static analysis

// src/main/runtime/orca-runtime.test.ts:12496-12518
it('does not let stale lower rows hide earlier corrected footer rows from cursor reads', async () => {
  const runtime = new OrcaRuntimeService(store)
  syncSinglePty(runtime)

  const [terminal] = (await runtime.listTerminals()).terminals
  runtime.onPtyData('pty-1', 'A\nB\nC\n', 100)
  const beforeRedraw = await runtime.readTerminal(terminal.handle, { cursor: 0 })
  expect(beforeRedraw.tail).toEqual(['A', 'B', 'C'])
  expect(beforeRedraw.nextCursor).toBe('3')

  runtime.onPtyData('pty-1', '\x1b[2A\x1b[2K\x1b[1GB2\n', 101)

  const read = await runtime.readTerminal(terminal.handle)
  expect(read.tail).toEqual(['A', 'B2'])
  expect(read.latestCursor).toBe('4')

  const cursorRead = await runtime.readTerminal(terminal.handle, {
    cursor: Number(beforeRedraw.nextCursor)
  })
  expect(cursorRead.tail).toEqual(['B2'])
  expect(cursorRead.oldestCursor).toBe('2')
  expect(cursorRead.nextCursor).toBe('4')
})

Walking through what this test's own numbers mean: C was completed as line index 2 (cursor value 2, since A=0, B=1, C=2, and beforeRedraw.nextCursor was 3). The redraw (\x1b[2A then overwrite) deletes C via the splice above and rewrites B in place as B2. After that, the full read's tail is ['A', 'B2'] — C is gone, permanently, with no trace. oldestCursor is then reported as '2', i.e. the test asserts, as correct, intended behavior, that the surviving row 'A' — whose real cursor value has always been 0 — is now labeled as if it were the content that starts at cursor 2. Cursor 2 used to belong to 'C', which no longer exists in the retained read transcript and cannot be recovered through cursor reads (a separate headless screen model may retain related state, but that's a different accounting system from the one terminal read exposes).

The test's cursorRead (requesting cursor: 3, beforeRedraw.nextCursor) resolves to tail: ['B2'] — that client was already caught up to latest before the redraw, so it simply gets the new content. A different client shows the actual damage: suppose it had paginated with a limit instead, reading { cursor: 0, limit: 2 } before the redraw. Substituting into the cursor branch (oldestCursor=0, latestCursor=3, args.cursor=0, limit=2): startCursor = max(0, 0) = 0, available = completedLines.slice(0) = ['A', 'B', 'C'], tail = available.slice(0, 2) = ['A', 'B'], nextCursor = 0 + 2 = 2. That client now legitimately holds cursor: 2 as its resume point. After the redraw, it resumes with readTerminal(handle, { cursor: 2 }). Tracing the same function (orca-runtime.ts:26039-26073) against the post-redraw state (oldestCursor=2, latestCursor=4, args.cursor=2): startCursor = max(2, 2) = 2, startIndex = 0, available = completedLines.slice(0) = ['A', 'B2'], tail = available.slice(0, limit) = ['A', 'B2'], and critically truncated: args.cursor < oldestCursor evaluates 2 < 2 = false. The client resuming at cursor 2 gets back the entire surviving buffer, ['A', 'B2'] — including 'A', a line it already has from its first read, plus 'B2' — both relabeled under cursor values (2 and 3) that were never theirs, with truncated: false. This is a direct trace of the pasted, already-tested function against a legitimately-obtained cursor value, not a literal assertion in the suite; the maintainers can verify it by adding a { cursor: 0, limit: 2 } read before the redraw and a { cursor: 2 } read after, against the same fixture.

Why this matters in practice

Orca's own CLI tells users to rely on exactly the corrupted field. The terminal read command help:

// src/cli/specs/core.ts:193-206
{
  path: ['terminal', 'read'],
  summary: 'Read bounded terminal output',
  usage: 'orca terminal read [--terminal <handle>] [--cursor <n>] [--limit <n>] [--json]',
  ...
  notes: [
    'Omit --terminal to target the active terminal in the current worktree.',
    'Use --cursor with the nextCursor value from a previous read to get only new output since that read.',
    'Use --limit to request more retained lines for long agent responses; output reports oldestCursor when older lines were dropped.',
    'Useful for capturing the response to a command: read before sending, then read --cursor <prev> after waiting.'
  ],
  ...
}

and the CLI's own limited-output warning explicitly instructs the user to page with the corrupted field:

// src/cli/terminal-format.ts:127-140
if (
  typeof terminal.nextCursor === 'string' &&
  typeof terminal.latestCursor === 'string' &&
  terminal.nextCursor !== terminal.latestCursor
) {
  return `warning: output limited; continue with --cursor ${terminal.nextCursor}`
}
if (
  typeof terminal.oldestCursor === 'string' &&
  typeof terminal.latestCursor === 'string' &&
  terminal.oldestCursor !== terminal.latestCursor
) {
  // A tail preview's next cursor is already latest, so oldestCursor is the retained history entry point.
  return `warning: output limited; page retained output with --cursor ${terminal.oldestCursor} --limit <count>`
}

Not every client following this pattern is affected — one that's fully caught up to latest at the moment of the redraw (like the test's own cursorRead, holding cursor: beforeRedraw.nextCursor = '3') resumes cleanly and gets the genuinely new 'B2'. The clients at risk are ones still behind by more than the most recent page when a redraw lands — e.g. the { cursor: 0, limit: 2 } client reconstructed above, still holding cursor: 2 when the redraw moves oldestCursor past it. Any automation paginating with --cursor against a TUI or any process that redraws with cursor-up sequences (status spinners, progress bars, in-place log updates — this is common, not exotic), while behind by more than one page when the redraw happens, can silently receive replayed or mislabeled lines instead of the new output it asked for. And the response gives no unambiguous signal of this: oldestCursor does jump forward when it happens, but that's indistinguishable from a legitimate front-eviction boundary, and truncated stays false — there's no field that flags this specific kind of discontinuity.

Expected vs. actual

Expected (per contract invariant 7) Actual
Rows deleted by a CUU redraw Should be reflected in truncated like any other retained-buffer loss truncated never set on this path
oldestCursor after a CUU-triggered deletion Should describe the real cursor value of the oldest surviving line Computed from completedLineCount - completedLines.length, silently relabeling a different, older line
A client re-reading a cursor whose line was deleted by a redraw Should get truncated: true (or equivalent signal) Gets a different line's content back with truncated: false

Suggested direction (not prescriptive)

  1. A surface-level fix — simply setting truncated = true in the CUU branch (orca-runtime.ts:25607-25609, and any other cursor-repositioning handling that discards already-completed rows) — is not sufficient on its own: the cursor-read branch never consumes args.bufferTruncated at all, it only computes truncated: args.cursor < oldestCursor (orca-runtime.ts:26039, :26066), so a flag set upstream would fix the uncursored-read symptom but leave cursor-paginated clients exactly as exposed. That the obvious quick fix doesn't reach the actual failure mode is itself evidence the problem lives in the accounting structure: either the cursor/discontinuity accounting needs to change so a real redraw-induced loss is distinguishable from ordinary front-eviction, or the cursor-read path needs to consume the truncation signal directly.
  2. More structurally: decouple the append-only cursor/line-numbering accounting from the in-place-mutable "current visual rows" array that redraw handling mutates. completedLineCount currently assumes a 1:1 relationship with completedLines.length that CUU redraws break; a redraw that overwrites/destroys previously assigned cursor slots needs its own accounting rather than reusing the "front eviction" math.

Environment

  • Orca 1.4.138-rc.7 (commit 9a77f5667)
  • Reproducible in isolation via the existing unit test above — no SSH/remote/TUI setup required to confirm

Companion issue: #8746 — a different defect in the same read path (the visible-screen fallback that should compensate for transcript gaps is effectively unreachable).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions