Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(terminal): cold-restore scrollback lands in the tmux pane, not the hidden emulator screen

reviewe59706043c63
diff --git a/CLAUDE.md b/CLAUDE.md
index 732bd2383..46754c64f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1507,7 +1507,16 @@ session (you can't keep a live OS process across a reboot):
timer (`SCROLLBACK_SNAPSHOT_MS`) + on detach/quit (`tmux capture-pane -e`). On a cold start the
renderer reads it via `pty.readScrollback` and writes it back into xterm (with a "session
restored" separator). Warm reattach skips it (tmux already redraws). Deleted with the node in
- `destroySession`.
+ `destroySession`. **That emulator replay is only for the non-tmux backends.** A fresh tmux
+ client puts xterm on the alternate screen at attach, so a snapshot written into xterm is hidden
+ an instant later and cannot be scrolled back to — the feature silently did nothing on every
+ local tmux terminal for months, with every decision test green. For a local tmux cold start the
+ caller passes `PtyCreateOptions.restoreScrollback`, core stages the snapshot and chains a
+ `run-shell` onto the same `new-session` that writes it to the new **pane's tty**
+ (`scrollbackSeedTmuxArgs`), so it is ordinary pane output tmux paints and keeps as history, and
+ answers `PtyCreateResult.scrollbackSeeded` so the renderer writes nothing (`seedPaint`'s
+ `coreSeeded`). Proven against a real tmux in `scrollback-seed.realtmux.test.ts`. **SSH-project
+ and Zellij nodes are not covered yet** — they still take the hidden emulator replay.
**The periodic capture is paced, serialized and deduplicated** (`snapshotTick`,
`core/scrollback-cadence.ts`). A working agent's spinner keeps its session dirty forever, so the
old tick spawned a `capture-pane -S -1500` (an ssh exec for a remote node) and rewrote up to
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index dbbfe1407..1c850222c 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -172,7 +172,13 @@ import { NESTED_AGENT_ENV_STRIP } from './nested-agent-env'
import { effectiveSize, type PtySize } from './pty-size'
import { DaReplyGate, DA_REPLY_TTL_OTHER_MS, DA_REPLY_TTL_TMUX_MS } from './da-reply-gate'
import { machOArch, archMismatch } from './macho-arch'
-import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'
+import {
+ writeScrollback,
+ readScrollback,
+ deleteScrollback,
+ prepareScrollbackSeed,
+ scrollbackSeedTmuxArgs
+} from './scrollback-store'
import { snapshotDue } from './scrollback-cadence'
import { createHash, randomUUID } from 'node:crypto'
import { claudeConfigDirFor } from './claude-config-dir'
@@ -953,6 +959,10 @@ interface Session {
/** True when this node had an `accountId` but its config dir was gone at spawn, so we fell back
* to the system account. `create()` surfaces it to the renderer (warning chip). */
accountFallback?: boolean
+ /** The spawn that created this session chained the cold-restore scrollback seed onto its
+ * `new-session` (see scrollback-store.ts). `create()` surfaces it so the renderer does not
+ * replay the same snapshot into its emulator. */
+ scrollbackSeeded?: boolean
/** Set once `join` has warned that this session holds a remote-only node's id somewhere other
* than that node's host (`held-elsewhere`). A watcher retries its join every 2/4/8/15 s for as
* long as the link lives, and every retry is refused the same way, so the warning is logged once
@@ -3177,6 +3187,19 @@ export class PtyManager {
background: options.onScreen === false
})
: null
+ // Cold start of a LOCAL tmux session whose caller wants its scrollback back: stage the
+ // snapshot so `spawnSession` can chain it into the new pane. It has to go into the PANE — the
+ // emulator is put on the alternate screen by the attach and would hide it (scrollback-store.ts).
+ // Staged here because `spawnSession` is synchronous. Null = no snapshot = nothing to seed.
+ const scrollbackSeed =
+ fresh &&
+ tmuxBacked &&
+ !options.sshRemote &&
+ !warmWindowsBackend &&
+ zellijChoice?.use !== true &&
+ options.restoreScrollback
+ ? await prepareScrollbackSeed(options.persistKey as string)
+ : null
let sessionId: string
try {
sessionId = this.spawnSession(
@@ -3185,7 +3208,8 @@ export class PtyManager {
undefined,
warmWindowsBackend,
projectOverrides,
- zellijChoice?.use === true
+ zellijChoice?.use === true,
+ scrollbackSeed
)
} catch (err) {
// A spawn that never happened must not hold a slot until the settle deadline — the next node
@@ -3293,7 +3317,8 @@ export class PtyManager {
// tmux emitted at attach — see PtyCreateResult.tmuxClient. Same gate as the join's alt screen.
...(spawned?.tmuxBacked && !spawned.sessionHost ? { tmuxClient: true as const } : {}),
...(staleCwd ? { staleCwd: true as const } : {}),
- ...(screen ? { screen } : {})
+ ...(screen ? { screen } : {}),
+ ...(spawned?.scrollbackSeeded && fresh ? { scrollbackSeeded: true as const } : {})
}
}
@@ -4354,7 +4379,10 @@ export class PtyManager {
/** `create()`'s Zellij decision. Absent on the detached (relay host) paths, which fall back to
* what this process knows about the node (`zellijKeys`) — a phone attaching to a Zellij node
* must join that session, never create a tmux one beside it. */
- zellijBackend?: boolean
+ zellijBackend?: boolean,
+ /** A staged cold-restore seed file (`prepareScrollbackSeed`) to write into the pane this spawn
+ * creates. Only honored by the local-tmux attach-or-create branch. */
+ scrollbackSeed?: string | null
): string {
// PRE-FLIGHT — refuse before node-pty is touched, not after it fails.
//
@@ -4718,6 +4746,9 @@ export class PtyManager {
// Unlike the installed-binary probe, this records the backend selected for THIS generation.
// A Windows profile may coexist with an MSYS/Cygwin tmux on PATH and must not inherit it.
let useLocalTmux = false
+ // Set only where the seed was actually chained onto a `new-session` — so the answer the
+ // renderer gets describes what this spawn did, not what `spawnNew` hoped it would do.
+ let scrollbackSeeded = false
// Set by the Zellij branch below; see zellij-backend.ts.
let useLocalZellij = false
const zellijBin =
@@ -5027,6 +5058,12 @@ export class PtyManager {
args.push(shell)
args.push(...programArgs)
}
+ // Cold restore: write the staged snapshot into the pane this invocation creates, as a
+ // second tmux command on the same line (after the session program, which it must follow).
+ if (scrollbackSeed) {
+ args.push(...scrollbackSeedTmuxArgs(scrollbackSeed, sessionName(options.persistKey)))
+ scrollbackSeeded = true
+ }
}
} else if (
!options.sshRemote &&
@@ -5206,6 +5243,7 @@ export class PtyManager {
unwatchedSince: null,
pausedBy: new Set<string>(),
accountFallback,
+ ...(scrollbackSeeded ? { scrollbackSeeded } : {}),
sessionHost: useSessionHost,
...(useSessionHost && options.agentId ? { launchAgentId: options.agentId } : {}),
...(useSessionHost && env[envPathKey(env)] ? { launchPath: env[envPathKey(env)] } : {}),
diff --git a/src/core/scrollback-seed.realtmux.test.ts b/src/core/scrollback-seed.realtmux.test.ts
new file mode 100644
index 000000000..0ea24e7ce
--- /dev/null
+++ b/src/core/scrollback-seed.realtmux.test.ts
@@ -0,0 +1,144 @@
+// COLD-RESTORE SEEDING, PROVEN AGAINST A REAL TMUX.
+//
+// The bug this pins: after a reboot the renderer replayed the persisted scrollback into xterm's
+// NORMAL screen, and the fresh tmux client's attach (`\e[?1049h` + clear) hid it an instant later
+// — with the wheel scrolling tmux's (empty) history, so it could not be scrolled back to either.
+// Nobody ever saw "session restored". The decision tests stayed green throughout, because they
+// only assert that a replay is CHOSEN, not that the text ends up anywhere a user can see.
+//
+// The fix writes the snapshot into the new PANE (scrollback-store.ts). Whether a `run-shell`
+// chained onto `new-session` really lands in that pane's history, expands `#{pane_tty}`, survives
+// a hostile path and leaves a live pane alone is a property of tmux — so it is measured here, with
+// the EXACT conf `tmuxConf()` ships and the EXACT argv `scrollbackSeedTmuxArgs` builds.
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
+import { execFileSync } from 'child_process'
+import fs from 'fs'
+import path from 'path'
+import { tmuxConf } from './pty-manager'
+import {
+ buildScrollbackSeed,
+ scrollbackSeedTmuxArgs,
+ SESSION_RESTORED_LINE
+} from './scrollback-store'
+import { makeTmuxTmpdir } from './tmux-test-socket'
+
+// Only `tmuxConf()` (a string builder) is needed from pty-manager; nothing here spawns a pty. Stub
+// the native module so this suite measures tmux even on a checkout whose node-pty is not built.
+vi.mock('node-pty', () => ({}))
+
+const SOCKET = `nt-seedtest-${process.pid}`
+
+let tmp: string
+let conf: string
+let tmuxOk = false
+
+function tmux(args: string[]): string {
+ return execFileSync('tmux', ['-L', SOCKET, ...args], {
+ env: { ...process.env, TMUX_TMPDIR: tmp },
+ stdio: ['ignore', 'pipe', 'pipe']
+ }).toString()
+}
+
+beforeAll(() => {
+ try {
+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })
+ tmuxOk = true
+ } catch {
+ return // no tmux on this host — every test below self-skips
+ }
+ tmp = makeTmuxTmpdir('ntseed-', SOCKET)
+ conf = path.join(tmp, 'tmux.conf')
+ fs.writeFileSync(conf, tmuxConf(2000))
+})
+
+afterAll(() => {
+ if (!tmuxOk) return
+ try {
+ tmux(['kill-server'])
+ } catch {
+ /* already gone */
+ }
+ fs.rmSync(tmp, { recursive: true, force: true })
+})
+
+/** The whole pane — history included — as text. */
+const pane = (session: string): string => tmux(['capture-pane', '-p', '-t', session, '-S', '-'])
+
+const until = async (ok: () => boolean, ms = 3000): Promise<void> => {
+ const t0 = Date.now()
+ while (!ok()) {
+ if (Date.now() - t0 > ms) throw new Error('timed out')
+ await new Promise((r) => setTimeout(r, 25))
+ }
+}
+
+const SEPARATOR_TEXT = 'session restored (process ended by a restart)'
+// What `capture-pane -p -e` hands the snapshot store: LF-separated, SGR inside, blank rows below
+// the cursor.
+const SNAPSHOT = '$ ls\n\x1b[34mfile-a\x1b[0m file-b\n$ \n\n\n\n'
+
+/** Stage a seed file and create a session the way the local spawn branch does (minus the client:
+ * `-d`, since a test has no tty to attach). `cat` is the pane program so nothing else prints. */
+function coldStart(session: string, seedFile: string): void {
+ fs.writeFileSync(seedFile, buildScrollbackSeed(SNAPSHOT))
+ tmux([
+ '-f', conf, 'new-session', '-d', '-x', '80', '-y', '24', '-s', session, 'cat',
+ ...scrollbackSeedTmuxArgs(seedFile, session)
+ ])
+}
+
+describe('buildScrollbackSeed', () => {
+ it('ends every line with CRLF, drops the trailing blank rows and appends the separator', () => {
+ const seed = buildScrollbackSeed(SNAPSHOT)
+ expect(seed).toBe(
+ '\r\x1b[2K$ ls\r\n\x1b[34mfile-a\x1b[0m file-b\r\n$\x1b[0m\r\n' + SESSION_RESTORED_LINE + '\r\n'
+ )
+ expect(seed.replace(/\r\n/g, '')).not.toContain('\n') // no bare LF left to staircase
+ })
+
+ it('is empty when there is nothing to restore — no lone separator over an empty pane', () => {
+ expect(buildScrollbackSeed('')).toBe('')
+ expect(buildScrollbackSeed('\n\n \n')).toBe('')
+ })
+})
+
+describe('cold-restore seed lands in the tmux pane (real tmux)', () => {
+ it('the restored text and the separator are in the new pane, where tmux paints and scrolls them', async () => {
+ if (!tmuxOk) return
+ const seedFile = path.join(tmp, 'a.seed')
+ coldStart('nt-cold', seedFile)
+ await until(() => pane('nt-cold').includes(SEPARATOR_TEXT))
+ const lines = pane('nt-cold').split('\n')
+ expect(lines.slice(0, 4)).toEqual(['$ ls', 'file-a file-b', '$', `── ${SEPARATOR_TEXT} ──`])
+ // …and it is HISTORY, not just a painted screen: scroll it off and it is still there.
+ tmux(['send-keys', '-t', 'nt-cold', ...Array.from({ length: 40 }, () => 'Enter')])
+ await until(() => Number(tmux(['display-message', '-p', '-t', 'nt-cold', '#{history_size}'])) > 0)
+ expect(pane('nt-cold')).toContain(SEPARATOR_TEXT)
+ // The staged file is one-shot.
+ await until(() => !fs.existsSync(seedFile))
+ })
+
+ it("a user-data path with a space, a quote and a '#' still seeds (shell quoting + format escaping)", async () => {
+ if (!tmuxOk) return
+ const dir = path.join(tmp, "App Support's #1 dir")
+ fs.mkdirSync(dir)
+ const seedFile = path.join(dir, 'b.seed')
+ coldStart('nt-path', seedFile)
+ await until(() => pane('nt-path').includes(SEPARATOR_TEXT))
+ await until(() => !fs.existsSync(seedFile))
+ })
+
+ it('a pane that already has history is left alone — `-A` may have attached to a LIVE session', async () => {
+ if (!tmuxOk) return
+ tmux(['-f', conf, 'new-session', '-d', '-x', '80', '-y', '24', '-s', 'nt-live', 'seq 1 200; cat'])
+ await until(() => Number(tmux(['display-message', '-p', '-t', 'nt-live', '#{history_size}'])) > 0)
+ const seedFile = path.join(tmp, 'c.seed')
+ fs.writeFileSync(seedFile, buildScrollbackSeed(SNAPSHOT))
+ // The chained command on its own (drop the leading `;`), aimed at the live session.
+ tmux(scrollbackSeedTmuxArgs(seedFile, 'nt-live').slice(1))
+ await until(() => !fs.existsSync(seedFile)) // consumed…
+ expect(pane('nt-live')).not.toContain(SEPARATOR_TEXT) // …but never written
+ // A refused seed must not flip the pane into view mode to report a failure.
+ expect(tmux(['display-message', '-p', '-t', 'nt-live', '#{pane_in_mode}']).trim()).toBe('0')
+ })
+})
diff --git a/src/core/scrollback-store.ts b/src/core/scrollback-store.ts
index c8fbac0ea..333725275 100644
--- a/src/core/scrollback-store.ts
+++ b/src/core/scrollback-store.ts
@@ -3,6 +3,7 @@ import path from 'path'
import { createHash } from 'crypto'
import { renameAtomic, tempNameFor } from './fs-atomic'
import { platform } from './platform'
+import { shellSingleQuote } from '../shared/shell-quote'
// On a machine reboot the tmux server dies, so the live scrollback is lost. We persist a
// byte-capped snapshot of each terminal's recent output to disk while it's running and replay
@@ -73,3 +74,90 @@ export async function deleteScrollback(persistKey: string): Promise<void> {
// ignore
}
}
+
+// ---------------------------------------------------------------------------------------------
+// Cold-restore SEEDING: put the snapshot into the new tmux pane, not into the emulator.
+//
+// tmux owns the client's screen: on attach it switches the emulator to the ALTERNATE screen
+// (`\e[?1049h`) and clears it, and the wheel scrolls tmux's own history. A snapshot the renderer
+// writes into xterm therefore lands on the normal screen and is hidden an instant later, with no
+// way to scroll back to it — measured: after "snapshot, then a fresh attach's bytes" the active
+// buffer is `alternate` and empty. That was the whole cold-restore feature silently doing nothing
+// on every tmux-backed terminal.
+//
+// So for a tmux-backed cold start the snapshot is written to the new PANE's tty instead. It becomes
+// ordinary pane output: tmux paints it, keeps it in its history, and the wheel scrolls it. The
+// write is chained onto the same `new-session` invocation (`run-shell`), so it needs no polling
+// and does not change how the user's shell is started.
+//
+// Known limit, measured (tmux 3.4, attached client): the write races the shell's first prompt. A
+// shell that reads startup files loses to it — a login bash: snapshot first, prompt after, 15/15.
+// A shell with nothing to read (`bash --norc`, dash) prompts within ~2 ms and wins, 14/15; so the
+// seed opens by erasing the current line, and in that case the restored text is followed by no
+// prompt until the user presses Enter. Cosmetic — the content is restored either way.
+// ---------------------------------------------------------------------------------------------
+
+/** The separator printed under restored scrollback — the same wording the renderer prints when
+ * it replays a snapshot itself (the non-tmux backends; TerminalNode.tsx). */
+export const SESSION_RESTORED_LINE =
+ '\x1b[90m── session restored (process ended by a restart) ──\x1b[0m'
+
+/**
+ * The bytes written to a fresh pane's tty: the snapshot (CRLF line ends — it comes from
+ * `capture-pane -p`, LF only, and must not depend on the tty still having `onlcr`), trailing blank
+ * rows dropped (a capture includes the empty rows below the cursor), then the separator.
+ * '' when there is nothing worth restoring.
+ */
+export function buildScrollbackSeed(snapshot: string): string {
+ const body = snapshot.replace(/\r\n/g, '\n').replace(/\s+$/, '')
+ if (!body) return ''
+ return (
+ '\r\x1b[2K' + body.replace(/\n/g, '\r\n') + '\x1b[0m\r\n' + SESSION_RESTORED_LINE + '\r\n'
+ )
+}
+
+function seedPath(persistKey: string): string {
+ return snapshotPath(persistKey).replace(/\.bin$/, '.seed')
+}
+
+/**
+ * Stage the seed file for `persistKey`'s cold start. Returns its path, or null when there is no
+ * snapshot (or it could not be staged) — in which case nothing is seeded and nothing breaks.
+ */
+export async function prepareScrollbackSeed(persistKey: string): Promise<string | null> {
+ const seed = buildScrollbackSeed(await readScrollback(persistKey))
+ if (!seed) return null
+ const file = seedPath(persistKey)
+ try {
+ await fs.promises.mkdir(dir(), { recursive: true })
+ await fs.promises.writeFile(file, seed, { mode: 0o600 })
+ return file
+ } catch {
+ return null
+ }
+}
+
+/**
+ * tmux arguments to APPEND to a `new-session` invocation so the staged seed is written into the
+ * pane that invocation creates. Each element is one argv entry (the lone `;` is tmux's command
+ * separator), so nothing here is parsed by a shell on our side; the `run-shell` body is, and the
+ * seed path is single-quoted for it — with `#` doubled first, because `run-shell` format-expands
+ * its command and a `#` in the user-data path would otherwise be read as a format.
+ *
+ * `#{history_size}` is the guard for the one case `-A` leaves open: if the session turned out to
+ * exist after all (it was created between our `has-session` probe and this spawn), the pane is
+ * live and must not have an old snapshot dumped into it. A pane this invocation created has no
+ * history yet. The seed file is removed either way, and the body always exits 0 — a non-zero
+ * `run-shell` makes tmux put the pane into view mode to show the failure.
+ */
+export function scrollbackSeedTmuxArgs(seedFile: string, session: string): string[] {
+ const file = shellSingleQuote(seedFile).replace(/#/g, '##')
+ return [
+ ';',
+ 'run-shell',
+ '-b',
+ '-t',
+ session,
+ `{ [ '#{history_size}' = 0 ] && cat ${file} > '#{pane_tty}'; rm -f ${file}; } 2>/dev/null; :`
+ ]
+}
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 5b6bd31f6..8013bd4a6 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -572,6 +572,7 @@ export function ModalTerminal({
accountId: spawn.accountId,
sshRemote,
requireRemote: spawn.sshRemoteTmux,
+ restoreScrollback: true,
// Same local-login exemption as the canvas node (issue #1186).
...(isLocalOnSshCanvas(nodeId) ? { localOnSshCanvas: true } : {})
}).catch((err: unknown): Error => (err instanceof Error ? err : new Error(String(err))))
@@ -642,7 +643,8 @@ export function ModalTerminal({
replay: attachReplay({ parked: false, fresh: res.fresh, hasInitialCommand: false }),
superseded: false,
snapshot,
- screen: res.screen
+ screen: res.screen,
+ coreSeeded: res.scrollbackSeeded
})
if (paint === 'snapshot') {
if (snapshot) term.write(toXtermText(snapshot))
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 03b460976..f4e7d79dc 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -3731,6 +3731,9 @@ export function TerminalNode({
// Belt AND braces: the guard above cannot see a `ssh` executable that has gone missing,
// which is core's other route into the local branch.
requireRemote: sshRemoteTmux,
+ // Same rule `attachReplay` applies below: a node with a one-shot launch command is being
+ // opened for the first time and has no history to restore.
+ restoreScrollback: !data.initialCommand,
// The one local terminal an SSH project's canvas may hold (issue #1186): core refuses
// every other local spawn owned by an SSH project. In-memory mark, never node data.
...(isLocalOnSshCanvas(id) ? { localOnSshCanvas: true } : {})
@@ -3750,7 +3753,8 @@ export function TerminalNode({
tmuxClient,
persistent,
sessionHost,
- unavailable
+ unavailable,
+ scrollbackSeeded
}) => {
// The spawn answered: whatever it says, we are no longer waiting on the host.
clearTimeout(slowSpawn)
@@ -4006,7 +4010,10 @@ export function TerminalNode({
if (replay === 'cold-snapshot') {
const snapshot = await scrollbackPromise
if ((toreDown = onDisposed())) return
- if (seedPaint({ replay, superseded, snapshot }) === 'snapshot') {
+ if (
+ seedPaint({ replay, superseded, snapshot, coreSeeded: scrollbackSeeded }) ===
+ 'snapshot'
+ ) {
// The snapshot comes from `capture-pane -p`: LF-separated, no CR bytes. xterm runs
// with convertEol:false, so writing it raw would render as a staircase.
term.write(toXtermText(snapshot))
diff --git a/src/renderer/terminal/terminal-config.test.ts b/src/renderer/terminal/terminal-config.test.ts
index 09b09345f..1611f8ab0 100644
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@ -681,6 +681,19 @@ describe('seedPaint', () => {
expect(seedPaint({ replay: 'cold-snapshot', superseded: false, snapshot: '' })).toBe('none')
})
+ it('paints NOTHING when core already seeded the snapshot into the tmux pane', () => {
+ // The fresh tmux client puts the emulator on the alternate screen at attach, so a copy written
+ // here is hidden an instant later — that was the "session restored never shows" bug. tmux
+ // paints the pane's copy; a second one here would be the same text twice on a non-tmux day.
+ expect(
+ seedPaint({ replay: 'cold-snapshot', superseded: false, snapshot: 'old', coreSeeded: true })
+ ).toBe('none')
+ // Not seeded by core (plain shell / session-host / SSH): the emulator replay still applies.
+ expect(
+ seedPaint({ replay: 'cold-snapshot', superseded: false, snapshot: 'old', coreSeeded: false })
+ ).toBe('snapshot')
+ })
+
it('paints NOTHING on a plain warm reattach — tmux redraws the pane itself', () => {
// Hydrating here is exactly what produced the black bands and duplicated screens: tmux is a
// screen painter, and its repaints leaked into whatever we had seeded.
diff --git a/src/renderer/terminal/terminal-config.ts b/src/renderer/terminal/terminal-config.ts
index f8b199841..19ef18b1a 100644
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@ -521,9 +521,15 @@ export function seedPaint(opts: {
snapshot?: string | null
/** `PtyCreateResult.screen`: present (and non-empty) only for a joiner that did not resize. */
screen?: string | null
+ /**
+ * `PtyCreateResult.scrollbackSeeded`: core already wrote the snapshot into the new tmux PANE.
+ * Then the emulator must be seeded with nothing — tmux paints the restored text itself, and a
+ * second copy written here would only sit on the normal screen the attach is about to leave.
+ */
+ coreSeeded?: boolean
}): SeedPaint {
if (opts.replay === 'none' || opts.superseded) return 'none'
- if (opts.replay === 'cold-snapshot') return opts.snapshot ? 'snapshot' : 'none'
+ if (opts.replay === 'cold-snapshot') return opts.snapshot && !opts.coreSeeded ? 'snapshot' : 'none'
// `warm-attach`: tmux paints this client itself, so the only thing left to write is a joiner's
// captured screen (it never gets a redraw). Everyone else seeds nothing.
return shouldApplyResync(opts.screen) ? 'create-screen' : 'none'
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 40ead30a9..5e0d0baef 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -222,6 +222,18 @@ export interface PtyCreateOptions {
* "not connected" overlay and re-spawns when the master is back.
*/
requireRemote?: boolean
+ /**
+ * "If this create turns out to be a COLD start, I want the persisted scrollback back." Set by a
+ * caller that would otherwise replay the snapshot into its own emulator (i.e. not a node being
+ * opened for the first time with an `initialCommand`).
+ *
+ * It exists because the emulator is the wrong place for it on a tmux-backed session: tmux puts
+ * the client on the alternate screen at attach, hiding anything written before it. With this
+ * set, core writes the snapshot into the new PANE instead and answers
+ * `PtyCreateResult.scrollbackSeeded`. Ignored on a warm attach, a co-attach join, an SSH-project
+ * node and the non-tmux backends — there the caller's own replay still applies.
+ */
+ restoreScrollback?: boolean
/**
* The ONE way a terminal may run on THIS machine while it sits on an SSH project's canvas: the
* local-account login node Settings → Accounts drops onto whatever canvas is active. Core refuses
@@ -452,6 +464,12 @@ export interface PtyCreateResult {
* checked. Nothing was joined or started, and the existing session was left untouched.
*/
unavailable?: 'ssh' | 'codex-account' | 'join-only' | 'held-elsewhere' | 'new-only'
+ /**
+ * Core already put the persisted scrollback (and the "session restored" separator) into the new
+ * tmux pane — see `PtyCreateOptions.restoreScrollback`. The caller must NOT replay the snapshot
+ * into its emulator: tmux paints it and owns it as history. Only ever set with `fresh: true`.
+ */
+ scrollbackSeeded?: boolean
}
/** Payload of `pty:recycled` — see IPC.ptyRecycled and `recycleAction` in the renderer. */