Merge pull request #554 from nwparker/cloud/v3-02-host-history-dedup

fix(cloud): V3-02 follow-up — divider back in place when the host restored pre-sleep history (no duplicate)
This commit is contained in:
Neil
2026-11-12 11:19:49 -08:00
committed by GitHub
2 changed files with 109 additions and 10 deletions
@@ -123,6 +123,43 @@ describe('a shallower replay never shrinks a cloud pane (N-02)', () => {
expect(after.indexOf(first)).toBeLessThan(after.indexOf(second))
})
// V3-02 follow-up (n33 baseline): the host restored the pre-sleep history into the woken
// terminal, so its replay already holds 1–2000; only the divider was lost.
it('the host restored the pre-sleep history: the divider goes back in place, nothing doubled', async () => {
const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 6000, allowProposedApi: true })
const divider = '── Slept 11:08 AM · processes stopped ──'
const preSleep = [...lines(1, 300), '$ sleep 900']
const postWake = ['$ seq 5001 5003', '5001', '5002', '5003', 'N02W-POSTWAKE']
await write(terminal, `${[...preSleep, divider, ...postWake].join('\r\n')}\r\n$ `)
const kept = await shallowReplay(terminal, `${[...preSleep, ...postWake].join('\r\n')}\r\n$ `)
expect(kept).toBe(true)
const after = rows(terminal)
expect(after[0]).toBe('00001 line')
expect(after.filter((row) => row === '00001 line')).toHaveLength(1)
expect(after.filter((row) => row === '00300 line')).toHaveLength(1)
expect(after.filter((row) => row === divider)).toHaveLength(1)
expect(after.filter((row) => row === 'N02W-POSTWAKE')).toHaveLength(1)
expect(after.indexOf('00300 line')).toBeLessThan(after.indexOf(divider))
expect(after.indexOf(divider)).toBeLessThan(after.indexOf('5001'))
})
it('the host restored only the newest pre-sleep lines: older ones come from the pane, once each', async () => {
const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 6000, allowProposedApi: true })
const divider = '── Slept 11:08 AM · processes stopped ──'
await write(terminal, `${[...lines(1, 300), divider].join('\r\n')}\r\n$ `)
const kept = await shallowReplay(terminal, `${lines(201, 300).join('\r\n')}\r\n$ `)
expect(kept).toBe(true)
const after = rows(terminal)
expect(after[0]).toBe('00001 line')
expect(after.filter((row) => row.endsWith(' line'))).toHaveLength(300)
expect(after.filter((row) => row === '00250 line')).toHaveLength(1)
expect(after.indexOf('00300 line')).toBeLessThan(after.indexOf(divider))
})
it('leaves the replay alone when it does not overlap what the pane held', async () => {
const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 6000, allowProposedApi: true })
await write(terminal, `${lines(1, 3000).join('\r\n')}\r\n$ `)
@@ -3,7 +3,12 @@
// cut overlaps what the pane held, the older lines above the overlap are written back above it,
// client-side only (nothing reaches the PTY). No overlap (the terminal moved on by more than the
// cut) leaves the host's image as it is: older lines without the ones between would mislead.
import { composeWakeRestore, forgetPreReplayCopy, preReplayCopy } from './cloud-wake-scrollback'
import {
forgetPreReplayCopy,
preReplayCopy,
type composeWakeRestore
} from './cloud-wake-scrollback'
import { wakeAnchorText } from './cloud-wake-scroll-anchor'
import {
renderBufferRows,
sanitizeRestoredText,
@@ -14,6 +19,44 @@ import {
const ANCHOR_LINES = 3
const SGR = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g')
/** How many of the pane's last lines before the divider may be prompts the host did not restore. */
const TRAILING_LINES_SKIPPED = 6
/**
* The host restored the pre-sleep history into the woken terminal (V3-02 follow-up): its replay
* then already holds the lines that end just above the pane's divider. The divider goes back where
* those lines end; nothing is repeated. Pre-sleep lines older than the host's start come from the
* pane. Null when the host holds none of the pre-sleep lines.
*/
function resumeHostAfterSleep(before: string[], dividerAt: number, host: string[]): string | null {
const lowest = Math.max(ANCHOR_LINES, dividerAt - TRAILING_LINES_SKIPPED)
for (let end = dividerAt; end >= lowest; end--) {
const anchor = before.slice(end - ANCHOR_LINES, end).map(plain)
if (anchor.every((line) => line === '')) {
continue
}
for (let start = host.length - ANCHOR_LINES; start >= 0; start--) {
if (!anchor.every((line, k) => plain(host[start + k]) === line)) {
continue
}
let hostEnd = start + ANCHOR_LINES
// The pre-sleep lines after the anchor (a prompt) the host restored too stay above the divider.
while (
end + (hostEnd - start - ANCHOR_LINES) < dividerAt &&
hostEnd < host.length &&
plain(host[hostEnd]) === plain(before[end + (hostEnd - start - ANCHOR_LINES)])
) {
hostEnd++
}
const older = before.slice(0, Math.max(0, end - ANCHOR_LINES - start))
return [...older, ...host.slice(0, hostEnd), before[dividerAt], ...host.slice(hostEnd)].join(
'\r\n'
)
}
}
return null
}
/** The wake divider ("── Slept 2:02–2:31 PM ──" in any of its forms, or a bare rule). */
function isWakeDivider(line: string | undefined): boolean {
return /^──( .+ ──|─*)$/.test(plain(line))
@@ -40,7 +83,10 @@ export function mergeDeeperHistory(paneCopy: string, replayHistory: string): str
}
if (dividerAt !== -1 && !after.some(isWakeDivider)) {
const hostLines = after.length === 1 && plain(after[0]) === '' ? [] : after
return [...before.slice(0, dividerAt + 1), ...hostLines].join('\r\n')
return (
resumeHostAfterSleep(before, dividerAt, hostLines) ??
[...before.slice(0, dividerAt + 1), ...hostLines].join('\r\n')
)
}
if (after.length < ANCHOR_LINES + 1 || before.length <= after.length) {
return null
@@ -62,7 +108,22 @@ type ReplayedTerminal = Parameters<typeof composeWakeRestore>[1] & {
buffer: { active: RestoreBuffer }
}
/** After a clearing replay painted: puts back the pane's deeper history when the replay cut it. */
/** The last row of the screen with text, or the cursor's row when below it (screen-relative). */
function lastScreenRow(terminal: ReplayedTerminal): number {
const active = terminal.buffer.active
for (let row = terminal.rows - 1; row > active.cursorY; row--) {
if (wakeAnchorText(active, active.baseY + row) !== null) {
return row
}
}
return active.cursorY
}
/**
* After a clearing replay painted: puts back the pane's deeper history when the replay cut it. The
* host's whole image (history and screen) is compared, since its newest lines sit on the screen;
* the rewrite ends on the screen's last row with the cursor back where the replay left it.
*/
export async function keepDeeperHistoryAfterReplay(
leafId: string,
terminal: ReplayedTerminal,
@@ -74,15 +135,16 @@ export async function keepDeeperHistoryAfterReplay(
if (paneCopy === null || active.type !== 'normal') {
return false
}
const merged = mergeDeeperHistory(paneCopy, renderBufferRows(active, 0, active.baseY))
const data =
merged === null
? null
: composeWakeRestore(`\x1b[0m${sanitizeRestoredText(merged)}\x1b[0m`, terminal)
if (data === null) {
const last = lastScreenRow(terminal)
const history = renderBufferRows(active, 0, active.baseY)
const screen = renderBufferRows(active, active.baseY, active.baseY + last + 1)
const merged = mergeDeeperHistory(paneCopy, history === '' ? screen : `${history}\r\n${screen}`)
if (merged === null) {
return false
}
// The replay's screen is read; drop its scrollback so the rewrite is the pane's only copy.
const up = last - active.cursorY
const data = `\x1b[2J\x1b[3J\x1b[H\x1b[0m${sanitizeRestoredText(merged)}\x1b[0m${up > 0 ? `\x1b[${up}A` : ''}\x1b[${active.cursorX + 1}G`
// The replay's image is read; drop its scrollback so the rewrite is the pane's only copy.
terminal.clear?.()
await write(data)
forgetPreReplayCopy(leafId)