From 0523a820051e451859504955da4a7425fa620012 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 12:47:37 +0100 Subject: [PATCH 1/5] feat(terminal): keep far more scrollback and page older output on demand Terminals kept only 5,000 lines or 8 MiB on the server, sent at most 512 KiB on attach with no way to reach anything older, held 10,000 rows in the client views, and forgot all but 128 exited sessions. Each persist also rewrote the whole history file, which would not scale to larger histories. The server now keeps up to 1,000,000 lines and 256 MiB per terminal by default (T3CODE_TERMINAL_HISTORY_MAX_LINES / _MAX_BYTES override them). History files grow by appends and are rewritten only when the history is cleared or the trimmed prefix outgrows the retained text, so total writes stay under about twice the output; existing files still load, and loading no longer rewrites them. Exited sessions are retained up to 4,096 and 4 GiB of history. An attach sends the newest 512 KiB plus its offset; the new terminal.history RPC returns the 512 KiB page before an offset. Clients prepend pages into the same buffer (now 8 MiB). Web and desktop load a page when the user scrolls to the top and keep the viewed rows in place; mobile gets a "Load earlier output" terminal menu action, since its native views own scrolling. Web, Android, and iOS views hold about 100,000 rows. Co-Authored-By: Claude Opus 5.5 --- .../android/src/main/cpp/t3_terminal_jni.cpp | 2 +- .../t3terminal/TerminalOutputBuffer.kt | 2 +- .../ios/TerminalOutputBuffer.swift | 4 +- .../terminal/ThreadTerminalRouteScreen.tsx | 33 +- .../terminal/terminalOutputWriter.test.ts | 10 +- .../src/features/terminal/terminalTheme.ts | 2 + apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + apps/server/src/terminal/Manager.test.ts | 108 ++++++ apps/server/src/terminal/Manager.ts | 341 +++++++++++++++--- apps/server/src/ws.ts | 1 + .../src/components/ThreadTerminalDrawer.tsx | 18 +- apps/web/src/terminal/ghostty/core.test.ts | 3 +- apps/web/src/terminal/ghostty/core.ts | 2 +- apps/web/src/terminal/ghostty/surface.ts | 19 + docs/user/terminal.md | 19 +- packages/client-runtime/src/state/terminal.ts | 120 +++++- .../src/state/terminalOutput.ts | 122 ++++++- .../src/state/terminalSession.test.ts | 61 ++++ .../src/state/terminalSession.ts | 26 +- packages/contracts/src/rpc.ts | 10 + packages/contracts/src/terminal.ts | 24 +- 22 files changed, 838 insertions(+), 91 deletions(-) diff --git a/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp b/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp index 95760e8ead926..d93e8cc81f85a 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp +++ b/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp @@ -12,7 +12,7 @@ namespace { constexpr uint32_t kSnapshotMagic = 0x54563354; // "T3VT" in little endian. constexpr uint16_t kSnapshotVersion = 1; -constexpr size_t kMaxScrollbackRows = 10000; +constexpr size_t kMaxScrollbackRows = 100000; enum CellFlag : uint16_t { kBold = 1 << 0, diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt index fde3393b911e4..449c93ab78259 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt @@ -2,7 +2,7 @@ package expo.modules.t3terminal import java.util.ArrayDeque -private const val REPLAY_LIMIT = 512 * 1024 +private const val REPLAY_LIMIT = 8 * 1024 * 1024 private const val REPLAY_CHUNK_SIZE = 16 * 1024 // Keep only replay history for intentional terminal recreation. diff --git a/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift b/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift index b25c18cd0b659..95d0c32bde1a6 100644 --- a/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift +++ b/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift @@ -4,7 +4,7 @@ import Foundation final class TerminalOutputBuffer { private var storage = Data() private var retainedStart = 0 - private let limit = 512 * 1024 + private let limit = 8 * 1024 * 1024 var data: Data { storage.subdata(in: retainedStart..= limit { storage = storage.subdata(in: retainedStart.. void; readonly onOpenNewTerminal: () => void; readonly onSelectTerminal: (terminalId: string) => void; + /** Null when the view already holds all the output the server keeps, or all that fits. */ + readonly onLoadOlderOutput: (() => void) | null; }) { return ( props.onSelectTerminal(session.terminalId), })), + ...(props.onLoadOlderOutput === null + ? [] + : [ + { + id: "terminal-load-older", + title: "Load earlier output", + icon: "arrow.up", + subtitle: "Older output the environment still keeps", + onPress: props.onLoadOlderOutput, + }, + ]), { id: "terminal-new", disabled: !props.canOperateTerminal, @@ -829,6 +846,20 @@ function ThreadTerminal(props: { onIncreaseFontSize={handleIncreaseFontSize} onOpenNewTerminal={handleOpenNewTerminal} onSelectTerminal={handleSelectTerminal} + onLoadOlderOutput={ + canLoadOlderTerminalOutput(terminal.output, DEFAULT_MAX_TERMINAL_BUFFER_BYTES) + ? () => + void terminalEnvironment.loadOlderOutput( + appAtomRegistry, + { + environmentId: selectedThread.environmentId, + threadId: selectedThread.id, + terminalId, + }, + terminal.output, + ) + : null + } /> diff --git a/apps/mobile/src/features/terminal/terminalOutputWriter.test.ts b/apps/mobile/src/features/terminal/terminalOutputWriter.test.ts index 877346e58aafd..685edf247f820 100644 --- a/apps/mobile/src/features/terminal/terminalOutputWriter.test.ts +++ b/apps/mobile/src/features/terminal/terminalOutputWriter.test.ts @@ -26,7 +26,9 @@ it("appends across rollover without replay and seeds fresh writers with only bou let state = EMPTY_TERMINAL_BUFFER_STATE; const chunks: string[] = []; await writer.write(state.output); - for (let index = 0; index < 128; index += 1) { + const retainedChunks = DEFAULT_MAX_TERMINAL_BUFFER_BYTES / (16 * 1024); + const total = retainedChunks * 4; + for (let index = 0; index < total; index += 1) { const chunk = `${index}\r\n`.padEnd(16 * 1024, "x"); chunks.push(chunk); state = append(state, chunk); @@ -34,10 +36,12 @@ it("appends across rollover without replay and seeds fresh writers with only bou expect(write).toHaveBeenLastCalledWith(chunk, false); } expect(state.output.retainedBytes).toBe(DEFAULT_MAX_TERMINAL_BUFFER_BYTES); - const retained = chunks.slice(-32).join(""); + const retained = chunks.slice(-retainedChunks).join(""); expect(terminalOutputText(state.output)).toBe(retained); expect(write.mock.calls.filter(([, reset]) => reset)).toEqual([["", true]]); - expect(write.mock.calls.reduce((total, [data]) => total + data.length, 0)).toBe(2 * 1024 * 1024); + expect(write.mock.calls.reduce((total, [data]) => total + data.length, 0)).toBe( + total * 16 * 1024, + ); const remountedWrite = vi.fn(async () => {}); await createTerminalOutputWriter(remountedWrite).write(state.output); diff --git a/apps/mobile/src/features/terminal/terminalTheme.ts b/apps/mobile/src/features/terminal/terminalTheme.ts index daadfed10c9a4..d5bb6a16555a1 100644 --- a/apps/mobile/src/features/terminal/terminalTheme.ts +++ b/apps/mobile/src/features/terminal/terminalTheme.ts @@ -120,6 +120,8 @@ export function buildGhosttyThemeConfig(theme: TerminalTheme): string { `foreground = ${theme.foreground}`, `cursor-color = ${theme.cursorForeground}`, `cursor-text = ${theme.cursorBackground}`, + // Bytes of scrollback, about 100,000 rows as on web and Android; the default holds 10 MB. + "scrollback-limit = 100000000", ]; for (const [index, color] of theme.palette.entries()) { diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 180f053f111f4..96288c7491d25 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -185,6 +185,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.terminalOpen]: AuthTerminalOperateScope, [WS_METHODS.terminalAttach]: AuthTerminalOperateScope, [WS_METHODS.terminalObserve]: AuthTerminalReadScope, + [WS_METHODS.terminalHistory]: AuthTerminalReadScope, [WS_METHODS.terminalWrite]: AuthTerminalOperateScope, [WS_METHODS.terminalResize]: AuthTerminalOperateScope, [WS_METHODS.terminalClear]: AuthTerminalOperateScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f9a861cca23fb..8116da0cc74f8 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -199,6 +199,7 @@ const RPC_AGGREGATES = { [WS_METHODS.terminalOpen]: "terminal", [WS_METHODS.terminalAttach]: "terminal", [WS_METHODS.terminalObserve]: "terminal", + [WS_METHODS.terminalHistory]: "terminal", [WS_METHODS.terminalWrite]: "terminal", [WS_METHODS.terminalResize]: "terminal", [WS_METHODS.terminalClear]: "terminal", diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index ed4645b18becf..13276da436fcd 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -383,6 +383,8 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen history.append(chunk); expected = retainedHistory(expected + chunk, maxLines, maxBytes); expect(history.value()).toBe(expected); + expect(history.textFrom(history.startOffset)).toBe(expected); + expect(history.endOffset - history.startOffset).toBe(expected.length); } } } @@ -406,6 +408,82 @@ it("bounds long partial lines and joins surrogate pairs across chunk boundaries" } }); +it("pages retained output back to its start without gaps or oversized pages", () => { + const history = new TerminalManager.BoundedTerminalHistory(40, "", 2_000); + for (let line = 0; line < 100; line += 1) + history.append(`line ${line} 損🚀 ${"x".repeat(line % 70)}\n`); + const latest = history.endOffset; + history.append("prompt$ "); + + const pages: string[] = []; + let before = latest; + for (;;) { + const page = history.pageBefore(before, 300); + expect(Buffer.byteLength(page.data)).toBeLessThanOrEqual(300); + expect(page.offset + page.data.length).toBe(before); + // Pages after the first start at a line. + if (page.older) expect(history.textFrom(page.offset - 1)?.[0]).toBe("\n"); + pages.unshift(page.data); + before = page.offset; + if (!page.older) break; + } + expect(before).toBe(history.startOffset); + expect(pages.join("") + "prompt$ ").toBe(history.value()); + + // Offsets keep naming the same text after newer output trims older lines. + const kept = history.textFrom(latest); + history.append("more\n".repeat(30)); + expect(history.textFrom(latest)).toBe(kept + "more\n".repeat(30)); + expect(history.pageBefore(history.startOffset - 1, 300)).toEqual({ + data: "", + offset: history.startOffset, + older: false, + }); + history.clear(); + expect(history.pageBefore(latest, 300).older).toBe(false); +}); + +it("appends history files and rewrites them only when cleared or mostly trimmed", () => { + const history = new TerminalManager.BoundedTerminalHistory(3, "", 1_000); + let file = ""; + const persist = () => { + const write = TerminalManager.planHistoryFileWrite(history, 64); + file = write.append ? file + write.text : write.text; + history.persisted = write.persisted; + expect(Buffer.byteLength(file)).toBe(write.persisted.fileBytes); + // Loading keeps the file's newest lines, which are exactly the history. + if (!history.endsInHighSurrogate) { + expect(new TerminalManager.BoundedTerminalHistory(3, file, 1_000).value()).toBe( + history.value(), + ); + } + return write.append; + }; + + history.append("one\ntwo\n"); + expect(persist()).toBe(false); + history.append("three\nfour\n"); + expect(persist()).toBe(true); + expect(file).toBe("one\ntwo\nthree\nfour\n"); + history.append("x".repeat(80) + "\n"); + expect(persist()).toBe(true); + history.append("a\nb\nc\n"); + // The trimmed prefix outgrew both the retained text and the minimum. + expect(persist()).toBe(false); + expect(file).toBe(history.value()); + + // A split surrogate waits for its pair instead of being written as U+FFFD. + history.append("\ud83d"); + expect(persist()).toBe(true); + history.append("\ude80\n"); + expect(persist()).toBe(true); + expect(file.endsWith("🚀\n")).toBe(true); + + history.clear(); + expect(persist()).toBe(false); + expect(file).toBe(""); +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -1017,6 +1095,36 @@ it.layer( }), ); + it.effect("attaches with the newest output and pages older output contiguously", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(1_000_000, { + historyByteLimit: 64 * 1024 * 1024, + }); + yield* manager.open(openInput()); + const lines = Array.from({ length: 40_000 }, (_, index) => `output line ${index}\n`); + for (let index = 0; index < lines.length; index += 1_000) { + ptyAdapter.processes[0]!.emitData(lines.slice(index, index + 1_000).join("")); + } + const attached = yield* manager.open(openInput()); + expect(attached.olderHistory).toBe(true); + expect(attached.history.endsWith(lines.at(-1)!)).toBe(true); + + let text = attached.history; + let before = attached.historyOffset!; + for (let older = true; older;) { + const page = yield* manager.historyPage({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + before, + }); + text = page.data + text; + before = page.offset; + older = page.olderHistory; + } + expect(text).toBe(lines.join("")); + }), + ); + it.effect("bounds persisted and attached history without truncating live output", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(5, { historyByteLimit: 10 }); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e2061df592d00..bb13ef922b02a 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -4,7 +4,7 @@ import * as NodeCrypto from "node:crypto"; import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { DEFAULT_TERMINAL_ID, - DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + TERMINAL_HISTORY_PAGE_BYTES, TerminalCwdError, TerminalCwdNotDirectoryError, TerminalCwdNotFoundError, @@ -21,6 +21,8 @@ import { type TerminalAttachStreamEvent, type TerminalClearInput, type TerminalCloseInput, + type TerminalHistoryInput, + type TerminalHistoryPage, type TerminalEvent, type TerminalMetadataStreamEvent, type TerminalOpenInput, @@ -45,6 +47,7 @@ import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-regis import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -91,8 +94,11 @@ export { TerminalWriteError, }; -const DEFAULT_HISTORY_LINE_LIMIT = 5_000; -const DEFAULT_HISTORY_BYTE_LIMIT = 8 * 1024 * 1024; +const DEFAULT_HISTORY_LINE_LIMIT = 1_000_000; +const DEFAULT_HISTORY_BYTE_LIMIT = 256 * 1024 * 1024; +// History files grow by appends; a rewrite drops their trimmed prefix once it is at +// least as large as the retained history, so total writes stay within twice the output. +const MIN_HISTORY_COMPACTION_BYTES = 4 * 1024 * 1024; // eCryptfs permits 143-byte names. const MAX_HISTORY_FILENAME_BYTES = 143; const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024; @@ -108,7 +114,8 @@ const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as // Discover children started without terminal input or output. const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; -const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; +const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 4_096; +const DEFAULT_MAX_RETAINED_INACTIVE_HISTORY_BYTES = 4 * 1024 * 1024 * 1024; const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; // The tmux/screen/Zellij keys name the multiplexer pane that launched the server, @@ -207,6 +214,11 @@ export class TerminalManager extends Context.Service< registerCleanup?: (stop: () => void) => void, ) => Effect.Effect<() => void, TerminalError>; + /** Retained output before a snapshot's or earlier page's offset, newest first. */ + readonly historyPage: ( + input: TerminalHistoryInput, + ) => Effect.Effect; + readonly write: (input: TerminalWriteInput) => Effect.Effect; readonly resize: ( @@ -387,6 +399,8 @@ function terminalWireLabel(session: TerminalSessionState): string { } function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { + // Older output is paged in with `terminal.history`, so an attach stays small. + const newest = session.history.pageBefore(session.history.endOffset, TERMINAL_HISTORY_PAGE_BYTES); return { threadId: session.threadId, terminalId: session.terminalId, @@ -394,7 +408,9 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: newest.data, + historyOffset: newest.offset, + olderHistory: newest.older, exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -876,6 +892,14 @@ interface TerminalHistoryChunk { lineBreaks: number; } +/** How much of a history file already holds this history's text. */ +interface PersistedHistoryFile { + readonly generation: number; + /** History offset where the file's text ends. */ + readonly end: number; + readonly fileBytes: number; +} + export class BoundedTerminalHistory { private readonly maxLines: number; private readonly maxBytes: number; @@ -883,9 +907,15 @@ export class BoundedTerminalHistory { private start = 0; private byteLength = 0; private lineBreaks = 0; + private length = 0; + // Offsets count UTF-16 code units appended over the history's life, so a range + // keeps naming the same text while newer output arrives and older output is trimmed. + private end = 0; + private generation = 0; // Reading the old string's tail on each append can force chunk concatenation. private lastCodeUnit: number | undefined; private cachedValue: string | null = ""; + persisted: PersistedHistoryFile | null = null; constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) { this.maxLines = maxLines; @@ -893,12 +923,38 @@ export class BoundedTerminalHistory { this.append(initial); } + get startOffset(): number { + return this.end - this.length; + } + + get endOffset(): number { + return this.end; + } + + get bytes(): number { + return this.byteLength; + } + + get endsInHighSurrogate(): boolean { + const last = this.lastCodeUnit; + return last !== undefined && last >= 0xd800 && last <= 0xdbff; + } + + /** Changes whenever retained text is dropped without trimming, as by `clear`. */ + get clearGeneration(): number { + return this.generation; + } + append(text: string): void { if (text.length === 0) return; this.cachedValue = null; if (this.maxBytes <= 0 || this.maxLines <= 0) { this.clear(); - if (this.maxBytes > 0 && text.endsWith("\n")) this.appendChunk("\n"); + this.end += text.length; + if (this.maxBytes > 0 && text.endsWith("\n")) { + this.end -= 1; + this.appendChunk("\n"); + } return; } @@ -918,6 +974,8 @@ export class BoundedTerminalHistory { previous.data += text[0]; previous.byteLength += 1; this.byteLength += 1; + this.length += 1; + this.end += 1; this.lastCodeUnit = firstCode; offset = 1; this.trim(); @@ -958,6 +1016,8 @@ export class BoundedTerminalHistory { } this.byteLength += byteLength; this.lineBreaks += lineBreaks; + this.length += data.length; + this.end += data.length; this.lastCodeUnit = data.charCodeAt(data.length - 1); this.cachedValue = null; } @@ -966,6 +1026,7 @@ export class BoundedTerminalHistory { const first = this.chunks[this.start]!; this.byteLength -= first.byteLength; this.lineBreaks -= first.lineBreaks; + this.length -= first.data.length; this.chunks[this.start++] = undefined; } @@ -980,6 +1041,7 @@ export class BoundedTerminalHistory { first.lineBreaks -= lineBreaks; this.byteLength -= byteLength; this.lineBreaks -= lineBreaks; + this.length -= offset; } private trim(): void { @@ -1037,6 +1099,8 @@ export class BoundedTerminalHistory { this.start = 0; this.byteLength = 0; this.lineBreaks = 0; + this.length = 0; + this.generation += 1; this.lastCodeUnit = undefined; this.cachedValue = ""; } @@ -1049,6 +1113,120 @@ export class BoundedTerminalHistory { .join(""); return this.cachedValue; } + + private codeUnitBefore(offset: number): number | undefined { + let chunkEnd = this.end; + for (let index = this.chunks.length - 1; index >= this.start; index -= 1) { + const data = this.chunks[index]!.data; + const chunkStart = chunkEnd - data.length; + if (chunkStart < offset) return data.charCodeAt(offset - 1 - chunkStart); + chunkEnd = chunkStart; + } + return undefined; + } + + /** The retained text from `offset` to the end, or null once `offset` was trimmed away. */ + textFrom(offset: number): string | null { + if (offset < this.startOffset || offset > this.end) return null; + const pieces: string[] = []; + let chunkEnd = this.end; + for (let index = this.chunks.length - 1; index >= this.start && chunkEnd > offset; index -= 1) { + const data = this.chunks[index]!.data; + const chunkStart = chunkEnd - data.length; + pieces.push(chunkStart >= offset ? data : data.slice(offset - chunkStart)); + chunkEnd = chunkStart; + } + return pieces.reverse().join(""); + } + + /** + * Up to `maxBytes` of the retained text ending at `before`, starting at a line + * when one begins inside it. `older` says whether retained text precedes it. + */ + pageBefore( + before: number, + maxBytes: number, + ): { readonly data: string; readonly offset: number; readonly older: boolean } { + const end = Math.min(before, this.end); + if (end <= this.startOffset || maxBytes <= 0) { + return { data: "", offset: Math.max(end, this.startOffset), older: false }; + } + const pieces: string[] = []; + let bytes = 0; + let chunkEnd = this.end; + let index = this.chunks.length - 1; + for (; index >= this.start && bytes < maxBytes; index -= 1) { + const chunk = this.chunks[index]!; + const chunkStart = chunkEnd - chunk.data.length; + if (chunkStart < end) { + const data = chunkEnd <= end ? chunk.data : chunk.data.slice(0, end - chunkStart); + pieces.push(data); + bytes += data === chunk.data ? chunk.byteLength : Buffer.byteLength(data); + } + chunkEnd = chunkStart; + } + pieces.reverse(); + let offset = chunkEnd; + if (bytes > maxBytes) { + // Drop whole code points from the front until the page fits. + const first = pieces[0]!; + let cut = 0; + while (bytes > maxBytes && cut < first.length) { + const codePoint = first.codePointAt(cut)!; + bytes -= codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + cut += codePoint <= 0xffff ? 1 : 2; + } + pieces[0] = first.slice(cut); + offset += cut; + } + let data = pieces.join(""); + if (offset > this.startOffset && this.codeUnitBefore(offset) !== 10) { + // A page cut inside a line would draw that line's tail as if it were whole. + const lineStart = data.indexOf("\n") + 1; + if (lineStart > 0 && lineStart < data.length) { + data = data.slice(lineStart); + offset += lineStart; + } + } + return { data, offset, older: offset > this.startOffset }; + } +} + +/** + * What to write so a history file ends with `history`: the text it lacks, or the whole + * history when the file was cleared, is unknown, or its trimmed prefix has outgrown the + * retained text. Loading reads only the file's tail, so a smaller prefix can stay. + */ +export function planHistoryFileWrite( + history: BoundedTerminalHistory, + minCompactionBytes = MIN_HISTORY_COMPACTION_BYTES, +): { readonly append: boolean; readonly text: string; readonly persisted: PersistedHistoryFile } { + const generation = history.clearGeneration; + // A trailing high surrogate is written with its pair, or encoding would replace it. + const end = history.endsInHighSurrogate ? history.endOffset - 1 : history.endOffset; + const persisted = history.persisted; + const appended = + persisted !== null && persisted.generation === generation + ? history.textFrom(persisted.end) + : null; + if (persisted !== null && appended !== null) { + const text = appended.slice(0, Math.max(0, end - persisted.end)); + const fileBytes = persisted.fileBytes + Buffer.byteLength(text); + const trimmedBytes = fileBytes - history.bytes; + if (trimmedBytes < Math.max(minCompactionBytes, history.bytes)) { + return { + append: true, + text, + persisted: { generation, end: Math.max(end, persisted.end), fileBytes }, + }; + } + } + const text = history.textFrom(history.startOffset)!.slice(0, end - history.startOffset); + return { + append: false, + text, + persisted: { generation, end, fileBytes: Buffer.byteLength(text) }, + }; } // Pop beyond Ghostty's eight-entry Kitty stacks on both screens before clearing @@ -1418,6 +1596,7 @@ interface TerminalManagerOptions { subprocessPollIntervalMs?: number; processKillGraceMs?: number; maxRetainedInactiveSessions?: number; + maxRetainedInactiveHistoryBytes?: number; registerTerminalProcesses?: (input: { readonly threadId: string; readonly terminalId: string; @@ -1495,8 +1674,29 @@ export const make = Effect.fn("TerminalManager.make")(function* () { env, }), ); + const historyLimit = (name: string, fallback: number) => + Config.Int(name).pipe( + Config.withDefault(fallback), + Effect.filterOrFail( + (value) => value > 0, + () => `${name} must be positive`, + ), + Effect.catch((error) => + Effect.logWarning("ignoring invalid terminal history limit", { name, error }).pipe( + Effect.as(fallback), + ), + ), + ); return yield* makeWithOptions({ logsDir: terminalLogsDir, + historyLineLimit: yield* historyLimit( + "T3CODE_TERMINAL_HISTORY_MAX_LINES", + DEFAULT_HISTORY_LINE_LIMIT, + ), + historyByteLimit: yield* historyLimit( + "T3CODE_TERMINAL_HISTORY_MAX_BYTES", + DEFAULT_HISTORY_BYTE_LIMIT, + ), ptyAdapter, processTable: nativeTelemetry.processTable.pipe( Effect.mapError( @@ -1623,6 +1823,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; const maxRetainedInactiveSessions = options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS; + const maxRetainedInactiveHistoryBytes = + options.maxRetainedInactiveHistoryBytes ?? DEFAULT_MAX_RETAINED_INACTIVE_HISTORY_BYTES; const registerTerminalProcesses = options.registerTerminalProcesses ?? (() => Effect.void); const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void); @@ -1922,6 +2124,23 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* registerKillFiber(process, fiber); }); + const writeHistoryFile = Effect.fn("terminal.writeHistoryFile")(function* ( + filePath: string, + history: BoundedTerminalHistory, + ) { + const write = planHistoryFileWrite(history); + // A failed write leaves the file unknown, so the next one rewrites it. + history.persisted = null; + if (write.append) { + if (write.text.length > 0) { + yield* fileSystem.writeFileString(filePath, write.text, { flag: "a" }); + } + } else { + yield* fileSystem.writeFileString(filePath, write.text); + } + history.persisted = write.persisted; + }); + const persistWorker = yield* makeKeyedCoalescingWorker< string, PersistHistoryRequest, @@ -1942,17 +2161,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return; } - yield* fileSystem - .writeFileString(historyPath(threadId, terminalId), request.history.value()) - .pipe( - Effect.catch((error) => - Effect.logWarning("failed to persist terminal history", { - threadId, - terminalId, - error, - }), - ), - ); + yield* writeHistoryFile(historyPath(threadId, terminalId), request.history).pipe( + Effect.catch((error) => + Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + error, + }), + ), + ); }), }); @@ -2006,7 +2223,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } return { history: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(start, length)), - truncated: offset > 0n, + fileBytes: Number(offset) + length, }; }); @@ -2026,38 +2243,36 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func )) ) continue; - const { history: raw, truncated } = yield* readHistoryTail(sourcePath).pipe( + const { history: raw, fileBytes } = yield* readHistoryTail(sourcePath).pipe( Effect.scoped, Effect.mapError( (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }), ), ); const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit); - const capped = history.value(); - if (migrating || truncated || capped !== raw) { - const write = migrating - ? Effect.gen(function* () { - const temporaryPath = yield* fileSystem.makeTempFileScoped({ - directory: logsDir, - prefix: ".history-", - }); - yield* fileSystem.writeFileString(temporaryPath, capped); - yield* fileSystem.rename(temporaryPath, nextPath); - }).pipe(Effect.scoped) - : fileSystem.writeFileString(nextPath, capped); - yield* write.pipe( + // The file ends with the retained history; appends compact away any longer prefix. + history.persisted = { + generation: history.clearGeneration, + end: history.endOffset, + fileBytes, + }; + if (migrating) { + const capped = history.value(); + yield* Effect.gen(function* () { + const temporaryPath = yield* fileSystem.makeTempFileScoped({ + directory: logsDir, + prefix: ".history-", + }); + yield* fileSystem.writeFileString(temporaryPath, capped); + yield* fileSystem.rename(temporaryPath, nextPath); + }).pipe( + Effect.scoped, Effect.mapError( (cause) => - new TerminalHistoryError({ - operation: migrating ? "migrate" : "truncate", - threadId, - terminalId, - cause, - }), + new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }), ), ); - } - if (migrating) { + history.persisted = { ...history.persisted, fileBytes: Buffer.byteLength(capped) }; yield* fileSystem.remove(sourcePath, { force: true }).pipe( Effect.catch((error) => Effect.logWarning("failed to remove legacy terminal history", { @@ -2169,7 +2384,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const inactiveSessions = [...state.sessions.values()].filter( (session) => session.status !== "running", ); - if (inactiveSessions.length <= maxRetainedInactiveSessions) { + let inactiveBytes = inactiveSessions.reduce( + (total, session) => total + session.history.bytes, + 0, + ); + if ( + inactiveSessions.length <= maxRetainedInactiveSessions && + inactiveBytes <= maxRetainedInactiveHistoryBytes + ) { return [undefined, state] as const; } @@ -2182,11 +2404,20 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const sessions = new Map(state.sessions); - const toEvict = inactiveSessions.length - maxRetainedInactiveSessions; - for (const session of inactiveSessions.slice(0, toEvict)) { + let retained = inactiveSessions.length; + // Evicted histories stay on disk and load again when the terminal reopens. + for (const session of inactiveSessions) { + if ( + retained <= maxRetainedInactiveSessions && + inactiveBytes <= maxRetainedInactiveHistoryBytes + ) { + break; + } const key = toSessionKey(session.threadId, session.terminalId); sessions.delete(key); closedSessionKeys.add(key); + retained -= 1; + inactiveBytes -= session.history.bytes; } return [undefined, { ...state, sessions }] as const; @@ -2841,15 +3072,20 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (Option.isNone(existing)) { yield* flushPersist(input.threadId, terminalId); const inherited = yield* readHistory(input.threadId, terminalId); + const inheritedText = inherited.value(); const history = new BoundedTerminalHistory( historyLineLimit, - neutralizeInheritedHistory( - inherited.value(), - historyLineLimit, - Math.min(historyByteLimit, DEFAULT_MAX_TERMINAL_BUFFER_BYTES), - ), + neutralizeInheritedHistory(inheritedText, historyLineLimit, historyByteLimit), historyByteLimit, ); + // The file already holds the inherited text, so the reset suffix can be appended. + if (inherited.persisted !== null && history.value().startsWith(inheritedText)) { + history.persisted = { + generation: history.clearGeneration, + end: history.startOffset + inheritedText.length, + fileBytes: inherited.persisted.fileBytes, + }; + } const cols = input.cols ?? DEFAULT_OPEN_COLS; const rows = input.rows ?? DEFAULT_OPEN_ROWS; const session: TerminalSessionState = { @@ -3479,9 +3715,18 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* closeIdle(input); }); + const historyPage: TerminalManager["Service"]["historyPage"] = Effect.fn("terminal.historyPage")( + function* (input) { + const session = yield* requireSession(input.threadId, input.terminalId); + const page = session.history.pageBefore(input.before, TERMINAL_HISTORY_PAGE_BYTES); + return { data: page.data, offset: page.offset, olderHistory: page.older }; + }, + ); + return TerminalManager.of({ open, getShell, + historyPage, attachStream, attachOutputStream, observeStream, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 08a2756bfbe6c..b09200f1da22e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3090,6 +3090,7 @@ export const layerWsRpc = ( [WS_METHODS.terminalResize]: (input, metadata) => terminalManager.resize(input, terminalViewerId(metadata)), [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), + [WS_METHODS.terminalHistory]: (input) => terminalManager.historyPage(input), [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), [WS_METHODS.terminalObserve]: (input) => terminalOutputStream( diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 049589d0b671a..018288dd9b475 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -161,10 +161,13 @@ function writeSystemMessage( } export function writeTerminalOutputUpdate( - terminal: Pick, + terminal: Pick & + Partial>, update: TerminalOutputUpdate, ): void { - if (update.type === "reset") { + if (update.type === "reset" && update.prepended && terminal.prependAndWrite) { + terminal.prependAndWrite(update.data); + } else if (update.type === "reset") { terminal.resetAndWrite(update.data); } else if (update.type === "append") { terminal.write(update.data); @@ -178,7 +181,8 @@ export function synchronizeTerminalOutput( terminal: Pick< GhosttyTerminalSurface, "resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection" - >, + > & + Partial>, session: Pick, cursor: TerminalOutputCursor, ): TerminalOutputCursor { @@ -629,6 +633,13 @@ function TerminalSessionViewport({ (listener: (session: TerminalSessionState) => void) => appAtomRegistry.subscribe(terminalSessionAtom, listener), ); + const loadOlderOutput = useEffectEvent(() => { + void terminalEnvironment.loadOlderOutput( + appAtomRegistry, + { environmentId, threadId, terminalId }, + readTerminalSession().output, + ); + }); const writeTerminal = useEffectEvent((data: string) => runTerminalWrite({ environmentId, @@ -731,6 +742,7 @@ function TerminalSessionViewport({ canActivateLink: (text) => canActivateTerminalLink(text), validateLink: (text) => validateTerminalLink(text), onLinkHover: (text) => setLinkPath(text !== null && !isTerminalUrl(text) ? text : null), + onScrollbackStart: () => loadOlderOutput(), // Surface listeners start before WASM loading finishes and the terminal handler exists. onContextMenu: (event) => { if (terminalRef.current) void showTerminalContextMenu(event); diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index 5e51c7b4be378..9d00a3fc32467 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -321,7 +321,8 @@ describe("GhosttyTerminalCore snapshots", () => { writeTerminalOutputUpdate(core, initial); const reset = vi.spyOn(core, "resetAndWrite"); const data = "line\r\n".repeat(8192); - for (let index = 0; index < 16; index += 1) state = append(state, data); + const appends = Math.ceil((1.5 * DEFAULT_MAX_TERMINAL_BUFFER_BYTES) / data.length); + for (let index = 0; index < appends; index += 1) state = append(state, data); const recovery = readTerminalOutputUpdate(state.output, initial.cursor); if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`); diff --git a/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index b8ca5a624636f..e92e722fedd7a 100644 --- a/apps/web/src/terminal/ghostty/core.ts +++ b/apps/web/src/terminal/ghostty/core.ts @@ -9,7 +9,7 @@ import { GhosttyRuntime, loadGhosttyRuntime } from "./runtime"; const GHOSTTY_SUCCESS = 0; const GHOSTTY_OUT_OF_SPACE = -3; -const MAX_SCROLLBACK_ROWS = 10_000; +const MAX_SCROLLBACK_ROWS = 100_000; // wasm32 GhosttyTerminalSelectionFormatOptions layout at the pinned libghostty-vt revision. const SELECTION_FORMAT_OPTIONS_SIZE = 16; const PALETTE_BYTES = 256 * 3; diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index f1db43056f76f..44e096fff1698 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -531,6 +531,8 @@ export interface GhosttyTerminalSurfaceOptions { readonly onLinkHover?: (text: string | null) => void; /** The host must prevent the default menu; native Paste cannot reach a canvas terminal. */ readonly onContextMenu?: (event: MouseEvent) => void; + /** The user scrolled up to the oldest row the view holds. */ + readonly onScrollbackStart?: () => void; } export class GhosttyTerminalSurface { @@ -776,6 +778,20 @@ export class GhosttyTerminalSurface { this.requestRender(); } + /** + * Replaces the contents with `data`, which only adds older output in front of what is + * shown, keeping the rows the user is reading in place. + */ + prependAndWrite(data: string): void { + if (this.disposed) return; + const before = this.core.scrollbarState(); + this.resetAndWrite(data); + const after = this.core.scrollbarState(); + if (before === null || after === null) return; + const rowsBelow = before.total - before.len - before.offset; + if (rowsBelow > 0) this.scrollViewport(after.total - after.len - rowsBelow - after.offset); + } + resetAndWrite(data: string): void { if (this.disposed) return; this.cancelSynchronizedRenderTimer(); @@ -1931,6 +1947,9 @@ export class GhosttyTerminalSurface { delta = offset - state.offset; this.scrollbarState = { ...state, offset }; } + if (delta < 0 && state !== null && state.offset + delta <= 0) { + this.options.onScrollbackStart?.(); + } if (delta === 0) return; this.core.scroll(delta); this.forceFullRender = true; diff --git a/docs/user/terminal.md b/docs/user/terminal.md index dd921eb9a9650..cec71e35f79b1 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -1,18 +1,23 @@ # Terminal history -Each terminal keeps up to 5,000 lines and 8 MiB of scrollback on its environment -server. T3 Code removes the oldest output when either limit is reached. A long -line can be shortened at the start. New terminal output is not truncated. - -These limits apply when you reconnect and when T3 Code restores saved terminal -history. A client can show less scrollback than the server keeps. +Each terminal keeps up to 1,000,000 lines and 256 MiB of scrollback on its +environment server. T3 Code removes the oldest output when either limit is +reached. A long line can be shortened at the start. New terminal output is not +truncated. To change the limits, set `T3CODE_TERMINAL_HISTORY_MAX_LINES` or +`T3CODE_TERMINAL_HISTORY_MAX_BYTES` in the environment that starts the server. + +When you open or reconnect to a terminal, it shows the most recent output first. +On web and desktop, scrolling to the top loads earlier output. On iPhone, iPad, +and Android, choose **Load earlier output** in the terminal menu. Each client +holds up to 8 MiB or 100,000 rows of a terminal's output; earlier output stays +on the server. On web and desktop, use Shift+PageUp and Shift+PageDown to read scrollback without leaving terminal input. Ctrl+Shift+Home and Ctrl+Shift+End jump to the start and latest output; use Cmd instead of Ctrl on macOS. Full-screen terminal programs keep these navigation keys. -To copy all retained output, choose Select all in the terminal's context menu, +To copy all output the client holds, choose Select all in the terminal's context menu, then copy. Cmd+A on macOS and Ctrl+Shift+A elsewhere select the same output. Ctrl+A still moves to the beginning of shell input on Windows and Linux. Jump to latest in the context menu returns to the current output. diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index a39e47b1340b4..5afa09f22c4c1 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -1,6 +1,8 @@ import { type EnvironmentId, type TerminalAttachInput, + type TerminalAttachStreamEvent, + type TerminalHistoryPage, type TerminalCloseInput, type TerminalOpenInput, type TerminalResizeInput, @@ -10,6 +12,7 @@ import { WS_METHODS, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; @@ -28,8 +31,14 @@ import { EMPTY_TERMINAL_BUFFER_STATE, nextTerminalAttachSeedState, type TerminalBufferState, + type TerminalOlderHistoryEvent, } from "./terminalSession.ts"; -import { terminalOutputText } from "./terminalOutput.ts"; +import { + canLoadOlderTerminalOutput, + terminalOutputText, + type TerminalOutputState, +} from "./terminalOutput.ts"; +import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts"; export function createTerminalEnvironmentAtoms( runtime: Atom.AtomRuntime, @@ -51,30 +60,61 @@ export function createTerminalEnvironmentAtoms( readonly input: { readonly threadId: string; readonly terminalId?: string | undefined }; }) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]); const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey }; + // Older pages are requested beside the stream and applied in order with its events. + const olderHistoryListeners = new Map void>>(); + const olderHistoryKey = (input: { readonly threadId: string; readonly terminalId: string }) => + JSON.stringify([input.threadId, input.terminalId]); + const withOlderHistory = ( + input: { readonly threadId: string; readonly terminalId: string }, + stream: Stream.Stream, + ) => + stream.pipe( + Stream.merge( + Stream.callback((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const key = olderHistoryKey(input); + const listener = (page: TerminalHistoryPage) => { + Queue.offerUnsafe(queue, { type: "olderHistory", page }); + }; + let listeners = olderHistoryListeners.get(key); + if (!listeners) olderHistoryListeners.set(key, (listeners = new Set())); + listeners.add(listener); + return () => { + listeners.delete(listener); + if (listeners.size === 0) olderHistoryListeners.delete(key); + }; + }), + (release) => Effect.sync(release), + ), + ), + { haltStrategy: "left" }, + ), + Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent), + ); + const pendingOlderHistory = new Set(); const atoms = { observe: createEnvironmentSubscriptionAtomFamily(runtime, { label: "environment-data:terminal:observe", subscribe: (input: EnvironmentRpcInput) => - Stream.suspend(() => - subscribe(WS_METHODS.terminalObserve, input).pipe( - Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent), - ), - ), + Stream.suspend(() => withOlderHistory(input, subscribe(WS_METHODS.terminalObserve, input))), }), attach: createEnvironmentSubscriptionAtomFamily(runtime, { label: "environment-data:terminal:attach", subscribe: (input: EnvironmentRpcInput) => { // Retry an unanswered first attach unchanged so it can still open the shell. let replied = false; - return subscribeDynamic(WS_METHODS.terminalAttach, () => - Effect.sync(() => (replied ? { ...input, resume: true } : input)), - ).pipe( - Stream.onFirst(() => - Effect.sync(() => { - replied = true; - }), + return withOlderHistory( + input, + subscribeDynamic(WS_METHODS.terminalAttach, () => + Effect.sync(() => (replied ? { ...input, resume: true } : input)), + ).pipe( + Stream.onFirst(() => + Effect.sync(() => { + replied = true; + }), + ), ), - Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent), ); }, }), @@ -115,9 +155,61 @@ export function createTerminalEnvironmentAtoms( scheduler: lifecycleScheduler, concurrency: lifecycleConcurrency, }), + history: createEnvironmentRpcCommand(runtime, { + label: "environment-data:terminal:history", + tag: WS_METHODS.terminalHistory, + onSuccess: (target, _registry, page) => + Effect.sync(() => { + for (const listener of olderHistoryListeners.get(olderHistoryKey(target.input)) ?? []) { + listener(page); + } + }), + }), + }; + /** + * Fetches the page of server output just before what `output` holds, when there is one + * and it fits. The page reaches the terminal's attach or observe state as it lands. + */ + const loadOlderOutput = async ( + registry: AtomRegistry.AtomRegistry, + target: { + readonly environmentId: EnvironmentId; + readonly threadId: string; + readonly terminalId: string; + }, + output: TerminalOutputState, + ): Promise => { + if ( + output.historyOffset === null || + !canLoadOlderTerminalOutput(output, DEFAULT_MAX_TERMINAL_BUFFER_BYTES) + ) { + return; + } + const key = JSON.stringify([target.environmentId, target.threadId, target.terminalId]); + if (pendingOlderHistory.has(key)) return; + pendingOlderHistory.add(key); + try { + await runAtomCommand( + registry, + atoms.history, + { + environmentId: target.environmentId, + input: { + threadId: target.threadId, + terminalId: target.terminalId, + before: output.historyOffset, + }, + }, + // An older server lacks the method; the view keeps what it has. + { reportFailure: false }, + ); + } finally { + pendingOlderHistory.delete(key); + } }; return { ...atoms, + loadOlderOutput, createSession: (options: TerminalSessionOptions) => createTerminalSession(atoms, options), }; } diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts index df4d2ee03955c..0625db2283d2a 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -10,6 +10,23 @@ export interface TerminalOutputState { readonly retainedBytes: number; readonly resetVersion: number; readonly nextOffset: number; + /** + * The server's offset of the first retained character, for paging in older output. + * Null when unknown: an older server, or live output pushed out every server page. + */ + readonly historyOffset: number | null; + /** How many leading characters are server history, whose offsets are known. */ + readonly historyLength: number; + /** The server keeps output before `historyOffset`. */ + readonly olderHistory: boolean; + /** The last reset only added older output in front of what was there. */ + readonly prepended: boolean; +} + +/** Where a server snapshot or page of history starts. */ +export interface TerminalHistoryAnchor { + readonly offset: number; + readonly older: boolean; } export interface TerminalOutputCursor { @@ -33,6 +50,8 @@ export type TerminalOutputUpdate = readonly type: "reset"; readonly data: string; readonly cursor: TerminalOutputCursor; + /** Only older output was added before what the reader had, so it can keep its place. */ + readonly prepended: boolean; } | { readonly type: "append"; @@ -41,7 +60,8 @@ export type TerminalOutputUpdate = }; const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024; -const MAX_TERMINAL_OUTPUT_CHUNKS = 1_024; +// Enough 16 KiB chunks for the default buffer; compaction keeps chunks near that size. +const MAX_TERMINAL_OUTPUT_CHUNKS = 2_048; const textEncoder = new TextEncoder(); // A BOM at a retained chunk boundary is terminal data, not an encoding marker. const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); @@ -52,6 +72,10 @@ export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze({ retainedBytes: 0, resetVersion: 0, nextOffset: 0, + historyOffset: null, + historyLength: 0, + olderHistory: false, + prepended: false, }); interface Utf8Chunk { @@ -190,11 +214,15 @@ function appendOutput( if (data.length === 0) return current; if (maxBufferBytes <= 0) { return { - generation: current.generation, + ...current, chunks: [], retainedBytes: 0, resetVersion: current.resetVersion + 1, nextOffset: current.nextOffset + data.length, + historyOffset: null, + historyLength: 0, + olderHistory: false, + prepended: false, }; } const appended = splitOutputChunks( @@ -235,12 +263,34 @@ function appendOutput( } } + const dropped = + (retainedChunks[0]?.startOffset ?? appended.nextOffset) - + (current.chunks[0]?.startOffset ?? current.nextOffset); return { - generation: current.generation, + ...current, chunks: retainedChunks, retainedBytes, - resetVersion: current.resetVersion, nextOffset: appended.nextOffset, + ...dropHistory(current, dropped), + }; +} + +function dropHistory( + current: TerminalOutputState, + dropped: number, +): Pick { + if (dropped === 0) { + const { historyOffset, historyLength, olderHistory } = current; + return { historyOffset, historyLength, olderHistory }; + } + // Live output differs from what the server keeps, so offsets end with its history. + if (current.historyOffset === null || dropped > current.historyLength) { + return { historyOffset: null, historyLength: 0, olderHistory: false }; + } + return { + historyOffset: current.historyOffset + dropped, + historyLength: current.historyLength - dropped, + olderHistory: true, }; } @@ -248,6 +298,7 @@ function resetOutput( current: TerminalOutputState, data: string, maxBufferBytes: number, + history?: TerminalHistoryAnchor, ): TerminalOutputState { const retained = trimBufferToBytes(data, maxBufferBytes); const reset = splitOutputChunks( @@ -255,12 +306,63 @@ function resetOutput( 0, Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), ); + const trimmed = data.length - retained.length; + return { + generation: current.generation, + chunks: reset.chunks, + retainedBytes: reset.byteLength, + resetVersion: current.resetVersion + 1, + nextOffset: reset.nextOffset, + historyOffset: history === undefined ? null : history.offset + trimmed, + historyLength: history === undefined ? 0 : retained.length, + olderHistory: history !== undefined && (history.older || trimmed > 0), + prepended: false, + }; +} + +/** Whether the server keeps older output that fits in front of what is retained. */ +export function canLoadOlderTerminalOutput( + output: TerminalOutputState, + maxBufferBytes: number, +): boolean { + return ( + output.olderHistory && output.historyOffset !== null && output.retainedBytes < maxBufferBytes + ); +} + +/** + * Puts a page of older server output in front of the retained output, keeping only what + * fits. A page that does not end where the retained history starts is stale and ignored. + */ +function prependOutput( + current: TerminalOutputState, + page: { readonly data: string; readonly offset: number; readonly olderHistory: boolean }, + maxBufferBytes: number, +): TerminalOutputState { + if (current.historyOffset === null || page.offset + page.data.length !== current.historyOffset) { + return current; + } + const fitted = trimBufferToBytes(page.data, maxBufferBytes - current.retainedBytes); + const offset = page.offset + page.data.length - fitted.length; + const olderHistory = page.olderHistory || offset > page.offset; + if (fitted.length === 0) { + return olderHistory === current.olderHistory ? current : { ...current, olderHistory }; + } + const reset = splitOutputChunks( + fitted + terminalOutputText(current), + 0, + Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), + ); return { generation: current.generation, chunks: reset.chunks, retainedBytes: reset.byteLength, resetVersion: current.resetVersion + 1, nextOffset: reset.nextOffset, + historyOffset: offset, + historyLength: current.historyLength + fitted.length, + olderHistory, + prepended: true, }; } @@ -283,7 +385,15 @@ export function readTerminalOutputUpdate( cursor.resetVersion !== output.resetVersion || cursor.offset < (firstChunk?.startOffset ?? output.nextOffset) ) { - return { type: "reset", data: terminalOutputText(output), cursor: nextCursor }; + return { + type: "reset", + data: terminalOutputText(output), + cursor: nextCursor, + prepended: + output.prepended && + cursor.generation === output.generation && + cursor.resetVersion === output.resetVersion - 1, + }; } // Appends and compaction preserve offset order, so unread chunks form a suffix. @@ -306,4 +416,4 @@ export function readTerminalOutputUpdate( }; } -export { appendOutput, resetOutput }; +export { appendOutput, prependOutput, resetOutput }; diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index 4eef70e099750..dc254eebc4c08 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -5,6 +5,7 @@ import { EnvironmentId, TerminalSessionSnapshot, ThreadId } from "@t3tools/contr import { applyTerminalAttachStreamEvent, applyTerminalMetadataStreamEvent, + canLoadOlderTerminalOutput, combineTerminalSessionState, EMPTY_TERMINAL_BUFFER_STATE, INITIAL_TERMINAL_OUTPUT_CURSOR, @@ -275,6 +276,66 @@ describe("terminal session reducers", () => { expect(state.lifecycleVersion).toBe(2); }); + it("prepends older pages contiguously and stops at the buffer or the server's start", () => { + const output = (data: string) => + ({ type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data }) as const; + let state = applyTerminalAttachStreamEvent( + EMPTY_TERMINAL_BUFFER_STATE, + { + type: "snapshot", + snapshot: { ...BASE_SNAPSHOT, history: "c\nd\n", historyOffset: 4, olderHistory: true }, + }, + 12, + ); + let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor; + state = applyTerminalAttachStreamEvent(state, output("$ "), 12); + expect(state.output.historyOffset).toBe(4); + cursor = readTerminalOutputUpdate(state.output, cursor).cursor; + + // A page that does not end where the retained history starts is stale. + const stale = { type: "olderHistory", page: { data: "x\n", offset: 1, olderHistory: true } }; + expect(applyTerminalAttachStreamEvent(state, stale as never, 12)).toBe(state); + + state = applyTerminalAttachStreamEvent( + state, + { type: "olderHistory", page: { data: "b\n", offset: 2, olderHistory: true } }, + 12, + ); + expect(terminalOutputText(state.output)).toBe("b\nc\nd\n$ "); + expect(readTerminalOutputUpdate(state.output, cursor)).toMatchObject({ + type: "reset", + data: "b\nc\nd\n$ ", + prepended: true, + }); + expect(canLoadOlderTerminalOutput(state.output, 12)).toBe(true); + + state = applyTerminalAttachStreamEvent( + state, + { type: "olderHistory", page: { data: "a\n", offset: 0, olderHistory: false } }, + 12, + ); + expect(terminalOutputText(state.output)).toBe("a\nb\nc\nd\n$ "); + expect(canLoadOlderTerminalOutput(state.output, 12)).toBe(false); + + // Live output that pushes out every server character ends paging: it is not server text. + state = applyTerminalAttachStreamEvent(state, output("0123456789X"), 12); + expect(state.output.historyOffset).toBeNull(); + expect(canLoadOlderTerminalOutput(state.output, 12)).toBe(false); + + // Trimming part of the server history moves the anchor and leaves older output loadable. + state = applyTerminalAttachStreamEvent( + EMPTY_TERMINAL_BUFFER_STATE, + { + type: "snapshot", + snapshot: { ...BASE_SNAPSHOT, history: "abcdefgh", historyOffset: 10, olderHistory: false }, + }, + 8, + ); + state = applyTerminalAttachStreamEvent(state, output("12"), 8); + expect(state.output).toMatchObject({ historyOffset: 12, historyLength: 6, olderHistory: true }); + expect(canLoadOlderTerminalOutput(state.output, 8)).toBe(false); + }); + it("does not reuse a renderer cursor when a fresh attach has matching counters", () => { const first = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), { type: "snapshot", diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index e03dc30507685..35323d3726863 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -1,6 +1,7 @@ import type { EnvironmentId, TerminalAttachStreamEvent, + TerminalHistoryPage, TerminalMetadataStreamEvent, TerminalSessionSnapshot, TerminalSummary, @@ -10,11 +11,13 @@ import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts"; import { appendOutput, EMPTY_TERMINAL_OUTPUT_STATE, + prependOutput, resetOutput, type TerminalOutputState, } from "./terminalOutput.ts"; export { + canLoadOlderTerminalOutput, INITIAL_TERMINAL_OUTPUT_CURSOR, readTerminalOutputUpdate, terminalOutputText, @@ -113,7 +116,14 @@ function terminalBufferStateFromSnapshot( current: TerminalBufferState = EMPTY_TERMINAL_BUFFER_STATE, ): TerminalBufferState { return { - output: resetOutput(current.output, snapshot.history, maxBufferBytes), + output: resetOutput( + current.output, + snapshot.history, + maxBufferBytes, + snapshot.historyOffset === undefined + ? undefined + : { offset: snapshot.historyOffset, older: snapshot.olderHistory ?? false }, + ), grid: nextGrid(current.grid, snapshot), status: snapshot.status, error: null, @@ -156,12 +166,24 @@ export function combineTerminalSessionState( }; } +/** A page of older output the client asked for, applied in order with the stream's events. */ +export interface TerminalOlderHistoryEvent { + readonly type: "olderHistory"; + readonly page: TerminalHistoryPage; +} + export function applyTerminalAttachStreamEvent( current: TerminalBufferState, - event: TerminalAttachStreamEvent, + event: TerminalAttachStreamEvent | TerminalOlderHistoryEvent, maxBufferBytes = DEFAULT_MAX_TERMINAL_BUFFER_BYTES, ): TerminalBufferState { switch (event.type) { + case "olderHistory": { + const output = prependOutput(current.output, event.page, maxBufferBytes); + return output === current.output + ? current + : { ...current, output, version: current.version + 1 }; + } case "snapshot": { if (current.version === 0) { return terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes, current); diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 0f6af19188e18..e20ed3a6a8aee 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -263,6 +263,8 @@ import { TerminalObserveInput, TerminalAttachStreamEvent, TerminalClearInput, + TerminalHistoryInput, + TerminalHistoryPage, TerminalCloseInput, TerminalError, TerminalMetadataStreamEvent, @@ -477,6 +479,7 @@ export const WS_METHODS = { terminalOpen: "terminal.open", terminalAttach: "terminal.attach", terminalObserve: "terminal.observe", + terminalHistory: "terminal.history", terminalWrite: "terminal.write", terminalResize: "terminal.resize", terminalClear: "terminal.clear", @@ -1619,6 +1622,12 @@ const WsTerminalObserveRpc = Rpc.make(WS_METHODS.terminalObserve, { stream: true, }); +const WsTerminalHistoryRpc = Rpc.make(WS_METHODS.terminalHistory, { + payload: TerminalHistoryInput, + success: TerminalHistoryPage, + error: Schema.Union([TerminalError, EnvironmentAuthorizationError]), +}); + const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, { payload: TerminalWriteInput, error: Schema.Union([TerminalError, EnvironmentAuthorizationError]), @@ -2232,6 +2241,7 @@ export const WsRpcGroup = RpcGroup.make( WsTerminalWriteRpc, WsTerminalResizeRpc, WsTerminalClearRpc, + WsTerminalHistoryRpc, WsTerminalCloseRpc, WsSubscribeTerminalMetadataRpc, WsPreviewOpenRpc, diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 8731d6ec25c8f..fce3ae3216c55 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -3,7 +3,10 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; export const DEFAULT_TERMINAL_ID = "term-1"; -export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024; +/** How much output a client keeps per terminal, including older pages it loaded. */ +export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 8 * 1024 * 1024; +/** The newest output an attach sends, and the size of each older page after it. */ +export const TERMINAL_HISTORY_PAGE_BYTES = 512 * 1024; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check( @@ -69,6 +72,21 @@ export const TerminalWriteInput = Schema.Struct({ }); export type TerminalWriteInput = Schema.Codec.Encoded; +/** Output the server keeps from before `before`, an offset from a snapshot or earlier page. */ +export const TerminalHistoryInput = Schema.Struct({ + ...TerminalSessionInput.fields, + before: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), +}); +export type TerminalHistoryInput = Schema.Codec.Encoded; + +export const TerminalHistoryPage = Schema.Struct({ + data: Schema.String, + /** Where `data` starts; pass it as `before` for the page before this one. */ + offset: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + olderHistory: Schema.Boolean, +}); +export type TerminalHistoryPage = typeof TerminalHistoryPage.Type; + export const TerminalResizeInput = Schema.Struct({ ...TerminalSessionInput.fields, cols: TerminalColsSchema, @@ -96,7 +114,11 @@ export const TerminalSessionSnapshot = Schema.Struct({ worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema), status: TerminalSessionStatus, pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))), + /** The newest output; `olderHistory` says the server keeps more before it. */ history: Schema.String, + /** Where `history` starts, for `terminal.history`. Absent from older servers. */ + historyOffset: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + olderHistory: Schema.optional(Schema.Boolean), exitCode: Schema.NullOr(Schema.Int), exitSignal: Schema.NullOr(Schema.Int), label: Schema.String.check(Schema.isMaxLength(128)), From 14fc77065ceb82e316e5f7b3783868506fcefa09 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:05:45 +0100 Subject: [PATCH 2/5] feat(search): page thread message search instead of capping it Message search read only the newest 2,000 hits, and of those at most the newest 10,000 index candidates or, without the index, the newest 20,000 messages. Anything older was silently missing from results. Search now pages newest-first by message rowid. Each page still reads at most 2,000 hits, passes over at most 10,000 index candidates (or scans 50,000 messages without the index) and returns up to `limit` ranked threads, so one request stays as fast as before. The result carries a cursor while older messages may hold more; the next request passes it back with the threads already returned, which later pages leave out. Every matching thread in a page's range is either returned or already excluded, so paging to the end misses none. The agent search tool keeps its single top-ranked page. Clients follow pages that found nothing on their own, and the web sidebar and mobile thread list searches show "Search older messages" while more remain. The command palettes keep showing only their best few message matches. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/features/home/HomeScreen.tsx | 8 +- .../threads/ThreadNavigationSidebar.tsx | 11 ++ .../features/threads/thread-list-v2-items.tsx | 29 +++++ apps/mobile/src/state/queries.ts | 8 ++ apps/server/src/mcp/toolkits/thread/tools.ts | 3 +- .../src/orchestration-v2/ThreadSearch.test.ts | 74 +++++++++++- .../src/orchestration-v2/ThreadSearch.ts | 109 +++++++++++++----- apps/web/src/components/Sidebar.tsx | 13 +++ apps/web/src/state/queries.ts | 8 ++ docs/user/thread-sidebar.md | 4 +- .../src/state/threadSearch.test.ts | 52 ++++++++- .../client-runtime/src/state/threadSearch.ts | 55 ++++++++- packages/contracts/src/threadSearch.ts | 16 ++- 13 files changed, 346 insertions(+), 44 deletions(-) diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 4ed447eb69f23..bcc2d5c58f02a 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -66,6 +66,7 @@ import { ThreadListV2Row, ThreadListV2SettledShelfHeader, ThreadListV2ShowMoreRow, + ThreadSearchMoreRow, ThreadListV2SnoozedShelfHeader, ThreadListV2WorkingShelfHeader, } from "../threads/thread-list-v2-items"; @@ -814,7 +815,12 @@ export function HomeScreen(props: HomeScreenProps) { // Lifted above the rows so an iOS filter menu's dismissal morph is not covered. ListHeaderComponentStyle={{ zIndex: 1 }} ListFooterComponent={ - settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? ( + hasSearchQuery && threadSearch.hasMore ? ( + + ) : settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? ( ); + const searchMoreRow = + props.searchQuery.trim().length > 0 && threadSearch.hasMore ? ( + + ) : null; const listEmpty = ( @@ -667,6 +677,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { showsVerticalScrollIndicator={false} style={styles.threadList} ListEmptyComponent={listEmpty} + ListFooterComponent={searchMoreRow} /> diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index d724d8056e95e..eac47167fd89f 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -360,6 +360,35 @@ export const ThreadListV2ShowMoreRow = memo(function ThreadListV2ShowMoreRow(pro ); }); +/** Reads the next page of message matches for a search that has more. */ +export const ThreadSearchMoreRow = memo(function ThreadSearchMoreRow(props: { + readonly pane?: "screen" | "sidebar"; + readonly loading: boolean; + readonly onPress: () => void; +}) { + const label = props.loading ? "Searching older messages
" : "Search older messages"; + return ( + ({ opacity: pressed ? 0.6 : 1 })} + > + + {label} + + + ); +}); + const PENDING_TASK_MENU_ACTIONS: MenuAction[] = [ { id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } }, ]; diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index 837d77ce851cf..7e33d5bded491 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -56,6 +56,7 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, isLoading: false, + hasMore: false, rows: [], }).pipe(Atom.withLabel("mobile:thread-search:empty")); @@ -206,6 +207,9 @@ export function useThreadSearch( scope: ThreadSearchScope = {}, ): { readonly matches: ReadonlyArray; + /** Older messages may hold more matches for the shown query. */ + readonly hasMore: boolean; + readonly loadMore: () => void; /** The query `matches` are for, which lags the typed one while a search runs. */ readonly query: string; readonly isPending: boolean; @@ -262,6 +266,10 @@ export function useThreadSearch( matches: visible.matches, query: visible.query, isPending, + hasMore: searchKey !== null && visible.query === settledQuery && result.hasMore, + loadMore: () => { + if (searchKey !== null) threadSearch.loadMore(appAtomRegistry, searchKey); + }, }; } diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index c6670c4e953d3..feade2f4a43e8 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -195,7 +195,8 @@ const ThreadSearchTool = Tool.make("t3_thread_search", { "Search active threads by title, branch, PR, project, then message text. Skips subagent threads. `projectId`: one project, else yours, else all outside a thread. Not exhaustive.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, - ...OrchestrationSearchThreadsInput.fields, + query: OrchestrationSearchThreadsInput.fields.query, + limit: OrchestrationSearchThreadsInput.fields.limit, projectId: Schema.optional(ProjectId), }), success: Schema.Struct({ diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 421e79f5a0904..fe86e1bc09fff 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -287,7 +287,7 @@ it.layer(layerTest)("ThreadSearch", (it) => { for (const match of ['"needle"', null]) { const plan = yield* sql<{ readonly detail: string; - }>`EXPLAIN QUERY PLAN ${ThreadSearch.messageHitsQuery(sql, { match, substrings: "[]", shortSpellings: "[]", projectId: null, excludedThreadIds: "[]" })}`; + }>`EXPLAIN QUERY PLAN ${ThreadSearch.messageHitsQuery(sql, { match, substrings: "[]", shortSpellings: "[]", projectId: null, excludedThreadIds: "[]", before: 1_000_000, lower: 0 })}`; assert.isFalse( plan.some((row) => row.detail.includes("TEMP B-TREE")), plan.map((row) => row.detail).join("\n"), @@ -802,7 +802,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { }), ); - it.effect("reads at most the newest 10,000 index hits, however many the filters drop", () => + it.effect("reads at most 10,000 index hits per page, however many the filters drop", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; const search = yield* ThreadSearch.ThreadSearch; @@ -834,11 +834,79 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { assert.deepEqual(yield* threadIds("kestrel ci"), [old]); yield* sql`DELETE FROM orchestration_v2_projection_messages WHERE thread_id = ${busy}`; yield* insertBusy(10_000); - assert.deepEqual(yield* threadIds("kestrel ci"), []); + const first = yield* search.search({ query: "kestrel ci" }); + assert.deepEqual(first.matches, []); + assert.isDefined(first.cursor); + // The next page continues below the hits the first one passed over. + const second = yield* search.search({ query: "kestrel ci", cursor: first.cursor! }); + assert.deepEqual( + second.matches.map((match) => match.threadId), + [old], + ); + assert.isUndefined(second.cursor); }), ); }); +it.effect.each([true, false])( + "ThreadSearch pages through every matching thread exactly once (indexed: %s)", + (indexed) => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const search = yield* ThreadSearch.ThreadSearch; + const sql = yield* SqlClient.SqlClient; + const project = ProjectId.make("project:osprey"); + const busy = ThreadId.make("thread:osprey-busy"); + const quiet = Array.from({ length: 7 }, (_, index) => + ThreadId.make(`thread:osprey-${index}`), + ); + yield* createProject(project); + yield* Effect.forEach( + [ + ...quiet.flatMap((threadId, index) => [ + thread(threadId, project), + message(threadId, `osprey-old-${index}`, "user", "an osprey sighting"), + ]), + thread(busy, project), + ], + projections.apply, + { discard: true }, + ); + if (!indexed) { + yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`; + yield* sql`DROP TRIGGER orchestration_v2_message_search_update`; + yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`; + yield* sql`DROP TABLE orchestration_v2_message_search`; + } + // Newer than every quiet thread's match, and more than one page's hits. + yield* sql` + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2100) + INSERT INTO orchestration_v2_projection_messages + (message_id, thread_id, role, streaming, created_at, updated_at, payload_json) + SELECT 'osprey-busy-' || i, ${busy}, 'assistant', 0, ${DateTime.formatIso(at(5))}, + ${DateTime.formatIso(at(5))}, json_object('text', 'osprey nest') + FROM n + `; + const seen: ThreadId[] = []; + let cursor: ThreadSearch.ThreadSearchCursor | undefined; + for (let page = 0; page < 20; page += 1) { + const result = yield* search.search({ + query: "osprey", + limit: 3, + excludedThreadIds: seen, + ...(cursor === undefined ? {} : { cursor }), + }); + seen.push(...result.matches.map((match) => match.threadId)); + cursor = result.cursor; + if (cursor === undefined) break; + } + assert.isUndefined(cursor); + assert.strictEqual(seen[0], busy); + assert.sameMembers(seen, [busy, ...quiet]); + assert.lengthOf(seen, quiet.length + 1); + }).pipe(Effect.provide(layerTest)), +); + it.effect.each([true, false])( "ThreadSearch narrows short words outside ASCII before the hit limit (indexed: %s)", (indexed) => diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index d3c96a40ce2b8..f5ee7a17ff1d0 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -76,6 +76,9 @@ const SearchRequest = Schema.Struct({ projectId: Schema.NullOr(ProjectId), /** Threads the caller already lists, left out before the hit limit. */ excludedThreadIds: TokenList, + /** The page reads messages with rowids in [lower, before), newest first. */ + before: Schema.Number, + lower: Schema.Number, }); const SearchRow = Schema.Struct({ messageRowid: Schema.Number, @@ -97,14 +100,14 @@ const decodeThreadOpens = Schema.decodeUnknownOption( ); const SNIPPET_LENGTH = 240; -// The newest hits read per query. A common word stops here instead of reading -// every message, so time stays flat as history grows. +// Each page reads at most this many hits, newest first, and ranks their threads, so a +// common word's page stays flat as history grows. Later pages continue older. const MESSAGE_HIT_LIMIT = 2000; -// How many of the newest index hits the filters may pass over to fill that -// limit: a rare short word or hidden threads would otherwise read every hit. -const MESSAGE_CANDIDATE_LIMIT = 10_000; -// Without the index, how many of the newest messages a search scans. -const MESSAGE_SCAN_LIMIT = 20_000; +// How many index hits one page's filters may pass over: a rare short word or hidden +// threads would otherwise read every hit before the page answers. +const MESSAGE_CANDIDATE_PAGE = 10_000; +// Without the index, how many messages one page scans. +const MESSAGE_SCAN_PAGE = 50_000; const NON_ASCII = /[\u0080-\uffff]/; /** SQLite's lower() folds ASCII only, so a short word is checked as each spelling it can match. */ @@ -129,7 +132,7 @@ function shortTokenSpellings(token: string): ReadonlyArray { function buildMessageSearch( query: string, hasIndex: boolean, -): Omit | null { +): Pick | null { const { long, short } = messageSearchTokens(query); if (long.length === 0) return null; // Two-character CJK words are too short for trigrams. @@ -182,7 +185,15 @@ export function buildSearchSnippet(text: string, matchStart: number): string { // The scan folds ASCII case only, so accent variants and non-ASCII case variants may not match. export const messageHitsQuery = ( sql: SqlClient.SqlClient, - { match, substrings, shortSpellings, projectId, excludedThreadIds }: typeof SearchRequest.Encoded, + { + match, + substrings, + shortSpellings, + projectId, + excludedThreadIds, + before, + lower, + }: typeof SearchRequest.Encoded, ) => sql` WITH eligible AS MATERIALIZED ( SELECT threads.thread_id, threads.project_id @@ -211,11 +222,9 @@ export const messageHitsQuery = ( messages.created_at AS "messageCreatedAt" FROM orchestration_v2_projection_messages AS messages INNER JOIN eligible ON eligible.thread_id = messages.thread_id - WHERE ${indexedMessageCondition(sql)} - -- A scan reads every message it passes, so it stops at the newest ones. - AND messages.rowid > ( - SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages - ) - ${MESSAGE_SCAN_LIMIT} + WHERE messages.rowid < ${before} + AND messages.rowid >= ${lower} + AND ${indexedMessageCondition(sql)} ` : sql` SELECT @@ -231,12 +240,8 @@ export const messageHitsQuery = ( ON messages.rowid = orchestration_v2_message_search.rowid INNER JOIN eligible ON eligible.thread_id = messages.thread_id WHERE orchestration_v2_message_search MATCH ${match} - AND orchestration_v2_message_search.rowid >= coalesce(( - SELECT orchestration_v2_message_search.rowid FROM orchestration_v2_message_search - WHERE orchestration_v2_message_search MATCH ${match} - ORDER BY orchestration_v2_message_search.rowid DESC - LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1} - ), 0) + AND orchestration_v2_message_search.rowid < ${before} + AND orchestration_v2_message_search.rowid >= ${lower} AND ${nonPlaceholderMessageCondition(sql)} ` } @@ -266,6 +271,8 @@ const TitleCandidateRow = Schema.Struct({ latestUserMessageAt: Schema.NullOr(IsoDateTime), }); +export type ThreadSearchCursor = NonNullable; + export interface ThreadSearchHit { readonly threadId: ThreadId; readonly projectId: ProjectId; @@ -333,6 +340,28 @@ export const make = Effect.gen(function* () { execute: (request) => messageHitsQuery(sql, request), }); + const newestRowid = SqlSchema.findAll({ + Request: Schema.Void, + Result: Schema.Struct({ next: Schema.Number }), + execute: () => sql` + SELECT coalesce(max(rowid), 0) + 1 AS next FROM orchestration_v2_projection_messages + `, + }); + + // The oldest index hit one page may read, or none when fewer than a page remain. + const candidateFloor = SqlSchema.findAll({ + Request: Schema.Struct({ match: Schema.String, before: Schema.Number }), + Result: Schema.Struct({ rowid: Schema.Number }), + execute: ({ match, before }) => sql` + SELECT orchestration_v2_message_search.rowid AS rowid + FROM orchestration_v2_message_search + WHERE orchestration_v2_message_search MATCH ${match} + AND orchestration_v2_message_search.rowid < ${before} + ORDER BY orchestration_v2_message_search.rowid DESC + LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_PAGE - 1} + `, + }); + const threadOpens = SqlSchema.findAll({ Request: Schema.Struct({ threadIds: TokenList }), Result: ThreadOpensRow, @@ -442,7 +471,7 @@ export const make = Effect.gen(function* () { input: OrchestrationSearchThreadsInput & { readonly projectId: ProjectId | null; /** Threads the caller already lists, which must not use up the limit. */ - readonly excludedThreadIds?: ReadonlySet; + readonly shownThreadIds?: ReadonlySet; /** Off for an agent's search, which has no use for the user's picks. */ readonly picks?: boolean; }, @@ -464,21 +493,29 @@ export const make = Effect.gen(function* () { right.quality - left.quality || Number(left.row.source !== "user") - Number(right.row.source !== "user") || newer(left, right); - const rows = yield* read( + const page = yield* read( Effect.gen(function* () { const index = yield* sql` SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search' `; const messageSearch = buildMessageSearch(input.query, index.length > 0); - return messageSearch === null - ? [] - : yield* searchRows({ - ...messageSearch, - projectId: input.projectId, - excludedThreadIds: [...(input.excludedThreadIds ?? [])], - }); + if (messageSearch === null) return { rows: [], before: 0, lower: 0 }; + const before = input.cursor?.before ?? (yield* newestRowid())[0]?.next ?? 0; + const lower = + messageSearch.match === null + ? Math.max(0, before - MESSAGE_SCAN_PAGE) + : ((yield* candidateFloor({ match: messageSearch.match, before }))[0]?.rowid ?? 0); + const rows = yield* searchRows({ + ...messageSearch, + projectId: input.projectId, + excludedThreadIds: [...(input.shownThreadIds ?? []), ...(input.excludedThreadIds ?? [])], + before, + lower, + }); + return { rows, before, lower }; }), ); + const rows = page.rows; const best = new Map(); // Matching messages per thread at its best quality: a thread that keeps // using the word ranks above a passing mention, and weaker hits ("Trust" @@ -525,8 +562,18 @@ export const make = Effect.gen(function* () { now, { picks: input.picks ?? true }, ); + const limit = input.limit ?? 50; + // Every matching thread in [next, before) is in this page or was excluded as shown, + // so a later page from `next` with this page's threads excluded misses none. + const next = + ranked.length > limit + ? page.before + : rows.length === MESSAGE_HIT_LIMIT + ? rows.at(-1)!.messageRowid + : page.lower; return { - matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({ + ...(next > 0 ? { cursor: { before: next } } : {}), + matches: ranked.slice(0, limit).map(({ row, text, quality, offset }) => ({ hits: hitCount(row.threadId), threadId: row.threadId, messageId: row.messageId, @@ -587,7 +634,7 @@ export const make = Effect.gen(function* () { query: input.query, limit: 50, projectId: input.projectId ?? null, - excludedThreadIds: shown, + shownThreadIds: shown, picks: false, }); const messageHits = matches diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8fa58d8456f75..3ae8720346d41 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3270,6 +3270,19 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); })} + {threadSearch.hasMore ? ( + + ) : null} ) : ( diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index e67937375849b..1949371ce9cc3 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -53,6 +53,7 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, isLoading: false, + hasMore: false, rows: [], }).pipe(Atom.withLabel("web:thread-search:empty")); @@ -105,6 +106,9 @@ export function useThreadSearch( scope: ThreadSearchScope = {}, ): { readonly matches: ReadonlyArray; + /** Older messages may hold more matches for the shown query. */ + readonly hasMore: boolean; + readonly loadMore: () => void; readonly query: string; readonly isPending: boolean; } { @@ -160,6 +164,10 @@ export function useThreadSearch( matches: visible.matches, query: visible.query, isPending, + hasMore: searchKey !== null && visible.query === settledQuery && result.hasMore, + loadMore: () => { + if (searchKey !== null) threadSearch.loadMore(appAtomRegistry, searchKey); + }, }; } diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 09ce63e2a3e65..911c0939db24e 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -231,7 +231,9 @@ messages**, and open at the matching message. Message search needs at least one word of three or more letters, or two for Chinese, Japanese, and Korean. On mobile, the thread list search also lists message matches and opens them at the matching message; on an iPad with a keyboard, `Cmd+K` opens the same -palette. +palette. The palette shows the best few message matches. The sidebar search on +web and desktop and the thread list search on mobile list every match: when a +long history holds more, **Search older messages** below the results loads them. Use **Settings → Keybindings** to find or customize shortcuts for searching files and copying a thread reference. A copied reference uses the thread's pull request diff --git a/packages/client-runtime/src/state/threadSearch.test.ts b/packages/client-runtime/src/state/threadSearch.test.ts index d9f2cca584fbc..e1e090ee76bf7 100644 --- a/packages/client-runtime/src/state/threadSearch.test.ts +++ b/packages/client-runtime/src/state/threadSearch.test.ts @@ -64,8 +64,8 @@ it("ignores invalid search keys", () => { const state = registry.get(searchAtom(makeThreadSearchKey([envA], "a".repeat(201)))); const malformedState = registry.get(searchAtom("not json{{")); - expect(state).toEqual({ matches: [], isLoading: false, rows: [] }); - expect(malformedState).toEqual({ matches: [], isLoading: false, rows: [] }); + expect(state).toEqual({ matches: [], isLoading: false, hasMore: false, rows: [] }); + expect(malformedState).toEqual({ matches: [], isLoading: false, hasMore: false, rows: [] }); expect(searchCount).toBe(0); } finally { registry.dispose(); @@ -101,6 +101,7 @@ it("merges successful environments and silently ignores failures", () => { expect(state).toEqual({ matches: [{ ...result.matches[0], environmentId: envA }], isLoading: false, + hasMore: false, rows: [], }); expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]'); @@ -108,6 +109,53 @@ it("merges successful environments and silently ignores failures", () => { registry.dispose(); }); +it("loads later pages on request, excluding earlier threads, and passes over empty pages", () => { + const match = (id: string) => ({ + threadId: ThreadId.make(id), + projectId: ProjectId.make("project-a"), + source: "user" as const, + snippet: "needle", + messageCreatedAt: null, + }); + // Keyed by the page's cursor: page 1 finds nothing, so page 2 follows on its own. + const pages: Record = { + first: { matches: [match("a")], cursor: { before: 30 } }, + 30: { matches: [], cursor: { before: 20 } }, + 20: { matches: [match("b")], cursor: { before: 10 } }, + 10: { matches: [match("c")] }, + }; + const inputs: OrchestrationV2SearchThreadsInput[] = []; + const search = createThreadSearchResultsAtomFamily({ + getSearchAtom: (_environmentId, input) => { + inputs.push(input); + return Atom.make(AsyncResult.success(pages[input.cursor?.before ?? "first"]!)); + }, + labelPrefix: "test:thread-search", + }); + const registry = AtomRegistry.make(); + const key = makeThreadSearchKey([envA], "needle"); + const threadIds = () => + registry.get(search.results(key)).matches.map((found) => found.threadId as string); + const unmount = registry.mount(search.results(key)); + + expect(threadIds()).toEqual(["a"]); + expect(registry.get(search.results(key)).hasMore).toBe(true); + search.loadMore(registry, key); + expect(threadIds()).toEqual(["a", "b"]); + expect(inputs.at(-1)).toEqual({ + query: "needle", + cursor: { before: 20 }, + excludedThreadIds: ["a"], + }); + search.loadMore(registry, key); + expect(threadIds()).toEqual(["a", "b", "c"]); + expect(registry.get(search.results(key)).hasMore).toBe(false); + expect(inputs.at(-1)?.excludedThreadIds).toEqual(["a", "b"]); + + unmount(); + registry.dispose(); +}); + it("asks environments that omit older settled threads for their rows, with the caller's scope", () => { const inputs: Array = []; const row = { id: ThreadId.make("thread-old") } as OrchestrationV2ThreadShell; diff --git a/packages/client-runtime/src/state/threadSearch.ts b/packages/client-runtime/src/state/threadSearch.ts index 23794cec2c33e..2b61f7319c29c 100644 --- a/packages/client-runtime/src/state/threadSearch.ts +++ b/packages/client-runtime/src/state/threadSearch.ts @@ -9,7 +9,7 @@ import { } from "@t3tools/contracts"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { AsyncResult, Atom } from "effect/reactivity"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import { foldSearchQuery, messageSearchTokens, @@ -52,6 +52,8 @@ export interface EnvironmentThreadSearchMatch extends OrchestrationThreadSearchM export interface ThreadSearchResultsState { readonly matches: ReadonlyArray; readonly isLoading: boolean; + /** Older messages may hold more matches; `loadMore` reads the next page. */ + readonly hasMore: boolean; /** Rows of matching older settled threads, which shells that omit them do not hold. */ readonly rows: ReadonlyArray<{ readonly environmentId: EnvironmentId; @@ -117,11 +119,15 @@ export function createThreadSearchResultsAtomFamily(options: { readonly olderSettledBefore?: (environmentId: EnvironmentId) => Atom.Atom; readonly labelPrefix: string; }) { + // How many pages of message matches each environment has been asked for, per search. + const requestedPages = Atom.family((pagesKey: string) => + Atom.make(1).pipe(Atom.withLabel(`${options.labelPrefix}-pages:${pagesKey}`)), + ); const results = Atom.family((key: string) => Atom.make((get): ThreadSearchResultsState => { const parsedKey = parseThreadSearchKey(key); if (Option.isNone(parsedKey)) { - return { matches: [], isLoading: false, rows: EMPTY_SEARCH_ROWS }; + return { matches: [], isLoading: false, hasMore: false, rows: EMPTY_SEARCH_ROWS }; } const [environmentIds, query, scope = {}] = parsedKey.value; @@ -131,6 +137,7 @@ export function createThreadSearchResultsAtomFamily(options: { const matches: EnvironmentThreadSearchMatch[] = []; const rows: Array = []; let isLoading = false; + let hasMore = false; for (const environmentId of environmentIds) { const before = options.olderSettledBefore @@ -162,9 +169,42 @@ export function createThreadSearchResultsAtomFamily(options: { }); } } + // Later pages leave out the threads earlier ones returned. A page that found nothing + // continues on its own, so "more" never shows without matches to load. + const wanted = get(requestedPages(JSON.stringify([key, environmentId]))); + const excludedThreadIds = value?.matches.map((match) => match.threadId) ?? []; + let cursor = value?.cursor; + let lastPageMatched = (value?.matches.length ?? 0) > 0; + let pages = 1; + while (cursor !== undefined && (pages < wanted || !lastPageMatched)) { + const next = get( + options.getSearchAtom(environmentId, { + query, + cursor, + excludedThreadIds: [...excludedThreadIds], + }), + ); + isLoading ||= next.waiting; + const nextValue = AsyncResult.getOrElse(next, () => null); + if (nextValue === null) { + cursor = undefined; + break; + } + matches.push(...nextValue.matches.map((match) => ({ ...match, environmentId }))); + excludedThreadIds.push(...nextValue.matches.map((match) => match.threadId)); + cursor = nextValue.cursor; + lastPageMatched = nextValue.matches.length > 0; + if (lastPageMatched) pages += 1; + } + hasMore ||= cursor !== undefined; } - return { matches, isLoading, rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows }; + return { + matches, + isLoading, + hasMore, + rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows, + }; }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)), ); const rowsAtom = Atom.family((rowsKey: string) => { @@ -182,6 +222,15 @@ export function createThreadSearchResultsAtomFamily(options: { }); return { results, + /** Reads the next page of message matches for a search key, where there is one. */ + loadMore: (registry: AtomRegistry.AtomRegistry, key: string) => { + const parsedKey = parseThreadSearchKey(key); + if (Option.isNone(parsedKey)) return; + for (const environmentId of parsedKey.value[0]) { + const pages = requestedPages(JSON.stringify([key, environmentId])); + registry.set(pages, registry.get(pages) + 1); + } + }, /** One environment's older settled rows for a search key, for `mountRows`. */ rows: (key: string, environmentId: EnvironmentId) => rowsAtom(JSON.stringify([key, environmentId])), diff --git a/packages/contracts/src/threadSearch.ts b/packages/contracts/src/threadSearch.ts index 42c87ebb610cd..9052973a8362b 100644 --- a/packages/contracts/src/threadSearch.ts +++ b/packages/contracts/src/threadSearch.ts @@ -15,14 +15,24 @@ export type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSo /** Longer queries are cut to this before they are sent. */ export const THREAD_SEARCH_QUERY_MAX_LENGTH = 200; -// The server's SQLite client is synchronous and single-connection. Bound both -// scan input and response size so a search cannot monopolize that connection. +/** Where the next page of message matches starts: messages older than `before`. */ +export const OrchestrationThreadSearchCursor = Schema.Struct({ + before: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), +}); +export type OrchestrationThreadSearchCursor = typeof OrchestrationThreadSearchCursor.Type; + +// The server's SQLite reader is shared. Each page bounds the messages it reads and the +// threads it returns, so a search cannot monopolize that connection or a client. export const OrchestrationSearchThreadsInput = Schema.Struct({ query: TrimmedString.check( Schema.isMinLength(2), Schema.isMaxLength(THREAD_SEARCH_QUERY_MAX_LENGTH), ), limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))), + /** The previous page's `cursor`, for the next page. */ + cursor: Schema.optionalKey(OrchestrationThreadSearchCursor), + /** Threads earlier pages of this search returned, so later pages leave them out. */ + excludedThreadIds: Schema.optionalKey(Schema.Array(ThreadId)), }); export type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type; @@ -48,6 +58,8 @@ export type OrchestrationThreadSearchMatch = typeof OrchestrationThreadSearchMat export const OrchestrationSearchThreadsResult = Schema.Struct({ matches: Schema.Array(OrchestrationThreadSearchMatch), + /** Present when older messages may hold more matches; pass it back for the next page. */ + cursor: Schema.optionalKey(OrchestrationThreadSearchCursor), }); export type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type; From 523709a09b3b57bd044149306a1c42351624f8b1 Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:39:19 +0100 Subject: [PATCH 3/5] fix(search): bound how far search reads on its own and how many threads it excludes Clients followed empty pages of message matches to the end of history on their own, which on a long history without matches could read for seconds per query. They now stop after three empty pages in a row and show "Search older messages", so the user decides whether to keep going. Without the index a page scans 20,000 messages again, as a single read did before paging. excludedThreadIds is capped at 2,000 threads; a search that reaches that many stops and says so in the web sidebar and mobile thread lists instead of dropping later matches silently. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/features/home/HomeScreen.tsx | 3 +- .../threads/ThreadNavigationSidebar.tsx | 3 +- .../features/threads/thread-list-v2-items.tsx | 17 ++++++-- apps/mobile/src/state/queries.ts | 4 ++ .../src/orchestration-v2/ThreadSearch.ts | 2 +- apps/web/src/components/Sidebar.tsx | 11 ++++- apps/web/src/state/queries.ts | 4 ++ docs/user/thread-sidebar.md | 2 + .../src/state/threadSearch.test.ts | 39 +++++++++++++---- .../client-runtime/src/state/threadSearch.ts | 43 +++++++++++++++---- packages/contracts/src/threadSearch.ts | 7 ++- 11 files changed, 109 insertions(+), 26 deletions(-) diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index bcc2d5c58f02a..7a50becede2ee 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -815,9 +815,10 @@ export function HomeScreen(props: HomeScreenProps) { // Lifted above the rows so an iOS filter menu's dismissal morph is not covered. ListHeaderComponentStyle={{ zIndex: 1 }} ListFooterComponent={ - hasSearchQuery && threadSearch.hasMore ? ( + hasSearchQuery && (threadSearch.hasMore || threadSearch.partial) ? ( ) : settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? ( diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 589598a8d9ca7..337b0a14b210f 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -558,10 +558,11 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { /> ); const searchMoreRow = - props.searchQuery.trim().length > 0 && threadSearch.hasMore ? ( + props.searchQuery.trim().length > 0 && (threadSearch.hasMore || threadSearch.partial) ? ( ) : null; diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index eac47167fd89f..b621c5076f6cb 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -25,7 +25,11 @@ import { formatWorkingDurationLabel, resolveThreadWorkingStartedAt, } from "@t3tools/client-runtime/state/models"; -import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts"; +import { + AuthOrchestrationOperateScope, + THREAD_SEARCH_MAX_EXCLUDED_THREADS, + type EnvironmentMachineKind, +} from "@t3tools/contracts"; import type { SnoozePresetSetting } from "@t3tools/contracts/settings"; import { canSnooze } from "@t3tools/client-runtime/state/thread-settled"; import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference"; @@ -360,18 +364,23 @@ export const ThreadListV2ShowMoreRow = memo(function ThreadListV2ShowMoreRow(pro ); }); -/** Reads the next page of message matches for a search that has more. */ +/** Reads the next page of message matches, or says the search stopped at its most threads. */ export const ThreadSearchMoreRow = memo(function ThreadSearchMoreRow(props: { readonly pane?: "screen" | "sidebar"; readonly loading: boolean; + readonly partial?: boolean; readonly onPress: () => void; }) { - const label = props.loading ? "Searching older messages
" : "Search older messages"; + const label = props.partial + ? `Showing the first ${THREAD_SEARCH_MAX_EXCLUDED_THREADS.toLocaleString()} threads with matching messages` + : props.loading + ? "Searching older messages
" + : "Search older messages"; return ( ({ opacity: pressed ? 0.6 : 1 })} diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index 7e33d5bded491..d5db54dddec2b 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -57,6 +57,7 @@ const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, isLoading: false, hasMore: false, + partial: false, rows: [], }).pipe(Atom.withLabel("mobile:thread-search:empty")); @@ -209,6 +210,8 @@ export function useThreadSearch( readonly matches: ReadonlyArray; /** Older messages may hold more matches for the shown query. */ readonly hasMore: boolean; + /** The search stopped at the most threads it can list; older matches are not shown. */ + readonly partial: boolean; readonly loadMore: () => void; /** The query `matches` are for, which lags the typed one while a search runs. */ readonly query: string; @@ -267,6 +270,7 @@ export function useThreadSearch( query: visible.query, isPending, hasMore: searchKey !== null && visible.query === settledQuery && result.hasMore, + partial: searchKey !== null && visible.query === settledQuery && result.partial, loadMore: () => { if (searchKey !== null) threadSearch.loadMore(appAtomRegistry, searchKey); }, diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index f5ee7a17ff1d0..a652ab5a55bc2 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -107,7 +107,7 @@ const MESSAGE_HIT_LIMIT = 2000; // threads would otherwise read every hit before the page answers. const MESSAGE_CANDIDATE_PAGE = 10_000; // Without the index, how many messages one page scans. -const MESSAGE_SCAN_PAGE = 50_000; +const MESSAGE_SCAN_PAGE = 20_000; const NON_ASCII = /[\u0080-\uffff]/; /** SQLite's lower() folds ASCII only, so a short word is checked as each spelling it can match. */ diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 3ae8720346d41..1c645371fdbec 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,5 +1,9 @@ import { attachSidebarTree } from "../lib/sidebarTree"; -import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; +import { + THREAD_SEARCH_MAX_EXCLUDED_THREADS, + type EnvironmentId, + type ScopedProjectRef, +} from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; import { dropThreadContext, @@ -3282,6 +3286,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ? "Searching older messages
" : "Search older messages"} + ) : threadSearch.partial ? ( +

+ Showing the first {THREAD_SEARCH_MAX_EXCLUDED_THREADS.toLocaleString()}{" "} + threads with matching messages. Refine the search to see others. +

) : null} diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index 1949371ce9cc3..41758b8186858 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -54,6 +54,7 @@ const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, isLoading: false, hasMore: false, + partial: false, rows: [], }).pipe(Atom.withLabel("web:thread-search:empty")); @@ -108,6 +109,8 @@ export function useThreadSearch( readonly matches: ReadonlyArray; /** Older messages may hold more matches for the shown query. */ readonly hasMore: boolean; + /** The search stopped at the most threads it can list; older matches are not shown. */ + readonly partial: boolean; readonly loadMore: () => void; readonly query: string; readonly isPending: boolean; @@ -165,6 +168,7 @@ export function useThreadSearch( query: visible.query, isPending, hasMore: searchKey !== null && visible.query === settledQuery && result.hasMore, + partial: searchKey !== null && visible.query === settledQuery && result.partial, loadMore: () => { if (searchKey !== null) threadSearch.loadMore(appAtomRegistry, searchKey); }, diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 911c0939db24e..ccd70f48366cb 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -234,6 +234,8 @@ the matching message; on an iPad with a keyboard, `Cmd+K` opens the same palette. The palette shows the best few message matches. The sidebar search on web and desktop and the thread list search on mobile list every match: when a long history holds more, **Search older messages** below the results loads them. +A search lists up to 2,000 threads with matching messages and says so when it +stops there. Use **Settings → Keybindings** to find or customize shortcuts for searching files and copying a thread reference. A copied reference uses the thread's pull request diff --git a/packages/client-runtime/src/state/threadSearch.test.ts b/packages/client-runtime/src/state/threadSearch.test.ts index e1e090ee76bf7..ed1449b018c44 100644 --- a/packages/client-runtime/src/state/threadSearch.test.ts +++ b/packages/client-runtime/src/state/threadSearch.test.ts @@ -64,8 +64,20 @@ it("ignores invalid search keys", () => { const state = registry.get(searchAtom(makeThreadSearchKey([envA], "a".repeat(201)))); const malformedState = registry.get(searchAtom("not json{{")); - expect(state).toEqual({ matches: [], isLoading: false, hasMore: false, rows: [] }); - expect(malformedState).toEqual({ matches: [], isLoading: false, hasMore: false, rows: [] }); + expect(state).toEqual({ + matches: [], + isLoading: false, + hasMore: false, + partial: false, + rows: [], + }); + expect(malformedState).toEqual({ + matches: [], + isLoading: false, + hasMore: false, + partial: false, + rows: [], + }); expect(searchCount).toBe(0); } finally { registry.dispose(); @@ -102,6 +114,7 @@ it("merges successful environments and silently ignores failures", () => { matches: [{ ...result.matches[0], environmentId: envA }], isLoading: false, hasMore: false, + partial: false, rows: [], }); expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]'); @@ -109,7 +122,7 @@ it("merges successful environments and silently ignores failures", () => { registry.dispose(); }); -it("loads later pages on request, excluding earlier threads, and passes over empty pages", () => { +it("loads later pages on request, passing over at most three empty pages on its own", () => { const match = (id: string) => ({ threadId: ThreadId.make(id), projectId: ProjectId.make("project-a"), @@ -117,9 +130,12 @@ it("loads later pages on request, excluding earlier threads, and passes over emp snippet: "needle", messageCreatedAt: null, }); - // Keyed by the page's cursor: page 1 finds nothing, so page 2 follows on its own. + // Keyed by the page's cursor. Pages 50..30 find nothing; 20 does. const pages: Record = { - first: { matches: [match("a")], cursor: { before: 30 } }, + first: { matches: [match("a")], cursor: { before: 60 } }, + 60: { matches: [], cursor: { before: 50 } }, + 50: { matches: [], cursor: { before: 40 } }, + 40: { matches: [], cursor: { before: 30 } }, 30: { matches: [], cursor: { before: 20 } }, 20: { matches: [match("b")], cursor: { before: 10 } }, 10: { matches: [match("c")] }, @@ -134,12 +150,17 @@ it("loads later pages on request, excluding earlier threads, and passes over emp }); const registry = AtomRegistry.make(); const key = makeThreadSearchKey([envA], "needle"); - const threadIds = () => - registry.get(search.results(key)).matches.map((found) => found.threadId as string); + const state = () => registry.get(search.results(key)); + const threadIds = () => state().matches.map((found) => found.threadId as string); const unmount = registry.mount(search.results(key)); expect(threadIds()).toEqual(["a"]); - expect(registry.get(search.results(key)).hasMore).toBe(true); + expect(state().hasMore).toBe(true); + // Three empty pages in a row stop the read and offer more. + search.loadMore(registry, key); + expect(threadIds()).toEqual(["a"]); + expect(inputs.at(-1)?.cursor).toEqual({ before: 40 }); + expect(state().hasMore).toBe(true); search.loadMore(registry, key); expect(threadIds()).toEqual(["a", "b"]); expect(inputs.at(-1)).toEqual({ @@ -149,7 +170,7 @@ it("loads later pages on request, excluding earlier threads, and passes over emp }); search.loadMore(registry, key); expect(threadIds()).toEqual(["a", "b", "c"]); - expect(registry.get(search.results(key)).hasMore).toBe(false); + expect(state()).toMatchObject({ hasMore: false, partial: false }); expect(inputs.at(-1)?.excludedThreadIds).toEqual(["a", "b"]); unmount(); diff --git a/packages/client-runtime/src/state/threadSearch.ts b/packages/client-runtime/src/state/threadSearch.ts index 2b61f7319c29c..ebb511b21b94b 100644 --- a/packages/client-runtime/src/state/threadSearch.ts +++ b/packages/client-runtime/src/state/threadSearch.ts @@ -1,6 +1,7 @@ import { EnvironmentId, OrchestrationSearchThreadsInput, + THREAD_SEARCH_MAX_EXCLUDED_THREADS, ProjectId, type OrchestrationThreadSearchMatch, type OrchestrationV2SearchThreadsInput, @@ -21,6 +22,9 @@ import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests"; import type { EnvironmentThreadShell } from "./models.ts"; import { getThreadSortTimestamp } from "./threadSort.ts"; +// Pages a search reads on its own, past ones without matches, before showing "more". +const EMPTY_PAGES_PER_REQUEST = 3; + // When this client last sent an open per thread, by its own clock: a server // timestamp would be off by any clock skew. The server merges opens closer // together than THREAD_OPEN_DEDUPE_MS anyway, so skipping them saves a command @@ -54,6 +58,8 @@ export interface ThreadSearchResultsState { readonly isLoading: boolean; /** Older messages may hold more matches; `loadMore` reads the next page. */ readonly hasMore: boolean; + /** The search listed as many threads as later pages can leave out, and stopped there. */ + readonly partial: boolean; /** Rows of matching older settled threads, which shells that omit them do not hold. */ readonly rows: ReadonlyArray<{ readonly environmentId: EnvironmentId; @@ -127,7 +133,13 @@ export function createThreadSearchResultsAtomFamily(options: { Atom.make((get): ThreadSearchResultsState => { const parsedKey = parseThreadSearchKey(key); if (Option.isNone(parsedKey)) { - return { matches: [], isLoading: false, hasMore: false, rows: EMPTY_SEARCH_ROWS }; + return { + matches: [], + isLoading: false, + hasMore: false, + partial: false, + rows: EMPTY_SEARCH_ROWS, + }; } const [environmentIds, query, scope = {}] = parsedKey.value; @@ -138,6 +150,7 @@ export function createThreadSearchResultsAtomFamily(options: { const rows: Array = []; let isLoading = false; let hasMore = false; + let partial = false; for (const environmentId of environmentIds) { const before = options.olderSettledBefore @@ -169,14 +182,27 @@ export function createThreadSearchResultsAtomFamily(options: { }); } } - // Later pages leave out the threads earlier ones returned. A page that found nothing - // continues on its own, so "more" never shows without matches to load. + // Later pages leave out the threads earlier ones returned. Each request reads until a + // page finds matches or a few in a row find none, so a long history without matches + // shows "more" instead of reading on unseen. const wanted = get(requestedPages(JSON.stringify([key, environmentId]))); const excludedThreadIds = value?.matches.map((match) => match.threadId) ?? []; let cursor = value?.cursor; - let lastPageMatched = (value?.matches.length ?? 0) > 0; - let pages = 1; - while (cursor !== undefined && (pages < wanted || !lastPageMatched)) { + let request = 1; + let satisfied = (value?.matches.length ?? 0) > 0; + let emptyPages = satisfied ? 0 : 1; + while (cursor !== undefined) { + if (satisfied || emptyPages >= EMPTY_PAGES_PER_REQUEST) { + if (request >= wanted) break; + request += 1; + satisfied = false; + emptyPages = 0; + } + if (excludedThreadIds.length >= THREAD_SEARCH_MAX_EXCLUDED_THREADS) { + partial = true; + cursor = undefined; + break; + } const next = get( options.getSearchAtom(environmentId, { query, @@ -193,8 +219,8 @@ export function createThreadSearchResultsAtomFamily(options: { matches.push(...nextValue.matches.map((match) => ({ ...match, environmentId }))); excludedThreadIds.push(...nextValue.matches.map((match) => match.threadId)); cursor = nextValue.cursor; - lastPageMatched = nextValue.matches.length > 0; - if (lastPageMatched) pages += 1; + if (nextValue.matches.length > 0) satisfied = true; + else emptyPages += 1; } hasMore ||= cursor !== undefined; } @@ -203,6 +229,7 @@ export function createThreadSearchResultsAtomFamily(options: { matches, isLoading, hasMore, + partial, rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows, }; }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)), diff --git a/packages/contracts/src/threadSearch.ts b/packages/contracts/src/threadSearch.ts index 9052973a8362b..0de32b8d005c4 100644 --- a/packages/contracts/src/threadSearch.ts +++ b/packages/contracts/src/threadSearch.ts @@ -15,6 +15,9 @@ export type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSo /** Longer queries are cut to this before they are sent. */ export const THREAD_SEARCH_QUERY_MAX_LENGTH = 200; +/** How many threads later pages can leave out, and so how many a search can list. */ +export const THREAD_SEARCH_MAX_EXCLUDED_THREADS = 2_000; + /** Where the next page of message matches starts: messages older than `before`. */ export const OrchestrationThreadSearchCursor = Schema.Struct({ before: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), @@ -32,7 +35,9 @@ export const OrchestrationSearchThreadsInput = Schema.Struct({ /** The previous page's `cursor`, for the next page. */ cursor: Schema.optionalKey(OrchestrationThreadSearchCursor), /** Threads earlier pages of this search returned, so later pages leave them out. */ - excludedThreadIds: Schema.optionalKey(Schema.Array(ThreadId)), + excludedThreadIds: Schema.optionalKey( + Schema.Array(ThreadId).check(Schema.isMaxLength(THREAD_SEARCH_MAX_EXCLUDED_THREADS)), + ), }); export type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type; From f50b970b813fdcf602fdb4aaee6189e8d0c058ac Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 13:39:33 +0100 Subject: [PATCH 4/5] feat(terminal): read any part of terminal history through a sliding window Clients could page older output only until their 8 MiB buffer filled, so most of a large server history stayed unreachable and scrolling to the top silently did nothing. Reopening a terminal also processed its whole history synchronously, and history rewrites truncated the file in place. History offsets now count UTF-8 bytes, so they map onto the history file. Each terminal keeps its newest 16 MiB in memory (512 MiB across all terminals, 256 MiB for exited ones); older output stays only in the file, and `terminal.history` reads pages before or after any offset from memory or the file. Loading reads the file in blocks and keeps just the tail, and the alternate-screen scan on reopen looks at the last 4 MiB. Rewrites copy what is still needed into a temporary file and rename it over the old one, so a crash leaves one whole file; a failed append marks the file for such a rewrite. Output events carry the server's history end. A client holds a window of about 4 MiB and 25,000 lines: reading further back drops its newest output and pauses on earlier output, buffering live output aside; reading forward drops the oldest, and reaching the end follows the live output again. On web the view keeps the rows being read in place, asks for a page once per arrival at an edge, and shows "Jump to latest" while paused. Mobile gets "Load later output" and "Jump to latest output" menu actions. Views keep 60,000 rows. Co-Authored-By: Claude Opus 5.5 --- .../android/src/main/cpp/t3_terminal_jni.cpp | 3 +- .../t3terminal/TerminalOutputBuffer.kt | 2 +- .../ios/TerminalOutputBuffer.swift | 2 +- .../terminal/ThreadTerminalRouteScreen.tsx | 61 +- .../src/features/terminal/terminalTheme.ts | 4 +- apps/server/src/terminal/History.test.ts | 147 ++++ apps/server/src/terminal/History.ts | 503 ++++++++++++ apps/server/src/terminal/Manager.test.ts | 170 ++-- apps/server/src/terminal/Manager.ts | 766 ++++++++---------- .../src/components/ThreadTerminalDrawer.tsx | 52 +- apps/web/src/terminal/ghostty/core.test.ts | 3 +- apps/web/src/terminal/ghostty/core.ts | 3 +- apps/web/src/terminal/ghostty/surface.test.ts | 28 + apps/web/src/terminal/ghostty/surface.ts | 60 +- docs/user/terminal.md | 12 +- packages/client-runtime/src/state/terminal.ts | 107 ++- .../src/state/terminalOutput.ts | 617 +++++++++----- .../src/state/terminalSession.test.ts | 114 +-- .../src/state/terminalSession.ts | 34 +- packages/contracts/src/terminal.ts | 35 +- 20 files changed, 1807 insertions(+), 916 deletions(-) create mode 100644 apps/server/src/terminal/History.test.ts create mode 100644 apps/server/src/terminal/History.ts diff --git a/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp b/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp index d93e8cc81f85a..1589f7693bc54 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp +++ b/apps/mobile/modules/t3-terminal/android/src/main/cpp/t3_terminal_jni.cpp @@ -12,7 +12,8 @@ namespace { constexpr uint32_t kSnapshotMagic = 0x54563354; // "T3VT" in little endian. constexpr uint16_t kSnapshotVersion = 1; -constexpr size_t kMaxScrollbackRows = 100000; +// TERMINAL_VIEW_SCROLLBACK_ROWS in packages/contracts. +constexpr size_t kMaxScrollbackRows = 60000; enum CellFlag : uint16_t { kBold = 1 << 0, diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt index 449c93ab78259..673c757645c4a 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt @@ -2,7 +2,7 @@ package expo.modules.t3terminal import java.util.ArrayDeque -private const val REPLAY_LIMIT = 8 * 1024 * 1024 +private const val REPLAY_LIMIT = 4 * 1024 * 1024 private const val REPLAY_CHUNK_SIZE = 16 * 1024 // Keep only replay history for intentional terminal recreation. diff --git a/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift b/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift index 95d0c32bde1a6..d4e29cf3d50d4 100644 --- a/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift +++ b/apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift @@ -4,7 +4,7 @@ import Foundation final class TerminalOutputBuffer { private var storage = Data() private var retainedStart = 0 - private let limit = 8 * 1024 * 1024 + private let limit = 4 * 1024 * 1024 var data: Data { storage.subdata(in: retainedStart.. void; readonly onOpenNewTerminal: () => void; readonly onSelectTerminal: (terminalId: string) => void; - /** Null when the view already holds all the output the server keeps, or all that fits. */ + /** Null when the view already holds the oldest output the server keeps. */ readonly onLoadOlderOutput: (() => void) | null; + /** Set while the view shows earlier output instead of following the live output. */ + readonly onLoadNewerOutput: (() => void) | null; + readonly onShowLatestOutput: (() => void) | null; }) { return ( void terminalEnvironment.loadOlderOutput( appAtomRegistry, - { - environmentId: selectedThread.environmentId, - threadId: selectedThread.id, - terminalId, - }, + outputTarget, + terminal.output, + ) + : null + } + onLoadNewerOutput={ + canLoadNewerTerminalOutput(terminal.output) + ? () => + void terminalEnvironment.loadNewerOutput( + appAtomRegistry, + outputTarget, + terminal.output, + ) + : null + } + onShowLatestOutput={ + canLoadNewerTerminalOutput(terminal.output) + ? () => + void terminalEnvironment.showLatestOutput( + appAtomRegistry, + outputTarget, terminal.output, ) : null diff --git a/apps/mobile/src/features/terminal/terminalTheme.ts b/apps/mobile/src/features/terminal/terminalTheme.ts index d5bb6a16555a1..85f7c117d2c07 100644 --- a/apps/mobile/src/features/terminal/terminalTheme.ts +++ b/apps/mobile/src/features/terminal/terminalTheme.ts @@ -120,8 +120,8 @@ export function buildGhosttyThemeConfig(theme: TerminalTheme): string { `foreground = ${theme.foreground}`, `cursor-color = ${theme.cursorForeground}`, `cursor-text = ${theme.cursorBackground}`, - // Bytes of scrollback, about 100,000 rows as on web and Android; the default holds 10 MB. - "scrollback-limit = 100000000", + // Bytes of scrollback, about TERMINAL_VIEW_SCROLLBACK_ROWS rows; the default holds 10 MB. + "scrollback-limit = 60000000", ]; for (const [index, color] of theme.palette.entries()) { diff --git a/apps/server/src/terminal/History.test.ts b/apps/server/src/terminal/History.test.ts new file mode 100644 index 0000000000000..976d470b9027f --- /dev/null +++ b/apps/server/src/terminal/History.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + BoundedTerminalHistory, + planHistoryFileWrite, + releaseHistoryMemory, + startPageAtLine, + type HistoryFileWrite, +} from "./History.ts"; + +/** Applies writes as the manager does, to a file kept as bytes. */ +function fileOf(history: BoundedTerminalHistory) { + let file = Buffer.alloc(0); + return { + get text() { + return file.toString("utf8"); + }, + persist(minCompactionBytes = 64): HistoryFileWrite { + const write = planHistoryFileWrite(history, minCompactionBytes); + const text = Buffer.from(write.text); + file = write.append + ? Buffer.concat([file, text]) + : Buffer.concat([ + write.copy === null ? Buffer.alloc(0) : file.subarray(write.copy.from, write.copy.to), + text, + ]); + history.persisted = write.persisted; + // The file ends with the history at the recorded offsets. + expect(file.length).toBe(write.persisted.end - write.persisted.fileStart); + return write; + }, + }; +} + +describe("BoundedTerminalHistory", () => { + it("keeps offsets in UTF-8 bytes across trimming and joined surrogates", () => { + const history = new BoundedTerminalHistory(3, "", 1_000); + history.append("a損\n"); + expect(history.endOffset).toBe(5); + history.append("\ud83d"); + history.append("\ude80\n"); + expect(history.endOffset).toBe(10); + history.append("x\ny\n"); + expect(history.memoryText(history.startOffset)).toBe("🚀\nx\ny\n"); + expect(history.startOffset).toBe(5); + expect(history.memoryText(5, 9)).toBe("🚀"); + expect(startPageAtLine("ab\ncd", 3, 0, false)).toEqual({ data: "cd", offset: 6 }); + }); + + it("releases persisted output from memory while limits still count it", () => { + const history = new BoundedTerminalHistory(1_000, "", 1_000_000); + const file = fileOf(history); + const line = "x".repeat(99) + "\n"; + history.append(line.repeat(400)); + file.persist(); + history.append(line); + // Unwritten output stays in memory. + history.spill(0); + expect(history.memoryStart).toBeLessThanOrEqual(40_000); + expect(history.memoryText(history.memoryStart).endsWith(line)).toBe(true); + expect(history.bytes).toBe(40_100); + // The line limit counts released lines, dropping them a whole segment at a time. + history.append(line.repeat(700)); + expect(history.startOffset).toBeGreaterThanOrEqual(10_100); + expect(history.startOffset).toBeLessThan(10_100 + 64 * 1024); + expect(history.endOffset).toBe(110_100); + }); + + it("appends to its file and rewrites it from the file and memory when mostly trimmed", () => { + const history = new BoundedTerminalHistory(10, "", 1_000_000); + const file = fileOf(history); + history.append("one\ntwo\n"); + expect(file.persist().append).toBe(false); + history.append("three\n"); + expect(file.persist()).toMatchObject({ append: true, text: "three\n" }); + const long = (index: number) => `line ${index} ${"y".repeat(6_000)}\n`; + for (let index = 0; index < 20; index += 1) { + history.append(long(index)); + file.persist(1e9); + } + history.spill(0); + expect(history.memoryStart).toBeGreaterThan(history.startOffset); + // The trimmed prefix outgrew the retained text, so the file is rebuilt: released + // output is copied from the old file, the rest written from memory. + const write = file.persist(64); + expect(write.append).toBe(false); + if (write.append) return; + expect(write.copy).not.toBeNull(); + expect(file.text).toBe(Array.from({ length: 10 }, (_, index) => long(index + 10)).join("")); + + // A split surrogate waits for its pair instead of being written as U+FFFD. + history.append("\ud83d"); + expect(file.persist(1e9)).toMatchObject({ append: true, text: "" }); + history.append("\ude80\n"); + file.persist(1e9); + expect(file.text.endsWith("🚀\n")).toBe(true); + + // A failed append leaves the file unknown past what was released, so it is rebuilt. + history.persisted = { ...history.persisted!, dirty: true }; + history.append("after\n"); + expect(file.persist().append).toBe(false); + expect(file.text.endsWith("🚀\nafter\n")).toBe(true); + + history.clear(); + expect(file.persist()).toMatchObject({ append: false, copy: null }); + expect(file.text).toBe(""); + }); + + it("restores a file's sizes and tail, trimming whole released segments", () => { + const history = BoundedTerminalHistory.restored( + 5, + 1_000, + 100, + [ + { bytes: 30, lineBreaks: 3 }, + { bytes: 20, lineBreaks: 2 }, + ], + "tail\n", + ); + // Six lines are over the limit; the oldest segment goes whole. + expect(history.startOffset).toBe(130); + expect(history.memoryStart).toBe(150); + expect(history.endOffset).toBe(155); + }); + + it("releases memory from the largest histories first, only as far as needed", () => { + const histories = [100, 300, 200].map((lines) => { + const history = new BoundedTerminalHistory(10_000, "", 10_000_000); + history.append(`${"x".repeat(1_023)}\n`.repeat(lines)); + history.persisted = { + generation: history.clearGeneration, + fileStart: 0, + end: history.endOffset, + }; + return history; + }); + releaseHistoryMemory(histories, 500 * 1024, 64 * 1024); + expect(histories.map((history) => history.memoryBytes <= 100 * 1024 + 16 * 1024)).toEqual([ + true, + true, + false, + ]); + expect(histories.reduce((sum, history) => sum + history.memoryBytes, 0)).toBeLessThanOrEqual( + 500 * 1024, + ); + }); +}); diff --git a/apps/server/src/terminal/History.ts b/apps/server/src/terminal/History.ts new file mode 100644 index 0000000000000..eb4fa7234548a --- /dev/null +++ b/apps/server/src/terminal/History.ts @@ -0,0 +1,503 @@ +// Offsets count UTF-8 bytes appended over a history's life, so they keep naming the same +// text as output is trimmed, and minus `fileStart` they are positions in its file. Memory +// holds the newest text; for older, "spilled" text only sizes stay, and the file has it. +export const DEFAULT_HISTORY_BYTE_LIMIT = 256 * 1024 * 1024; +const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024; +const SPILLED_SEGMENT_BYTES = 64 * 1024; +// A history file is rewritten once its trimmed prefix is at least as large as the retained +// history, so total writes stay within twice the output. +const MIN_HISTORY_COMPACTION_BYTES = 4 * 1024 * 1024; + +interface Chunk { + data: string; + byteLength: number; + lineBreaks: number; +} + +interface Segment { + bytes: number; + lineBreaks: number; +} + +/** What the history file holds: this history's bytes from `fileStart` to `end`. */ +export interface PersistedHistoryFile { + readonly generation: number; + readonly fileStart: number; + readonly end: number; + /** The file may not match memory past the spilled part, so the next write rewrites it. */ + readonly dirty?: boolean; +} + +const utf8Width = (codePoint: number) => + codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + +/** The UTF-16 index where `bytes` UTF-8 bytes of `text` end, at a code point boundary. */ +function utf16IndexAtByte(text: string, bytes: number): number { + let index = 0; + let consumed = 0; + while (index < text.length) { + const codePoint = text.codePointAt(index)!; + const width = utf8Width(codePoint); + if (consumed + width > bytes) break; + consumed += width; + index += codePoint <= 0xffff ? 1 : 2; + } + return index; +} + +const countLineBreaks = (data: string) => { + let lineBreaks = 0; + for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { + lineBreaks += 1; + } + return lineBreaks; +}; + +export class BoundedTerminalHistory { + private readonly maxLines: number; + private readonly maxBytes: number; + private chunks: Array = []; + private start = 0; + private byteLength = 0; + private lineBreaks = 0; + private spilled: Array = []; + private spilledStart = 0; + private spilledBytes = 0; + private spilledLines = 0; + private end = 0; + private generation = 0; + // Reading the old string's tail on each append can force chunk concatenation. + private lastCodeUnit: number | undefined; + private cachedValue: string | null = ""; + persisted: PersistedHistoryFile | null = null; + + constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) { + this.maxLines = maxLines; + this.maxBytes = maxBytes; + this.append(initial); + } + + /** + * A history read back from a file: `segments` describe the file's bytes from `start` that + * stay on disk, and `tail` is the text after them. + */ + static restored( + maxLines: number, + maxBytes: number, + start: number, + segments: ReadonlyArray, + tail: string, + ): BoundedTerminalHistory { + const history = new BoundedTerminalHistory(maxLines, "", maxBytes); + history.end = start; + for (const segment of segments) { + if (segment.bytes === 0) continue; + history.spilled.push({ ...segment }); + history.spilledBytes += segment.bytes; + history.spilledLines += segment.lineBreaks; + history.end += segment.bytes; + } + history.trim(); + history.append(tail); + return history; + } + + get startOffset(): number { + return this.end - this.spilledBytes - this.byteLength; + } + + /** Where the text held in memory starts; older text is only in the file. */ + get memoryStart(): number { + return this.end - this.byteLength; + } + + get endOffset(): number { + return this.end; + } + + get bytes(): number { + return this.spilledBytes + this.byteLength; + } + + get memoryBytes(): number { + return this.byteLength; + } + + /** Changes whenever retained text is dropped without trimming, as by `clear`. */ + get clearGeneration(): number { + return this.generation; + } + + get endsInHighSurrogate(): boolean { + const last = this.lastCodeUnit; + return last !== undefined && last >= 0xd800 && last <= 0xdbff; + } + + append(text: string): void { + if (text.length === 0) return; + this.cachedValue = null; + if (this.maxBytes <= 0 || this.maxLines <= 0) { + this.clearRetained(); + this.end += Buffer.byteLength(text); + if (this.maxBytes > 0 && text.endsWith("\n")) { + this.end -= 1; + this.appendChunk("\n"); + } + return; + } + + let offset = 0; + const previous = this.chunks.at(-1); + const lastCode = this.lastCodeUnit; + const firstCode = text.charCodeAt(0); + if ( + previous && + lastCode !== undefined && + lastCode >= 0xd800 && + lastCode <= 0xdbff && + firstCode >= 0xdc00 && + firstCode <= 0xdfff + ) { + // Joining a split surrogate changes its UTF-8 size from 3 to 4 bytes. + previous.data += text[0]; + previous.byteLength += 1; + this.byteLength += 1; + this.end += 1; + this.lastCodeUnit = firstCode; + offset = 1; + this.trim(); + } + + while (offset < text.length) { + let end = Math.min(offset + MAX_HISTORY_CHUNK_LENGTH, text.length); + const before = text.charCodeAt(end - 1); + const after = text.charCodeAt(end); + if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) { + end -= 1; + } + const data = text.slice(offset, end); + // Detach small chunks from large input strings so evicted prefixes can be collected. + this.appendChunk( + text.length > MAX_HISTORY_CHUNK_LENGTH + ? Buffer.from(data, "utf16le").toString("utf16le") + : data, + ); + this.trim(); + offset = end; + } + } + + private appendChunk(data: string): void { + const byteLength = Buffer.byteLength(data); + const lineBreaks = countLineBreaks(data); + const previous = this.chunks.at(-1); + if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) { + previous.data += data; + previous.byteLength += byteLength; + previous.lineBreaks += lineBreaks; + } else { + this.chunks.push({ data, byteLength, lineBreaks }); + } + this.byteLength += byteLength; + this.lineBreaks += lineBreaks; + this.end += byteLength; + this.lastCodeUnit = data.charCodeAt(data.length - 1); + this.cachedValue = null; + } + + private discardChunk(): void { + const first = this.chunks[this.start]!; + this.byteLength -= first.byteLength; + this.lineBreaks -= first.lineBreaks; + this.chunks[this.start++] = undefined; + this.cachedValue = null; + } + + private trimChunk(offset: number, byteLength: number, lineBreaks: number): void { + const first = this.chunks[this.start]!; + if (offset === first.data.length) { + this.discardChunk(); + return; + } + first.data = first.data.slice(offset); + first.byteLength -= byteLength; + first.lineBreaks -= lineBreaks; + this.byteLength -= byteLength; + this.lineBreaks -= lineBreaks; + this.cachedValue = null; + } + + private discardSegment(): void { + const first = this.spilled[this.spilledStart]!; + this.spilledBytes -= first.bytes; + this.spilledLines -= first.lineBreaks; + this.spilled[this.spilledStart++] = undefined; + if (this.spilledStart === this.spilled.length) { + this.spilled = []; + this.spilledStart = 0; + } else if (this.spilledStart > 2_048 && this.spilledStart * 2 >= this.spilled.length) { + this.spilled = this.spilled.slice(this.spilledStart); + this.spilledStart = 0; + } + } + + private linesOver(): number { + const trailingNewline = this.lastCodeUnit === 10; + return ( + this.spilledLines + + this.lineBreaks + + (trailingNewline || this.byteLength === 0 ? 0 : 1) - + this.maxLines + ); + } + + private trim(): void { + // Text on disk is dropped a whole segment at a time, so a limit can keep slightly less. + while ( + this.spilledBytes > 0 && + (this.linesOver() > 0 || this.spilledBytes + this.byteLength > this.maxBytes) + ) { + this.discardSegment(); + } + + let linesToDrop = this.linesOver(); + while (linesToDrop > 0 && this.start < this.chunks.length) { + const first = this.chunks[this.start]!; + if (first.lineBreaks < linesToDrop) { + linesToDrop -= first.lineBreaks; + this.discardChunk(); + continue; + } + let offset = 0; + for (let line = 0; line < linesToDrop; line += 1) { + offset = first.data.indexOf("\n", offset) + 1; + } + this.trimChunk(offset, Buffer.byteLength(first.data.slice(0, offset)), linesToDrop); + linesToDrop = 0; + } + + while (this.byteLength > this.maxBytes) { + const first = this.chunks[this.start]!; + const bytesToDrop = this.byteLength - this.maxBytes; + if (first.byteLength <= bytesToDrop) { + this.discardChunk(); + continue; + } + if (first.byteLength === first.data.length && first.lineBreaks === 0) { + this.trimChunk(bytesToDrop, bytesToDrop, 0); + continue; + } + let offset = 0; + let bytes = 0; + let lineBreaks = 0; + while (bytes < bytesToDrop) { + const codePoint = first.data.codePointAt(offset)!; + bytes += utf8Width(codePoint); + offset += codePoint <= 0xffff ? 1 : 2; + if (codePoint === 10) lineBreaks += 1; + } + this.trimChunk(offset, bytes, lineBreaks); + } + this.compactChunks(); + } + + private compactChunks(): void { + if ( + this.start === this.chunks.length || + (this.start > 2_048 && this.start * 2 >= this.chunks.length) + ) { + this.chunks = this.chunks.slice(this.start); + this.start = 0; + if (this.chunks.length === 0) this.lastCodeUnit = undefined; + } + } + + /** + * Releases the oldest text held in memory, down to about `targetBytes`, keeping only its + * size. Only text the file already holds is released. + */ + spill(targetBytes: number): void { + const persisted = this.persisted; + if (persisted === null || persisted.generation !== this.generation || persisted.dirty) return; + let chunkEnd = this.memoryStart; + while (this.byteLength > targetBytes && this.start < this.chunks.length - 1) { + const first = this.chunks[this.start]!; + chunkEnd += first.byteLength; + if (chunkEnd > persisted.end) break; + const last = this.spilled.at(-1); + if ( + last !== undefined && + this.spilled.length > this.spilledStart && + last.bytes < SPILLED_SEGMENT_BYTES + ) { + last.bytes += first.byteLength; + last.lineBreaks += first.lineBreaks; + } else { + this.spilled.push({ bytes: first.byteLength, lineBreaks: first.lineBreaks }); + } + this.spilledBytes += first.byteLength; + this.spilledLines += first.lineBreaks; + this.discardChunk(); + } + this.compactChunks(); + } + + private clearRetained(): void { + this.chunks = []; + this.start = 0; + this.byteLength = 0; + this.lineBreaks = 0; + this.spilled = []; + this.spilledStart = 0; + this.spilledBytes = 0; + this.spilledLines = 0; + this.lastCodeUnit = undefined; + this.cachedValue = ""; + } + + clear(): void { + this.clearRetained(); + this.generation += 1; + } + + /** The text held in memory. */ + value(): string { + if (this.cachedValue !== null) return this.cachedValue; + this.cachedValue = this.chunks + .slice(this.start) + .map((chunk) => chunk!.data) + .join(""); + return this.cachedValue; + } + + /** The text from `from` to `to`, which must both lie in memory. */ + memoryText(from: number, to: number = this.end): string { + const lower = Math.max(from, this.memoryStart); + const upper = Math.min(to, this.end); + if (upper <= lower) return ""; + const pieces: string[] = []; + let chunkStart = this.memoryStart; + for (let index = this.start; index < this.chunks.length && chunkStart < upper; index += 1) { + const chunk = this.chunks[index]!; + const chunkEnd = chunkStart + chunk.byteLength; + if (chunkEnd > lower) { + const begin = lower > chunkStart ? utf16IndexAtByte(chunk.data, lower - chunkStart) : 0; + const finish = + upper < chunkEnd ? utf16IndexAtByte(chunk.data, upper - chunkStart) : chunk.data.length; + pieces.push( + begin === 0 && finish === chunk.data.length + ? chunk.data + : chunk.data.slice(begin, finish), + ); + } + chunkStart = chunkEnd; + } + return pieces.join(""); + } + + /** Whether the text just before `offset` is a line break, when memory holds it. */ + lineBreakBefore(offset: number): boolean | undefined { + if (offset <= this.memoryStart || offset > this.end) return undefined; + return this.memoryText(offset - 1, offset) === "\n"; + } +} + +/** A page of output: its text, where it starts and ends, and whether more lies either side. */ +export interface HistoryPage { + readonly data: string; + readonly offset: number; + readonly end: number; + readonly olderHistory: boolean; + readonly newerHistory: boolean; +} + +/** + * Trims a page read before `end` so it starts at a line (unless it starts the history), + * since a page cut inside a line would draw that line's tail as if it were whole. + */ +export function startPageAtLine( + data: string, + offset: number, + historyStart: number, + lineBreakBefore: boolean, +): { readonly data: string; readonly offset: number } { + if (offset <= historyStart || lineBreakBefore) return { data, offset }; + const lineStart = data.indexOf("\n") + 1; + if (lineStart <= 0 || lineStart >= data.length) return { data, offset }; + return { + data: data.slice(lineStart), + offset: offset + Buffer.byteLength(data.slice(0, lineStart)), + }; +} + +export type HistoryFileWrite = + | { + readonly append: true; + readonly text: string; + readonly persisted: PersistedHistoryFile; + } + | { + readonly append: false; + /** File bytes to copy into the new file first, from the current file. */ + readonly copy: { readonly from: number; readonly to: number } | null; + readonly text: string; + readonly persisted: PersistedHistoryFile; + }; + +/** + * What to write so the history file holds `history`: the text it lacks, appended; or a new + * file, written aside and renamed over the old one, when the history was cleared, the file + * is unknown or dirty, or its trimmed prefix has outgrown the retained text. + */ +export function planHistoryFileWrite( + history: BoundedTerminalHistory, + minCompactionBytes = MIN_HISTORY_COMPACTION_BYTES, +): HistoryFileWrite { + const generation = history.clearGeneration; + // A trailing high surrogate is written with its pair, or encoding would replace it. + const end = history.endsInHighSurrogate ? history.endOffset - 3 : history.endOffset; + const persisted = history.persisted; + const current = persisted !== null && persisted.generation === generation ? persisted : null; + if (current !== null && !current.dirty && current.end >= history.memoryStart) { + const trimmedBytes = history.startOffset - current.fileStart; + if (trimmedBytes < Math.max(minCompactionBytes, history.bytes)) { + return { + append: true, + text: current.end < end ? history.memoryText(current.end, end) : "", + persisted: { generation, fileStart: current.fileStart, end: Math.max(end, current.end) }, + }; + } + } + const start = history.startOffset; + const memoryStart = history.memoryStart; + return { + append: false, + // Text released from memory is only in the file; it was written before it was released. + copy: + current !== null && memoryStart > start + ? { from: start - current.fileStart, to: memoryStart - current.fileStart } + : null, + text: history.memoryText(memoryStart, end), + persisted: { generation, fileStart: start, end: Math.max(end, memoryStart) }, + }; +} + +/** + * Releases the oldest in-memory output of the histories holding the most, down to `floor` + * each, until all together fit `budget`. Released output stays readable from the files. + */ +export function releaseHistoryMemory( + histories: Iterable, + budget: number, + floor: number, +): void { + const all = [...histories]; + let total = all.reduce((sum, history) => sum + history.memoryBytes, 0); + if (total <= budget) return; + for (const history of all.sort((left, right) => right.memoryBytes - left.memoryBytes)) { + const before = history.memoryBytes; + history.spill(floor); + total -= before - history.memoryBytes; + if (total <= budget) return; + } +} diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 13276da436fcd..a318da166f2f3 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -237,6 +237,8 @@ interface CreateManagerOptions { >[0]["registerTerminalProcesses"]; maxRetainedInactiveSessions?: number; historyByteLimit?: number; + historyMemoryBytes?: number; + historyCompactionBytes?: number; ptyAdapter?: FakePtyAdapter; resolveProviderInstanceEnvironment?: Parameters< typeof TerminalManager.makeWithOptions @@ -275,6 +277,12 @@ const createManager = ( ...(options.historyByteLimit !== undefined ? { historyByteLimit: options.historyByteLimit } : {}), + ...(options.historyMemoryBytes !== undefined + ? { historyMemoryBytes: options.historyMemoryBytes } + : {}), + ...(options.historyCompactionBytes !== undefined + ? { historyCompactionBytes: options.historyCompactionBytes } + : {}), ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}), ...(options.env !== undefined ? { env: options.env } : {}), ...(options.subprocessInspector !== undefined @@ -383,8 +391,8 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen history.append(chunk); expected = retainedHistory(expected + chunk, maxLines, maxBytes); expect(history.value()).toBe(expected); - expect(history.textFrom(history.startOffset)).toBe(expected); - expect(history.endOffset - history.startOffset).toBe(expected.length); + expect(history.memoryText(history.startOffset)).toBe(expected); + expect(history.endOffset - history.startOffset).toBe(Buffer.byteLength(expected)); } } } @@ -408,82 +416,6 @@ it("bounds long partial lines and joins surrogate pairs across chunk boundaries" } }); -it("pages retained output back to its start without gaps or oversized pages", () => { - const history = new TerminalManager.BoundedTerminalHistory(40, "", 2_000); - for (let line = 0; line < 100; line += 1) - history.append(`line ${line} 損🚀 ${"x".repeat(line % 70)}\n`); - const latest = history.endOffset; - history.append("prompt$ "); - - const pages: string[] = []; - let before = latest; - for (;;) { - const page = history.pageBefore(before, 300); - expect(Buffer.byteLength(page.data)).toBeLessThanOrEqual(300); - expect(page.offset + page.data.length).toBe(before); - // Pages after the first start at a line. - if (page.older) expect(history.textFrom(page.offset - 1)?.[0]).toBe("\n"); - pages.unshift(page.data); - before = page.offset; - if (!page.older) break; - } - expect(before).toBe(history.startOffset); - expect(pages.join("") + "prompt$ ").toBe(history.value()); - - // Offsets keep naming the same text after newer output trims older lines. - const kept = history.textFrom(latest); - history.append("more\n".repeat(30)); - expect(history.textFrom(latest)).toBe(kept + "more\n".repeat(30)); - expect(history.pageBefore(history.startOffset - 1, 300)).toEqual({ - data: "", - offset: history.startOffset, - older: false, - }); - history.clear(); - expect(history.pageBefore(latest, 300).older).toBe(false); -}); - -it("appends history files and rewrites them only when cleared or mostly trimmed", () => { - const history = new TerminalManager.BoundedTerminalHistory(3, "", 1_000); - let file = ""; - const persist = () => { - const write = TerminalManager.planHistoryFileWrite(history, 64); - file = write.append ? file + write.text : write.text; - history.persisted = write.persisted; - expect(Buffer.byteLength(file)).toBe(write.persisted.fileBytes); - // Loading keeps the file's newest lines, which are exactly the history. - if (!history.endsInHighSurrogate) { - expect(new TerminalManager.BoundedTerminalHistory(3, file, 1_000).value()).toBe( - history.value(), - ); - } - return write.append; - }; - - history.append("one\ntwo\n"); - expect(persist()).toBe(false); - history.append("three\nfour\n"); - expect(persist()).toBe(true); - expect(file).toBe("one\ntwo\nthree\nfour\n"); - history.append("x".repeat(80) + "\n"); - expect(persist()).toBe(true); - history.append("a\nb\nc\n"); - // The trimmed prefix outgrew both the retained text and the minimum. - expect(persist()).toBe(false); - expect(file).toBe(history.value()); - - // A split surrogate waits for its pair instead of being written as U+FFFD. - history.append("\ud83d"); - expect(persist()).toBe(true); - history.append("\ude80\n"); - expect(persist()).toBe(true); - expect(file.endsWith("🚀\n")).toBe(true); - - history.clear(); - expect(persist()).toBe(false); - expect(file).toBe(""); -}); - it.layer( Layer.mergeAll( NodeServices.layer, @@ -1095,33 +1027,71 @@ it.layer( }), ); - it.effect("attaches with the newest output and pages older output contiguously", () => + it.effect("pages any part of history, from memory or its file, in both directions", () => Effect.gen(function* () { + // Memory keeps about 1 MiB; the rest is read back from the file after a reopen. const { manager, ptyAdapter } = yield* createManager(1_000_000, { historyByteLimit: 64 * 1024 * 1024, + historyMemoryBytes: 1, }); yield* manager.open(openInput()); - const lines = Array.from({ length: 40_000 }, (_, index) => `output line ${index}\n`); + const lines = Array.from({ length: 120_000 }, (_, index) => `output line ${index} ✓\n`); for (let index = 0; index < lines.length; index += 1_000) { ptyAdapter.processes[0]!.emitData(lines.slice(index, index + 1_000).join("")); } + yield* manager.close({ threadId: "thread-1" }); const attached = yield* manager.open(openInput()); expect(attached.olderHistory).toBe(true); - expect(attached.history.endsWith(lines.at(-1)!)).toBe(true); + const all = lines.join(""); + const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }; let text = attached.history; let before = attached.historyOffset!; for (let older = true; older;) { - const page = yield* manager.historyPage({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - before, - }); + const page = yield* manager.historyPage({ ...target, before }); + expect(page.end).toBe(before); + expect(Buffer.byteLength(page.data)).toBeLessThanOrEqual(512 * 1024); text = page.data + text; before = page.offset; older = page.olderHistory; } - expect(text).toBe(lines.join("")); + expect(before).toBe(0); + expect(text.startsWith(all)).toBe(true); + + let forward = ""; + let after = 0; + for (let newer = true; newer;) { + const page = yield* manager.historyPage({ ...target, after }); + expect(page.offset).toBe(after); + forward += page.data; + after = page.end; + newer = page.newerHistory; + } + expect(forward).toBe(text); + }), + ); + + it.effect("replaces a mostly trimmed history file by renaming a complete copy", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { manager, ptyAdapter, logsDir } = yield* createManager(1_000, { + historyByteLimit: 100, + historyCompactionBytes: 1, + }); + yield* manager.open(openInput()); + ptyAdapter.processes[0]!.emitData("first\n"); + yield* manager.close({ threadId: "thread-1" }); + const filePath = yield* historyLogPath(logsDir); + const before = yield* fs.stat(filePath); + yield* manager.open(openInput()); + ptyAdapter.processes[1]!.emitData("x".repeat(60) + "\n" + "y".repeat(60) + "\n"); + yield* manager.close({ threadId: "thread-1" }); + // A rewrite in place would keep the file and could leave it half written. + expect((yield* fs.stat(filePath)).ino).not.toBe(before.ino); + expect(yield* readFileString(filePath)).toBe( + ("x".repeat(60) + "\n" + "y".repeat(60) + "\n").slice(-100), + ); + expect(yield* fs.readDirectory(logsDir)).toHaveLength(1); }), ); @@ -1596,23 +1566,19 @@ it.layer( it.effect("retains encoded history if migration cannot write the bounded file", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - let failNextWrite = true; + let failNextRename = true; const limited = FileSystem.FileSystem.of({ ...fs, - writeFileString: (filePath, data, options) => { - if (!failNextWrite) return fs.writeFileString(filePath, data, options); - failNextWrite = false; - return fs.writeFileString(filePath, "partial").pipe( - Effect.andThen( - Effect.fail( - PlatformError.systemError({ - _tag: "Unknown", - module: "FileSystem", - method: "writeFileString", - cause: { code: "ENOSPC" }, - }), - ), - ), + rename: (from, to) => { + if (!failNextRename) return fs.rename(from, to); + failNextRename = false; + return Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "rename", + cause: { code: "ENOSPC" }, + }), ); }, }); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index bb13ef922b02a..e2df04465a74a 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -77,6 +77,16 @@ import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts"; import { terminalOutputStream } from "./OutputProtocol.ts"; +import { + BoundedTerminalHistory, + DEFAULT_HISTORY_BYTE_LIMIT, + planHistoryFileWrite, + releaseHistoryMemory, + startPageAtLine, + type HistoryPage, +} from "./History.ts"; + +export { BoundedTerminalHistory }; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; export { @@ -95,13 +105,15 @@ export { }; const DEFAULT_HISTORY_LINE_LIMIT = 1_000_000; -const DEFAULT_HISTORY_BYTE_LIMIT = 256 * 1024 * 1024; -// History files grow by appends; a rewrite drops their trimmed prefix once it is at -// least as large as the retained history, so total writes stay within twice the output. -const MIN_HISTORY_COMPACTION_BYTES = 4 * 1024 * 1024; +// Each terminal keeps its newest output in memory; older output is read from its file. +const DEFAULT_HISTORY_MEMORY_BYTES = 16 * 1024 * 1024; +// All terminals' in-memory output together; past it, the largest release their oldest. +const DEFAULT_HISTORY_MEMORY_BUDGET = 512 * 1024 * 1024; +// A terminal keeps at least this much in memory, so attaching never reads its file. +const MIN_HISTORY_MEMORY_BYTES = 2 * TERMINAL_HISTORY_PAGE_BYTES; +const HISTORY_FILE_BLOCK_BYTES = 1024 * 1024; // eCryptfs permits 143-byte names. const MAX_HISTORY_FILENAME_BYTES = 143; -const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024; const DEFAULT_PERSIST_DEBOUNCE_MS = 250; const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000; const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000; @@ -115,7 +127,8 @@ const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 4_096; -const DEFAULT_MAX_RETAINED_INACTIVE_HISTORY_BYTES = 4 * 1024 * 1024 * 1024; +// Exited terminals' in-memory output; evicted ones reload from their files. +const DEFAULT_MAX_RETAINED_INACTIVE_HISTORY_BYTES = 256 * 1024 * 1024; const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; // The tmux/screen/Zellij keys name the multiplexer pane that launched the server, @@ -349,6 +362,7 @@ type DrainProcessEventAction = terminalId: string; sequence: number; history: BoundedTerminalHistory | null; + historyEnd: number; data: string; } | { @@ -398,9 +412,22 @@ function terminalWireLabel(session: TerminalSessionState): string { return truncateTerminalWireLabel(getTerminalLabel(session.terminalId)); } +/** The newest output held in memory, up to one page, starting at a line. */ +function newestHistoryPage(history: BoundedTerminalHistory): HistoryPage { + const end = history.endOffset; + const from = Math.max(history.memoryStart, end - TERMINAL_HISTORY_PAGE_BYTES); + const page = startPageAtLine( + history.memoryText(from, end), + from, + history.startOffset, + history.lineBreakBefore(from) ?? false, + ); + return { ...page, end, olderHistory: page.offset > history.startOffset, newerHistory: false }; +} + function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { // Older output is paged in with `terminal.history`, so an attach stays small. - const newest = session.history.pageBefore(session.history.endOffset, TERMINAL_HISTORY_PAGE_BYTES); + const newest = newestHistoryPage(session.history); return { threadId: session.threadId, terminalId: session.terminalId, @@ -410,7 +437,8 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { pid: session.pid, history: newest.data, historyOffset: newest.offset, - olderHistory: newest.older, + historyEnd: newest.end, + olderHistory: newest.olderHistory, exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -886,349 +914,6 @@ const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnaps return processTableSnapshotFromProcesses(processes); }); -interface TerminalHistoryChunk { - data: string; - byteLength: number; - lineBreaks: number; -} - -/** How much of a history file already holds this history's text. */ -interface PersistedHistoryFile { - readonly generation: number; - /** History offset where the file's text ends. */ - readonly end: number; - readonly fileBytes: number; -} - -export class BoundedTerminalHistory { - private readonly maxLines: number; - private readonly maxBytes: number; - private chunks: Array = []; - private start = 0; - private byteLength = 0; - private lineBreaks = 0; - private length = 0; - // Offsets count UTF-16 code units appended over the history's life, so a range - // keeps naming the same text while newer output arrives and older output is trimmed. - private end = 0; - private generation = 0; - // Reading the old string's tail on each append can force chunk concatenation. - private lastCodeUnit: number | undefined; - private cachedValue: string | null = ""; - persisted: PersistedHistoryFile | null = null; - - constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) { - this.maxLines = maxLines; - this.maxBytes = maxBytes; - this.append(initial); - } - - get startOffset(): number { - return this.end - this.length; - } - - get endOffset(): number { - return this.end; - } - - get bytes(): number { - return this.byteLength; - } - - get endsInHighSurrogate(): boolean { - const last = this.lastCodeUnit; - return last !== undefined && last >= 0xd800 && last <= 0xdbff; - } - - /** Changes whenever retained text is dropped without trimming, as by `clear`. */ - get clearGeneration(): number { - return this.generation; - } - - append(text: string): void { - if (text.length === 0) return; - this.cachedValue = null; - if (this.maxBytes <= 0 || this.maxLines <= 0) { - this.clear(); - this.end += text.length; - if (this.maxBytes > 0 && text.endsWith("\n")) { - this.end -= 1; - this.appendChunk("\n"); - } - return; - } - - let offset = 0; - const previous = this.chunks.at(-1); - const lastCode = this.lastCodeUnit; - const firstCode = text.charCodeAt(0); - if ( - previous && - lastCode !== undefined && - lastCode >= 0xd800 && - lastCode <= 0xdbff && - firstCode >= 0xdc00 && - firstCode <= 0xdfff - ) { - // Joining a split surrogate changes its UTF-8 size from 3 to 4 bytes. - previous.data += text[0]; - previous.byteLength += 1; - this.byteLength += 1; - this.length += 1; - this.end += 1; - this.lastCodeUnit = firstCode; - offset = 1; - this.trim(); - } - - while (offset < text.length) { - let end = Math.min(offset + MAX_HISTORY_CHUNK_LENGTH, text.length); - const before = text.charCodeAt(end - 1); - const after = text.charCodeAt(end); - if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) { - end -= 1; - } - const data = text.slice(offset, end); - // Detach small chunks from large input strings so evicted prefixes can be collected. - this.appendChunk( - text.length > MAX_HISTORY_CHUNK_LENGTH - ? Buffer.from(data, "utf16le").toString("utf16le") - : data, - ); - this.trim(); - offset = end; - } - } - - private appendChunk(data: string): void { - const byteLength = Buffer.byteLength(data); - let lineBreaks = 0; - for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { - lineBreaks += 1; - } - const previous = this.chunks.at(-1); - if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) { - previous.data += data; - previous.byteLength += byteLength; - previous.lineBreaks += lineBreaks; - } else { - this.chunks.push({ data, byteLength, lineBreaks }); - } - this.byteLength += byteLength; - this.lineBreaks += lineBreaks; - this.length += data.length; - this.end += data.length; - this.lastCodeUnit = data.charCodeAt(data.length - 1); - this.cachedValue = null; - } - - private discardChunk(): void { - const first = this.chunks[this.start]!; - this.byteLength -= first.byteLength; - this.lineBreaks -= first.lineBreaks; - this.length -= first.data.length; - this.chunks[this.start++] = undefined; - } - - private trimChunk(offset: number, byteLength: number, lineBreaks: number): void { - const first = this.chunks[this.start]!; - if (offset === first.data.length) { - this.discardChunk(); - return; - } - first.data = first.data.slice(offset); - first.byteLength -= byteLength; - first.lineBreaks -= lineBreaks; - this.byteLength -= byteLength; - this.lineBreaks -= lineBreaks; - this.length -= offset; - } - - private trim(): void { - const trailingNewline = this.lastCodeUnit === 10; - let linesToDrop = this.lineBreaks + (trailingNewline ? 0 : 1) - this.maxLines; - while (linesToDrop > 0) { - const first = this.chunks[this.start]!; - if (first.lineBreaks < linesToDrop) { - linesToDrop -= first.lineBreaks; - this.discardChunk(); - continue; - } - let offset = 0; - for (let line = 0; line < linesToDrop; line += 1) { - offset = first.data.indexOf("\n", offset) + 1; - } - this.trimChunk(offset, Buffer.byteLength(first.data.slice(0, offset)), linesToDrop); - linesToDrop = 0; - } - - while (this.byteLength > this.maxBytes) { - const first = this.chunks[this.start]!; - const bytesToDrop = this.byteLength - this.maxBytes; - if (first.byteLength <= bytesToDrop) { - this.discardChunk(); - continue; - } - if (first.byteLength === first.data.length && first.lineBreaks === 0) { - this.trimChunk(bytesToDrop, bytesToDrop, 0); - continue; - } - let offset = 0; - let bytes = 0; - let lineBreaks = 0; - while (bytes < bytesToDrop) { - const codePoint = first.data.codePointAt(offset)!; - bytes += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; - offset += codePoint <= 0xffff ? 1 : 2; - if (codePoint === 10) lineBreaks += 1; - } - this.trimChunk(offset, bytes, lineBreaks); - } - if ( - this.start === this.chunks.length || - (this.start > 2_048 && this.start * 2 >= this.chunks.length) - ) { - this.chunks = this.chunks.slice(this.start); - this.start = 0; - if (this.chunks.length === 0) this.lastCodeUnit = undefined; - } - } - - clear(): void { - this.chunks = []; - this.start = 0; - this.byteLength = 0; - this.lineBreaks = 0; - this.length = 0; - this.generation += 1; - this.lastCodeUnit = undefined; - this.cachedValue = ""; - } - - value(): string { - if (this.cachedValue !== null) return this.cachedValue; - this.cachedValue = this.chunks - .slice(this.start) - .map((chunk) => chunk!.data) - .join(""); - return this.cachedValue; - } - - private codeUnitBefore(offset: number): number | undefined { - let chunkEnd = this.end; - for (let index = this.chunks.length - 1; index >= this.start; index -= 1) { - const data = this.chunks[index]!.data; - const chunkStart = chunkEnd - data.length; - if (chunkStart < offset) return data.charCodeAt(offset - 1 - chunkStart); - chunkEnd = chunkStart; - } - return undefined; - } - - /** The retained text from `offset` to the end, or null once `offset` was trimmed away. */ - textFrom(offset: number): string | null { - if (offset < this.startOffset || offset > this.end) return null; - const pieces: string[] = []; - let chunkEnd = this.end; - for (let index = this.chunks.length - 1; index >= this.start && chunkEnd > offset; index -= 1) { - const data = this.chunks[index]!.data; - const chunkStart = chunkEnd - data.length; - pieces.push(chunkStart >= offset ? data : data.slice(offset - chunkStart)); - chunkEnd = chunkStart; - } - return pieces.reverse().join(""); - } - - /** - * Up to `maxBytes` of the retained text ending at `before`, starting at a line - * when one begins inside it. `older` says whether retained text precedes it. - */ - pageBefore( - before: number, - maxBytes: number, - ): { readonly data: string; readonly offset: number; readonly older: boolean } { - const end = Math.min(before, this.end); - if (end <= this.startOffset || maxBytes <= 0) { - return { data: "", offset: Math.max(end, this.startOffset), older: false }; - } - const pieces: string[] = []; - let bytes = 0; - let chunkEnd = this.end; - let index = this.chunks.length - 1; - for (; index >= this.start && bytes < maxBytes; index -= 1) { - const chunk = this.chunks[index]!; - const chunkStart = chunkEnd - chunk.data.length; - if (chunkStart < end) { - const data = chunkEnd <= end ? chunk.data : chunk.data.slice(0, end - chunkStart); - pieces.push(data); - bytes += data === chunk.data ? chunk.byteLength : Buffer.byteLength(data); - } - chunkEnd = chunkStart; - } - pieces.reverse(); - let offset = chunkEnd; - if (bytes > maxBytes) { - // Drop whole code points from the front until the page fits. - const first = pieces[0]!; - let cut = 0; - while (bytes > maxBytes && cut < first.length) { - const codePoint = first.codePointAt(cut)!; - bytes -= codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; - cut += codePoint <= 0xffff ? 1 : 2; - } - pieces[0] = first.slice(cut); - offset += cut; - } - let data = pieces.join(""); - if (offset > this.startOffset && this.codeUnitBefore(offset) !== 10) { - // A page cut inside a line would draw that line's tail as if it were whole. - const lineStart = data.indexOf("\n") + 1; - if (lineStart > 0 && lineStart < data.length) { - data = data.slice(lineStart); - offset += lineStart; - } - } - return { data, offset, older: offset > this.startOffset }; - } -} - -/** - * What to write so a history file ends with `history`: the text it lacks, or the whole - * history when the file was cleared, is unknown, or its trimmed prefix has outgrown the - * retained text. Loading reads only the file's tail, so a smaller prefix can stay. - */ -export function planHistoryFileWrite( - history: BoundedTerminalHistory, - minCompactionBytes = MIN_HISTORY_COMPACTION_BYTES, -): { readonly append: boolean; readonly text: string; readonly persisted: PersistedHistoryFile } { - const generation = history.clearGeneration; - // A trailing high surrogate is written with its pair, or encoding would replace it. - const end = history.endsInHighSurrogate ? history.endOffset - 1 : history.endOffset; - const persisted = history.persisted; - const appended = - persisted !== null && persisted.generation === generation - ? history.textFrom(persisted.end) - : null; - if (persisted !== null && appended !== null) { - const text = appended.slice(0, Math.max(0, end - persisted.end)); - const fileBytes = persisted.fileBytes + Buffer.byteLength(text); - const trimmedBytes = fileBytes - history.bytes; - if (trimmedBytes < Math.max(minCompactionBytes, history.bytes)) { - return { - append: true, - text, - persisted: { generation, end: Math.max(end, persisted.end), fileBytes }, - }; - } - } - const text = history.textFrom(history.startOffset)!.slice(0, end - history.startOffset); - return { - append: false, - text, - persisted: { generation, end, fileBytes: Buffer.byteLength(text) }, - }; -} - // Pop beyond Ghostty's eight-entry Kitty stacks on both screens before clearing // flags. A 1049 round trip preserves the main cursor, text, and scrollback. const INHERITED_INPUT_RESET = @@ -1236,23 +921,22 @@ const INHERITED_INPUT_RESET = "\u001b[?1;9;66;67;1000;1002;1003;1004;1005;1006;1015;2004l" + "\u001b[?25;1035;1036h\u001b[<100u\u001b[=0;1u\u001b[>4m"; -function neutralizeInheritedHistory(history: string, maxLines: number, maxBytes: number): string { - // Scan exactly the cold replay window, reserving the entire longest reset so - // neither the server nor the client can trim away the entry after we choose its exit. - const resetBytes = history.includes("\u001b") - ? Buffer.byteLength(INHERITED_INPUT_RESET + "\u001b7\u001b[?1049l") - : 0; - history = new BoundedTerminalHistory( - // The suffix occupies the empty line after a trailing newline, too. - resetBytes > 0 && history.endsWith("\n") ? maxLines - 1 : maxLines, - history, - Math.max(0, maxBytes - resetBytes), - ).value(); - if (!history.includes("\u001b")) return history; +// Restored history is scanned only this far back for an unfinished alternate screen. +const INHERITED_SCAN_BYTES = 4 * 1024 * 1024; + +/** + * Appends what a restored history needs so a new shell starts from a clean screen: leave an + * alternate screen it was left on, then reset input modes. + */ +function neutralizeInheritedHistory(history: BoundedTerminalHistory): void { + const tail = history.memoryText( + Math.max(history.memoryStart, history.endOffset - INHERITED_SCAN_BYTES), + ); + if (!tail.includes("\u001b")) return; // An unconditional 1049 reset restores a stale saved cursor on the main // screen. The exit must match the inherited screen's cursor-save behavior. let alternateScreen: number | undefined; - for (const match of history.matchAll(/\u001b(?:\[\?([0-9;]+)([hl])|(c))/gu)) { + for (const match of tail.matchAll(/\u001b(?:\[\?([0-9;]+)([hl])|(c))/gu)) { if (match[3]) alternateScreen = undefined; for (const parameter of (match[1] ?? "").split(";")) { const mode = Number(parameter); @@ -1261,11 +945,11 @@ function neutralizeInheritedHistory(history: string, maxLines: number, maxBytes: } } } - // A client may trim away the entry, leaving us on main: save its current + // A client may not have the entry, leaving it on main: save its current // cursor before exiting. On alternate this saves only the alternate cursor. const leaveAlternateScreen = alternateScreen === undefined ? "" : `\u001b7\u001b[?${alternateScreen}l`; - return history + leaveAlternateScreen + INHERITED_INPUT_RESET; + history.append(leaveAlternateScreen + INHERITED_INPUT_RESET); } function isCsiFinalByte(codePoint: number): boolean { @@ -1597,6 +1281,11 @@ interface TerminalManagerOptions { processKillGraceMs?: number; maxRetainedInactiveSessions?: number; maxRetainedInactiveHistoryBytes?: number; + /** Output each terminal keeps in memory; older output is read from its file. */ + historyMemoryBytes?: number; + /** Output all terminals keep in memory together. */ + historyMemoryBudget?: number; + historyCompactionBytes?: number; registerTerminalProcesses?: (input: { readonly threadId: string; readonly terminalId: string; @@ -1722,6 +1411,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const logsDir = options.logsDir; const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; const historyByteLimit = options.historyByteLimit ?? DEFAULT_HISTORY_BYTE_LIMIT; + const historyMemoryBytes = Math.max( + MIN_HISTORY_MEMORY_BYTES, + options.historyMemoryBytes ?? DEFAULT_HISTORY_MEMORY_BYTES, + ); + const historyMemoryBudget = options.historyMemoryBudget ?? DEFAULT_HISTORY_MEMORY_BUDGET; const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const agentScope = yield* AgentScope; @@ -2124,20 +1818,69 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* registerKillFiber(process, fiber); }); + // One terminal's file operations run one at a time, so a page read never sees its file + // being replaced and a rewrite never races an append. + const historyFileLocks = yield* KeyedLock.make(); + + const readFileRange = Effect.fn("terminal.readFileRange")(function* ( + filePath: string, + from: number, + to: number, + ) { + const file = yield* fileSystem.open(filePath, { flag: "r" }); + const bytes = new Uint8Array(Math.max(0, to - from)); + let length = 0; + while (length < bytes.length) { + const read = Number( + yield* file.read(bytes.subarray(length), { position: BigInt(from + length) }), + ); + if (read === 0) break; + length += read; + } + return bytes.subarray(0, length); + }, Effect.scoped); + const writeHistoryFile = Effect.fn("terminal.writeHistoryFile")(function* ( filePath: string, history: BoundedTerminalHistory, + sourcePath: string = filePath, ) { - const write = planHistoryFileWrite(history); - // A failed write leaves the file unknown, so the next one rewrites it. - history.persisted = null; + const write = planHistoryFileWrite(history, options.historyCompactionBytes); if (write.append) { if (write.text.length > 0) { + // A failed append may leave part of the text, so the next write replaces the file. + if (history.persisted !== null) history.persisted = { ...history.persisted, dirty: true }; yield* fileSystem.writeFileString(filePath, write.text, { flag: "a" }); } - } else { - yield* fileSystem.writeFileString(filePath, write.text); + history.persisted = write.persisted; + return; } + // Written aside and renamed over the old file, so a crash leaves one or the other whole. + yield* Effect.gen(function* () { + const temporaryPath = yield* fileSystem.makeTempFileScoped({ + directory: logsDir, + prefix: ".history-", + }); + yield* Effect.gen(function* () { + const out = yield* fileSystem.open(temporaryPath, { flag: "w" }); + const copy = write.copy; + if (copy !== null) { + for (let from = copy.from; from < copy.to; from += HISTORY_FILE_BLOCK_BYTES) { + const to = Math.min(copy.to, from + HISTORY_FILE_BLOCK_BYTES); + const block = yield* readFileRange(sourcePath, from, to); + if (block.length !== to - from) { + return yield* Effect.die( + new TerminalHistoryError({ operation: "read", threadId: "", terminalId: "" }), + ); + } + yield* out.writeAll(block); + } + } + yield* out.writeAll(Buffer.from(write.text)); + yield* out.sync; + }).pipe(Effect.scoped); + yield* fileSystem.rename(temporaryPath, filePath); + }).pipe(Effect.scoped); history.persisted = write.persisted; }); @@ -2161,14 +1904,27 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return; } - yield* writeHistoryFile(historyPath(threadId, terminalId), request.history).pipe( - Effect.catch((error) => - Effect.logWarning("failed to persist terminal history", { - threadId, - terminalId, - error, - }), - ), + yield* historyFileLocks + .withLock( + sessionKey, + writeHistoryFile(historyPath(threadId, terminalId), request.history).pipe( + Effect.tap(() => Effect.sync(() => request.history.spill(historyMemoryBytes))), + ), + ) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + cause, + }), + ), + ); + const { sessions } = yield* readManagerState; + releaseHistoryMemory( + [...sessions.values()].map((session) => session.history), + historyMemoryBudget, + MIN_HISTORY_MEMORY_BYTES, ); }), }); @@ -2203,28 +1959,55 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* flushPersist(threadId, terminalId); }); - const readHistoryTail = Effect.fn("terminal.readHistoryTail")(function* (filePath: string) { - const file = yield* fileSystem.open(filePath, { flag: "r" }); - const info = yield* file.stat; - const limit = BigInt(historyByteLimit); - const offset = info.size > limit ? info.size - limit : 0n; - yield* file.seek(offset, "start"); - const bytes = new Uint8Array(Number(info.size - offset)); - let length = 0; - while (length < bytes.length) { - const read = Number(yield* file.read(bytes.subarray(length))); - if (read === 0) break; - length += read; - } - let start = 0; - if (offset > 0n) { - // A tail read can start inside a UTF-8 code point. Skip its remaining bytes. - while (start < length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start += 1; - } - return { - history: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(start, length)), - fileBytes: Number(offset) + length, + const isContinuationByte = (byte: number | undefined) => + byte !== undefined && (byte & 0xc0) === 0x80; + const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true }); + + /** + * Reads a history file without holding it whole: sizes of the part that stays on disk, + * and the text of its newest part, which memory keeps. + */ + const loadHistoryFile = Effect.fn("terminal.loadHistoryFile")(function* (filePath: string) { + const size = Number((yield* fileSystem.stat(filePath)).size); + const scanStart = Math.max(0, size - historyByteLimit); + const tailStart = Math.max(scanStart, size - historyMemoryBytes); + const segments: Array<{ bytes: number; lineBreaks: number }> = []; + for (let from = scanStart; from < tailStart; from += HISTORY_FILE_BLOCK_BYTES) { + const block = yield* readFileRange( + filePath, + from, + Math.min(tailStart, from + HISTORY_FILE_BLOCK_BYTES), + ); + if (block.length === 0) break; + let lineBreaks = 0; + for (let index = block.indexOf(10); index !== -1; index = block.indexOf(10, index + 1)) { + lineBreaks += 1; + } + segments.push({ bytes: block.length, lineBreaks }); + } + const tail = yield* readFileRange(filePath, tailStart, size); + // The tail can start inside a code point; those bytes stay with the part on disk. + let skip = 0; + while (skip < tail.length && isContinuationByte(tail[skip])) skip += 1; + if (skip > 0) segments.push({ bytes: skip, lineBreaks: 0 }); + const text = utf8Decoder.decode(tail.subarray(skip)); + const history = BoundedTerminalHistory.restored( + historyLineLimit, + historyByteLimit, + scanStart, + segments, + text, + ); + // Invalid UTF-8 decodes to replacement characters of another size, so memory no longer + // matches the file's tail and the next write replaces the file. + const exact = Buffer.byteLength(text) === tail.length - skip; + history.persisted = { + generation: history.clearGeneration, + fileStart: 0, + end: history.endOffset, + ...(exact ? {} : { dirty: true }), }; + return history; }); const readHistory = Effect.fn("terminal.readHistory")(function* ( @@ -2243,36 +2026,25 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func )) ) continue; - const { history: raw, fileBytes } = yield* readHistoryTail(sourcePath).pipe( - Effect.scoped, + const history = yield* loadHistoryFile(sourcePath).pipe( Effect.mapError( (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }), ), ); - const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit); - // The file ends with the retained history; appends compact away any longer prefix. - history.persisted = { - generation: history.clearGeneration, - end: history.endOffset, - fileBytes, - }; if (migrating) { - const capped = history.value(); - yield* Effect.gen(function* () { - const temporaryPath = yield* fileSystem.makeTempFileScoped({ - directory: logsDir, - prefix: ".history-", - }); - yield* fileSystem.writeFileString(temporaryPath, capped); - yield* fileSystem.rename(temporaryPath, nextPath); - }).pipe( - Effect.scoped, - Effect.mapError( - (cause) => - new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }), - ), - ); - history.persisted = { ...history.persisted, fileBytes: Buffer.byteLength(capped) }; + // A rewrite copies the source's bytes into a file at the bounded path. + history.persisted = { ...history.persisted!, dirty: true }; + yield* historyFileLocks + .withLock( + toSessionKey(threadId, terminalId), + writeHistoryFile(nextPath, history, sourcePath), + ) + .pipe( + Effect.mapError( + (cause) => + new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }), + ), + ); yield* fileSystem.remove(sourcePath, { force: true }).pipe( Effect.catch((error) => Effect.logWarning("failed to remove legacy terminal history", { @@ -2283,11 +2055,66 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ), ); } + history.spill(historyMemoryBytes); return history; } return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit); }); + /** Output the server keeps between `from` and `to`, from memory and, before it, the file. */ + const readHistoryRange = Effect.fn("terminal.readHistoryRange")(function* ( + threadId: string, + terminalId: string, + history: BoundedTerminalHistory, + from: number, + to: number, + ) { + // Read memory first: releasing output to the file while reading only moves it on disk. + const memoryStart = history.memoryStart; + const memoryPart = history.memoryText(Math.max(from, memoryStart), to); + const persisted = history.persisted; + if (from >= memoryStart || persisted === null) { + return { + data: memoryPart, + from: Math.max(from, memoryStart), + to, + lineBreakBefore: history.lineBreakBefore(Math.max(from, memoryStart)) ?? false, + }; + } + const diskEnd = Math.min(to, memoryStart); + // One byte more in front tells whether the range starts a line. + const readFrom = Math.max(persisted.fileStart, from - 1); + const bytes = yield* historyFileLocks.withLock( + toSessionKey(threadId, terminalId), + Effect.suspend(() => { + const current = history.persisted ?? persisted; + return readFileRange( + historyPath(threadId, terminalId), + readFrom - current.fileStart, + diskEnd - current.fileStart, + ); + }), + ); + let start = from - readFrom; + const lineBreakBefore = start > 0 && bytes[start - 1] === 10; + while (start < bytes.length && isContinuationByte(bytes[start])) start += 1; + let stop = bytes.length; + if (to < memoryStart) { + // Cut before a code point the range ends inside. + let lead = stop - 1; + while (lead > start && isContinuationByte(bytes[lead])) lead -= 1; + const byte = bytes[lead] ?? 0; + const width = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1; + if (lead + width > stop) stop = lead; + } + return { + data: utf8Decoder.decode(bytes.subarray(start, stop)) + memoryPart, + from: readFrom + start, + to: to < memoryStart ? readFrom + stop : to, + lineBreakBefore, + }; + }); + const deleteHistory = Effect.fn("terminal.deleteHistory")(function* ( threadId: string, terminalId: string, @@ -2385,7 +2212,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func (session) => session.status !== "running", ); let inactiveBytes = inactiveSessions.reduce( - (total, session) => total + session.history.bytes, + (total, session) => total + session.history.memoryBytes, 0, ); if ( @@ -2417,7 +2244,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func sessions.delete(key); closedSessionKeys.add(key); retained -= 1; - inactiveBytes -= session.history.bytes; + inactiveBytes -= session.history.memoryBytes; } return [undefined, { ...state, sessions }] as const; @@ -2472,6 +2299,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId: session.terminalId, sequence: eventStamp.sequence, history: sanitized.visibleText.length > 0 ? session.history : null, + historyEnd: session.history.endOffset, data: nextEvent.data, } as const; } @@ -2521,6 +2349,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId: action.terminalId, sequence: action.sequence, data: action.data, + historyEnd: action.historyEnd, }); continue; } @@ -3071,21 +2900,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const existing = yield* getSession(input.threadId, terminalId); if (Option.isNone(existing)) { yield* flushPersist(input.threadId, terminalId); - const inherited = yield* readHistory(input.threadId, terminalId); - const inheritedText = inherited.value(); - const history = new BoundedTerminalHistory( - historyLineLimit, - neutralizeInheritedHistory(inheritedText, historyLineLimit, historyByteLimit), - historyByteLimit, - ); - // The file already holds the inherited text, so the reset suffix can be appended. - if (inherited.persisted !== null && history.value().startsWith(inheritedText)) { - history.persisted = { - generation: history.clearGeneration, - end: history.startOffset + inheritedText.length, - fileBytes: inherited.persisted.fileBytes, - }; - } + const history = yield* readHistory(input.threadId, terminalId); + neutralizeInheritedHistory(history); const cols = input.cols ?? DEFAULT_OPEN_COLS; const rows = input.rows ?? DEFAULT_OPEN_ROWS; const session: TerminalSessionState = { @@ -3715,13 +3531,63 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* closeIdle(input); }); - const historyPage: TerminalManager["Service"]["historyPage"] = Effect.fn("terminal.historyPage")( - function* (input) { - const session = yield* requireSession(input.threadId, input.terminalId); - const page = session.history.pageBefore(input.before, TERMINAL_HISTORY_PAGE_BYTES); - return { data: page.data, offset: page.offset, olderHistory: page.older }; - }, - ); + const historyPage: TerminalManager["Service"]["historyPage"] = (input) => + readHistoryPage(input).pipe( + Effect.catchTags({ + PlatformError: (cause) => + Effect.fail( + new TerminalHistoryError({ + operation: "read", + threadId: input.threadId, + terminalId: input.terminalId, + cause, + }), + ), + }), + ); + + const readHistoryPage = Effect.fn("terminal.historyPage")(function* ( + input: TerminalHistoryInput, + ) { + const session = yield* requireSession(input.threadId, input.terminalId); + const history = session.history; + const start = history.startOffset; + const end = history.endOffset; + if (input.after !== undefined) { + const from = Math.min(Math.max(input.after, start), end); + const range = yield* readHistoryRange( + input.threadId, + input.terminalId, + history, + from, + Math.min(end, from + TERMINAL_HISTORY_PAGE_BYTES), + ); + return { + data: range.data, + offset: range.from, + end: range.to, + olderHistory: range.from > start, + newerHistory: range.to < end, + }; + } + if (input.before === undefined) return newestHistoryPage(history); + const to = Math.min(Math.max(input.before, start), end); + const range = yield* readHistoryRange( + input.threadId, + input.terminalId, + history, + Math.max(start, to - TERMINAL_HISTORY_PAGE_BYTES), + to, + ); + const page = startPageAtLine(range.data, range.from, start, range.lineBreakBefore); + return { + data: page.data, + offset: page.offset, + end: to, + olderHistory: page.offset > start, + newerHistory: to < end, + }; + }); return TerminalManager.of({ open, diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 018288dd9b475..2f54e3de46c67 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -33,7 +33,7 @@ import { } from "@t3tools/contracts"; import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import * as Schema from "effect/Schema"; -import { AsyncResult } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; import { type PointerEvent as ReactPointerEvent, type ReactNode, @@ -162,11 +162,11 @@ function writeSystemMessage( export function writeTerminalOutputUpdate( terminal: Pick & - Partial>, + Partial>, update: TerminalOutputUpdate, ): void { - if (update.type === "reset" && update.prepended && terminal.prependAndWrite) { - terminal.prependAndWrite(update.data); + if (update.type === "reset" && update.anchor !== null && terminal.resetAndWriteAnchored) { + terminal.resetAndWriteAnchored(update.data, update.anchor); } else if (update.type === "reset") { terminal.resetAndWrite(update.data); } else if (update.type === "append") { @@ -182,7 +182,7 @@ export function synchronizeTerminalOutput( GhosttyTerminalSurface, "resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection" > & - Partial>, + Partial>, session: Pick, cursor: TerminalOutputCursor, ): TerminalOutputCursor { @@ -628,6 +628,11 @@ function TerminalSessionViewport({ // Attaching starts with the viewport, while the WASM surface is still loading; // the surface reads the session itself, so output chunks never re-render here. useAtomMount(terminalSessionAtom); + // Only whether the view shows older output re-renders; output chunks never do. + const detachedAtom = Atom.make((get) => get(terminalSessionAtom).output.detached !== null).pipe( + Atom.withLabel("web-terminal-session:detached"), + ); + const viewingOlderOutput = useAtomValue(detachedAtom); const readTerminalSession = useEffectEvent(() => appAtomRegistry.get(terminalSessionAtom)); const subscribeTerminalSession = useEffectEvent( (listener: (session: TerminalSessionState) => void) => @@ -640,6 +645,20 @@ function TerminalSessionViewport({ readTerminalSession().output, ); }); + const loadNewerOutput = useEffectEvent(() => { + void terminalEnvironment.loadNewerOutput( + appAtomRegistry, + { environmentId, threadId, terminalId }, + readTerminalSession().output, + ); + }); + const showLatestOutput = useEffectEvent(() => { + void terminalEnvironment.showLatestOutput( + appAtomRegistry, + { environmentId, threadId, terminalId }, + readTerminalSession().output, + ); + }); const writeTerminal = useEffectEvent((data: string) => runTerminalWrite({ environmentId, @@ -743,6 +762,7 @@ function TerminalSessionViewport({ validateLink: (text) => validateTerminalLink(text), onLinkHover: (text) => setLinkPath(text !== null && !isTerminalUrl(text) ? text : null), onScrollbackStart: () => loadOlderOutput(), + onScrollbackEnd: () => loadNewerOutput(), // Surface listeners start before WASM loading finishes and the terminal handler exists. onContextMenu: (event) => { if (terminalRef.current) void showTerminalContextMenu(event); @@ -953,7 +973,8 @@ function TerminalSessionViewport({ focusIfCurrent(requestId); return; case "scroll-to-bottom": - terminalRef.current?.scrollToBottom(); + if (readTerminalSession().output.detached !== null) showLatestOutput(); + else terminalRef.current?.scrollToBottom(); focusIfCurrent(requestId); return; } @@ -1226,11 +1247,20 @@ function TerminalSessionViewport({ }; }; return ( -
+
+
+ {viewingOlderOutput ? ( +
+ +
+ ) : null} +
); } diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index 9d00a3fc32467..b1f3ba975320e 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -320,7 +320,8 @@ describe("GhosttyTerminalCore snapshots", () => { const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR); writeTerminalOutputUpdate(core, initial); const reset = vi.spyOn(core, "resetAndWrite"); - const data = "line\r\n".repeat(8192); + // Long lines, so the byte budget binds before the line budget. + const data = `${"line".repeat(100)}\r\n`.repeat(128); const appends = Math.ceil((1.5 * DEFAULT_MAX_TERMINAL_BUFFER_BYTES) / data.length); for (let index = 0; index < appends; index += 1) state = append(state, data); diff --git a/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index e92e722fedd7a..554e2c2bfa28d 100644 --- a/apps/web/src/terminal/ghostty/core.ts +++ b/apps/web/src/terminal/ghostty/core.ts @@ -1,3 +1,4 @@ +import { TERMINAL_VIEW_SCROLLBACK_ROWS } from "@t3tools/contracts"; import { type GhosttyKeyboardLayoutMap, ghosttyConsumedMods, @@ -9,7 +10,7 @@ import { GhosttyRuntime, loadGhosttyRuntime } from "./runtime"; const GHOSTTY_SUCCESS = 0; const GHOSTTY_OUT_OF_SPACE = -3; -const MAX_SCROLLBACK_ROWS = 100_000; +const MAX_SCROLLBACK_ROWS = TERMINAL_VIEW_SCROLLBACK_ROWS; // wasm32 GhosttyTerminalSelectionFormatOptions layout at the pinned libghostty-vt revision. const SELECTION_FORMAT_OPTIONS_SIZE = 16; const PALETTE_BYTES = 256 * 3; diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts index c7e938524fa9d..27eae21d7428c 100644 --- a/apps/web/src/terminal/ghostty/surface.test.ts +++ b/apps/web/src/terminal/ghostty/surface.test.ts @@ -285,6 +285,34 @@ describe("GhosttyTerminalSurface visibility", () => { expect(surface.hasSelection()).toBe(false); }); + it("keeps the rows being read in place across older output, asking once per edge", async () => { + vi.stubGlobal("navigator", { platform: "Linux x86_64" }); + const harness = createHarness(); + const onScrollbackStart = vi.fn(); + const surface = await harness.create({ beforeKey: () => true, onScrollbackStart }); + const scrollbar = () => + (surface as unknown as { core: GhosttyTerminalCore }).core.scrollbarState()!; + const lines = (from: number, count: number) => + Array.from({ length: count }, (_, index) => `line ${from + index}\r\n`).join(""); + surface.resetAndWrite(lines(100, 60)); + const jumpToStart = () => key(surface, "Home", "Home", { ctrlKey: true, shiftKey: true }); + + jumpToStart(); + jumpToStart(); + expect(onScrollbackStart).toHaveBeenCalledTimes(1); + // A page that adds no rows leaves the view at the top without asking again. + surface.resetAndWriteAnchored(lines(100, 60), { split: 0, keep: "start" }); + jumpToStart(); + expect(onScrollbackStart).toHaveBeenCalledTimes(1); + + const older = lines(50, 50); + surface.resetAndWriteAnchored(older + lines(100, 60), { split: older.length, keep: "start" }); + // The first row shown is still the one the user was reading. + expect(scrollbar().offset).toBe(50); + jumpToStart(); + expect(onScrollbackStart).toHaveBeenCalledTimes(2); + }); + it("leaves modified history keys with alternate-screen applications", async () => { vi.stubGlobal("navigator", { platform: "Linux x86_64" }); const harness = createHarness(); diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index 44e096fff1698..86cd6922427c7 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -533,6 +533,8 @@ export interface GhosttyTerminalSurfaceOptions { readonly onContextMenu?: (event: MouseEvent) => void; /** The user scrolled up to the oldest row the view holds. */ readonly onScrollbackStart?: () => void; + /** The user scrolled down to the newest row the view holds. */ + readonly onScrollbackEnd?: () => void; } export class GhosttyTerminalSurface { @@ -571,6 +573,7 @@ export class GhosttyTerminalSurface { private forceFullRender = true; private scrollbarDirty = true; private scrollbarState: GhosttyScrollbar | null = null; + private scrollbackEdgeNotified: "start" | "end" | null = null; private scrollbarPointerId: number | null = null; private scrollbarPointerOffset = 0; private disposed = false; @@ -779,21 +782,41 @@ export class GhosttyTerminalSurface { } /** - * Replaces the contents with `data`, which only adds older output in front of what is - * shown, keeping the rows the user is reading in place. + * Replaces the contents with `data`, keeping the rows the user is reading in place: + * `data` holds the text shown so far starting (`start`) or ending (`end`) at `split`. */ - prependAndWrite(data: string): void { + resetAndWriteAnchored(data: string, anchor: { split: number; keep: "start" | "end" }): void { if (this.disposed) return; const before = this.core.scrollbarState(); - this.resetAndWrite(data); + const head = data.slice(0, anchor.split); + this.resetAndWrite(head); + const middle = this.core.scrollbarState(); + this.write(data.slice(anchor.split)); const after = this.core.scrollbarState(); - if (before === null || after === null) return; - const rowsBelow = before.total - before.len - before.offset; - if (rowsBelow > 0) this.scrollViewport(after.total - after.len - rowsBelow - after.offset); + if (before === null || middle === null || after === null) return; + // The split's row is the cursor's: the last screen row once the screen has filled, + // else at least one row per line break before it. + let lineBreaks = 0; + for (let index = head.indexOf("\n"); index !== -1; index = head.indexOf("\n", index + 1)) { + lineBreaks += 1; + } + const splitRow = + middle.total > middle.len ? middle.total - 1 : Math.min(middle.len - 1, lineBreaks); + const target = + anchor.keep === "start" + ? splitRow + before.offset + : splitRow - (before.total - 1 - before.offset); + const offset = Math.max(0, Math.min(target, after.total - after.len)); + this.moveViewport(offset - after.offset); + // Rows that arrived at an edge the user already reached do not ask for more until + // the user leaves that edge, so a page that adds nothing cannot chain more pages. + this.scrollbackEdgeNotified = + offset === 0 ? "start" : offset === after.total - after.len ? "end" : null; } resetAndWrite(data: string): void { if (this.disposed) return; + this.scrollbackEdgeNotified = null; this.cancelSynchronizedRenderTimer(); this.lastMouseMotionData = ""; this.core.resetAndWrite(data); @@ -1939,17 +1962,32 @@ export class GhosttyTerminalSurface { } private scrollViewport(deltaRows: number): void { - let delta = Math.trunc(deltaRows); + const requested = Math.trunc(deltaRows); + let delta = requested; const state = this.readScrollbarState(); if (state !== null) { const maxOffset = Math.max(0, state.total - state.len); const offset = Math.max(0, Math.min(state.offset + delta, maxOffset)); delta = offset - state.offset; this.scrollbarState = { ...state, offset }; + const reached = + requested < 0 && offset === 0 + ? "start" + : requested > 0 && offset === maxOffset + ? "end" + : null; + if (reached !== null && reached !== this.scrollbackEdgeNotified) { + this.scrollbackEdgeNotified = reached; + if (reached === "start") this.options.onScrollbackStart?.(); + else this.options.onScrollbackEnd?.(); + } else if (reached === null && delta !== 0) { + this.scrollbackEdgeNotified = null; + } } - if (delta < 0 && state !== null && state.offset + delta <= 0) { - this.options.onScrollbackStart?.(); - } + this.moveViewport(delta); + } + + private moveViewport(delta: number): void { if (delta === 0) return; this.core.scroll(delta); this.forceFullRender = true; diff --git a/docs/user/terminal.md b/docs/user/terminal.md index cec71e35f79b1..ae1e5cfc70e33 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -7,17 +7,19 @@ truncated. To change the limits, set `T3CODE_TERMINAL_HISTORY_MAX_LINES` or `T3CODE_TERMINAL_HISTORY_MAX_BYTES` in the environment that starts the server. When you open or reconnect to a terminal, it shows the most recent output first. -On web and desktop, scrolling to the top loads earlier output. On iPhone, iPad, -and Android, choose **Load earlier output** in the terminal menu. Each client -holds up to 8 MiB or 100,000 rows of a terminal's output; earlier output stays -on the server. +On web and desktop, scrolling to the top loads earlier output, and you can keep +going back to the oldest output the server keeps. A terminal view holds about +4 MiB of output at a time, so when you read far back, the newest output is set +aside and a **Jump to latest** button appears; scrolling down loads later +output again. On iPhone, iPad, and Android, use **Load earlier output**, **Load +later output**, and **Jump to latest output** in the terminal menu. On web and desktop, use Shift+PageUp and Shift+PageDown to read scrollback without leaving terminal input. Ctrl+Shift+Home and Ctrl+Shift+End jump to the start and latest output; use Cmd instead of Ctrl on macOS. Full-screen terminal programs keep these navigation keys. -To copy all output the client holds, choose Select all in the terminal's context menu, +To copy all output the view holds, choose Select all in the terminal's context menu, then copy. Cmd+A on macOS and Ctrl+Shift+A elsewhere select the same output. Ctrl+A still moves to the beginning of shell input on Windows and Linux. Jump to latest in the context menu returns to the current output. diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index 5afa09f22c4c1..0b4492197f5e4 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -2,7 +2,6 @@ import { type EnvironmentId, type TerminalAttachInput, type TerminalAttachStreamEvent, - type TerminalHistoryPage, type TerminalCloseInput, type TerminalOpenInput, type TerminalResizeInput, @@ -31,14 +30,13 @@ import { EMPTY_TERMINAL_BUFFER_STATE, nextTerminalAttachSeedState, type TerminalBufferState, - type TerminalOlderHistoryEvent, + type TerminalHistoryPageEvent, } from "./terminalSession.ts"; import { canLoadOlderTerminalOutput, terminalOutputText, type TerminalOutputState, } from "./terminalOutput.ts"; -import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts"; export function createTerminalEnvironmentAtoms( runtime: Atom.AtomRuntime, @@ -60,29 +58,29 @@ export function createTerminalEnvironmentAtoms( readonly input: { readonly threadId: string; readonly terminalId?: string | undefined }; }) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]); const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey }; - // Older pages are requested beside the stream and applied in order with its events. - const olderHistoryListeners = new Map void>>(); - const olderHistoryKey = (input: { readonly threadId: string; readonly terminalId: string }) => + // Pages are requested beside the stream and applied in order with its events. + const historyListeners = new Map void>>(); + const historyKey = (input: { readonly threadId: string; readonly terminalId: string }) => JSON.stringify([input.threadId, input.terminalId]); - const withOlderHistory = ( + const withHistoryPages = ( input: { readonly threadId: string; readonly terminalId: string }, stream: Stream.Stream, ) => stream.pipe( Stream.merge( - Stream.callback((queue) => + Stream.callback((queue) => Effect.acquireRelease( Effect.sync(() => { - const key = olderHistoryKey(input); - const listener = (page: TerminalHistoryPage) => { - Queue.offerUnsafe(queue, { type: "olderHistory", page }); + const key = historyKey(input); + const listener = (event: TerminalHistoryPageEvent) => { + Queue.offerUnsafe(queue, event); }; - let listeners = olderHistoryListeners.get(key); - if (!listeners) olderHistoryListeners.set(key, (listeners = new Set())); + let listeners = historyListeners.get(key); + if (!listeners) historyListeners.set(key, (listeners = new Set())); listeners.add(listener); return () => { listeners.delete(listener); - if (listeners.size === 0) olderHistoryListeners.delete(key); + if (listeners.size === 0) historyListeners.delete(key); }; }), (release) => Effect.sync(release), @@ -92,19 +90,19 @@ export function createTerminalEnvironmentAtoms( ), Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent), ); - const pendingOlderHistory = new Set(); + const pendingHistory = new Set(); const atoms = { observe: createEnvironmentSubscriptionAtomFamily(runtime, { label: "environment-data:terminal:observe", subscribe: (input: EnvironmentRpcInput) => - Stream.suspend(() => withOlderHistory(input, subscribe(WS_METHODS.terminalObserve, input))), + Stream.suspend(() => withHistoryPages(input, subscribe(WS_METHODS.terminalObserve, input))), }), attach: createEnvironmentSubscriptionAtomFamily(runtime, { label: "environment-data:terminal:attach", subscribe: (input: EnvironmentRpcInput) => { // Retry an unanswered first attach unchanged so it can still open the shell. let replied = false; - return withOlderHistory( + return withHistoryPages( input, subscribeDynamic(WS_METHODS.terminalAttach, () => Effect.sync(() => (replied ? { ...input, resume: true } : input)), @@ -160,56 +158,77 @@ export function createTerminalEnvironmentAtoms( tag: WS_METHODS.terminalHistory, onSuccess: (target, _registry, page) => Effect.sync(() => { - for (const listener of olderHistoryListeners.get(olderHistoryKey(target.input)) ?? []) { - listener(page); + const type = + target.input.before !== undefined + ? "olderHistory" + : target.input.after !== undefined + ? "newerHistory" + : "latestHistory"; + for (const listener of historyListeners.get(historyKey(target.input)) ?? []) { + listener({ type, page }); } }), }), }; - /** - * Fetches the page of server output just before what `output` holds, when there is one - * and it fits. The page reaches the terminal's attach or observe state as it lands. - */ - const loadOlderOutput = async ( + type Target = { + readonly environmentId: EnvironmentId; + readonly threadId: string; + readonly terminalId: string; + }; + /** Reads one page; the terminal's attach or observe state applies it as it lands. */ + const loadPage = async ( registry: AtomRegistry.AtomRegistry, - target: { - readonly environmentId: EnvironmentId; - readonly threadId: string; - readonly terminalId: string; - }, - output: TerminalOutputState, + target: Target, + position: { readonly before: number } | { readonly after: number } | null, ): Promise => { - if ( - output.historyOffset === null || - !canLoadOlderTerminalOutput(output, DEFAULT_MAX_TERMINAL_BUFFER_BYTES) - ) { - return; - } const key = JSON.stringify([target.environmentId, target.threadId, target.terminalId]); - if (pendingOlderHistory.has(key)) return; - pendingOlderHistory.add(key); + if (pendingHistory.has(key)) return; + pendingHistory.add(key); try { await runAtomCommand( registry, atoms.history, { environmentId: target.environmentId, - input: { - threadId: target.threadId, - terminalId: target.terminalId, - before: output.historyOffset, - }, + input: { threadId: target.threadId, terminalId: target.terminalId, ...position }, }, // An older server lacks the method; the view keeps what it has. { reportFailure: false }, ); } finally { - pendingOlderHistory.delete(key); + pendingHistory.delete(key); } }; + /** Reads the page before what `output` holds, when the server keeps more. */ + const loadOlderOutput = ( + registry: AtomRegistry.AtomRegistry, + target: Target, + output: TerminalOutputState, + ): Promise => + output.historyOffset === null || !canLoadOlderTerminalOutput(output) + ? Promise.resolve() + : loadPage(registry, target, { before: output.historyOffset }); + /** Reads the page after what a window detached from the live output holds. */ + const loadNewerOutput = ( + registry: AtomRegistry.AtomRegistry, + target: Target, + output: TerminalOutputState, + ): Promise => + output.detached === null + ? Promise.resolve() + : loadPage(registry, target, { after: output.detached.end }); + /** Shows the newest output again and follows the live output. */ + const showLatestOutput = ( + registry: AtomRegistry.AtomRegistry, + target: Target, + output: TerminalOutputState, + ): Promise => + output.detached === null ? Promise.resolve() : loadPage(registry, target, null); return { ...atoms, loadOlderOutput, + loadNewerOutput, + showLatestOutput, createSession: (options: TerminalSessionOptions) => createTerminalSession(atoms, options), }; } diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts index 0625db2283d2a..2814bfcc3f385 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -1,32 +1,48 @@ +import { MAX_TERMINAL_BUFFER_LINES, TERMINAL_HISTORY_PAGE_BYTES } from "@t3tools/contracts"; + export interface TerminalOutputChunk { readonly startOffset: number; readonly data: string; readonly byteLength: number; + readonly lineBreaks: number; + /** The server's history offset where this chunk ends, when known. */ + readonly serverEnd: number | null; + /** Ends inside output whose end a later chunk knows. */ + readonly pendingEnd: boolean; + /** The server's own text, so its bytes map to history offsets. */ + readonly exact: boolean; +} + +/** The held output ends before the live output, after older output was read in. */ +export interface TerminalDetachedWindow { + /** The server offset where the held output ends. */ + readonly end: number; + /** Live output that arrived meanwhile, with the server offset where each ends. */ + readonly buffered: ReadonlyArray<{ readonly data: string; readonly end: number }>; + /** The server offset where `buffered` starts. */ + readonly bufferedFrom: number; +} + +/** How a reset relates to what a reader showed, so it can keep the reader's place. */ +export interface TerminalOutputAnchor { + /** Where, in the reset's text, the text the reader had starts (`start`) or ends (`end`). */ + readonly split: number; + readonly keep: "start" | "end"; } export interface TerminalOutputState { readonly generation: number; readonly chunks: ReadonlyArray; readonly retainedBytes: number; + readonly retainedLines: number; readonly resetVersion: number; readonly nextOffset: number; - /** - * The server's offset of the first retained character, for paging in older output. - * Null when unknown: an older server, or live output pushed out every server page. - */ + /** The server offset where the held output starts, or null when unknown. */ readonly historyOffset: number | null; - /** How many leading characters are server history, whose offsets are known. */ - readonly historyLength: number; /** The server keeps output before `historyOffset`. */ readonly olderHistory: boolean; - /** The last reset only added older output in front of what was there. */ - readonly prepended: boolean; -} - -/** Where a server snapshot or page of history starts. */ -export interface TerminalHistoryAnchor { - readonly offset: number; - readonly older: boolean; + readonly detached: TerminalDetachedWindow | null; + readonly anchor: (TerminalOutputAnchor & { readonly resetVersion: number }) | null; } export interface TerminalOutputCursor { @@ -50,8 +66,8 @@ export type TerminalOutputUpdate = readonly type: "reset"; readonly data: string; readonly cursor: TerminalOutputCursor; - /** Only older output was added before what the reader had, so it can keep its place. */ - readonly prepended: boolean; + /** Set when the reader's last text is part of this one, so it can keep its place. */ + readonly anchor: TerminalOutputAnchor | null; } | { readonly type: "append"; @@ -59,9 +75,20 @@ export type TerminalOutputUpdate = readonly data: string; }; +/** A page of server output, as `terminal.history` returns it. */ +export interface TerminalHistoryPageInput { + readonly data: string; + readonly offset: number; + readonly end: number; + readonly olderHistory: boolean; + readonly newerHistory: boolean; +} + const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024; // Enough 16 KiB chunks for the default buffer; compaction keeps chunks near that size. const MAX_TERMINAL_OUTPUT_CHUNKS = 2_048; +// Live output kept aside while the held output ends before it. +const MAX_DETACHED_BUFFER_BYTES = TERMINAL_HISTORY_PAGE_BYTES; const textEncoder = new TextEncoder(); // A BOM at a retained chunk boundary is terminal data, not an encoding marker. const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); @@ -70,100 +97,98 @@ export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze({ generation: 0, chunks: Object.freeze([]), retainedBytes: 0, + retainedLines: 0, resetVersion: 0, nextOffset: 0, historyOffset: null, - historyLength: 0, olderHistory: false, - prepended: false, + detached: null, + anchor: null, }); -interface Utf8Chunk { - readonly data: string; - readonly byteLength: number; -} - -function splitStringByUtf8Bytes(data: string, maxBytes: number): ReadonlyArray { - if (data.length === 0) return []; +const utf8Length = (data: string) => textEncoder.encode(data).byteLength; - const encoded = textEncoder.encode(data); - if (encoded.byteLength <= maxBytes) { - return [{ data, byteLength: encoded.byteLength }]; +const countLineBreaks = (data: string) => { + let lineBreaks = 0; + for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { + lineBreaks += 1; } + return lineBreaks; +}; + +const utf8Width = (codePoint: number) => + codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; - const chunks: Utf8Chunk[] = []; +function splitStringByUtf8Bytes( + data: string, + maxBytes: number, +): ReadonlyArray<{ readonly data: string; readonly byteLength: number }> { + if (data.length === 0) return []; + const encoded = textEncoder.encode(data); + if (encoded.byteLength <= maxBytes) return [{ data, byteLength: encoded.byteLength }]; + const chunks: Array<{ data: string; byteLength: number }> = []; let offset = 0; while (offset < encoded.byteLength) { let end = Math.min(offset + maxBytes, encoded.byteLength); - while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) { - end -= 1; - } - // A degenerate budget smaller than one code point still has to advance: - // include the whole code point rather than looping forever. + while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) end -= 1; + // A degenerate budget smaller than one code point still has to advance. if (end === offset) { end = Math.min(offset + maxBytes, encoded.byteLength); - while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) { - end += 1; - } + while (end < encoded.byteLength && ((encoded[end] ?? 0) & 0xc0) === 0x80) end += 1; } const bytes = encoded.subarray(offset, end); chunks.push({ data: textDecoder.decode(bytes), byteLength: bytes.byteLength }); offset = end; } - return chunks; } -function trimBufferToBytes(buffer: string, maxBufferBytes: number): string { - if (maxBufferBytes <= 0) { - return ""; - } - - const encoded = textEncoder.encode(buffer); - if (encoded.byteLength <= maxBufferBytes) { - return buffer; - } - - let start = encoded.byteLength - maxBufferBytes; - while (start < encoded.length) { - const byte = encoded[start]; - if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000) { - break; - } - start += 1; - } - - return textDecoder.decode(encoded.subarray(start)); -} - -function splitOutputChunks( +/** + * Chunks for `data`, numbered from `firstOffset`. Exact text gets the server offset at + * every chunk end; live output only at its last one. + */ +function makeChunks( data: string, firstOffset: number, + source: { readonly exact: boolean; readonly serverEnd: number | null }, maxChunkBytes = DEFAULT_TERMINAL_CHUNK_BYTES, -): { - readonly chunks: ReadonlyArray; - readonly nextOffset: number; - readonly byteLength: number; -} { +): ReadonlyArray { const split = splitStringByUtf8Bytes(data, maxChunkBytes); - let byteLength = 0; - let nextOffset = firstOffset; - const chunks = split.map((chunk) => { - byteLength += chunk.byteLength; - const startOffset = nextOffset; - nextOffset += chunk.data.length; - return { + const totalBytes = split.reduce((total, chunk) => total + chunk.byteLength, 0); + let startOffset = firstOffset; + let consumed = 0; + return split.map((chunk, index) => { + consumed += chunk.byteLength; + const last = index === split.length - 1; + const serverEnd = + source.serverEnd === null + ? null + : last + ? source.serverEnd + : source.exact + ? source.serverEnd - totalBytes + consumed + : null; + const made: TerminalOutputChunk = { startOffset, data: chunk.data, byteLength: chunk.byteLength, + lineBreaks: countLineBreaks(chunk.data), + serverEnd, + pendingEnd: serverEnd === null && source.serverEnd !== null, + exact: source.exact, }; + startOffset += chunk.data.length; + return made; }); +} - return { - chunks, - nextOffset, - byteLength, - }; +function renumber(chunks: ReadonlyArray, firstOffset = 0) { + let startOffset = firstOffset; + return chunks.map((chunk) => { + const renumbered = { ...chunk, startOffset }; + startOffset += chunk.data.length; + return renumbered; + }); } function compactRetainedChunks(chunks: ReadonlyArray) { @@ -179,6 +204,10 @@ function compactRetainedChunks(chunks: ReadonlyArray) { startOffset: previous.startOffset, data: `${previous.data}${chunk.data}`, byteLength: previous.byteLength + chunk.byteLength, + lineBreaks: previous.lineBreaks + chunk.lineBreaks, + serverEnd: chunk.serverEnd, + pendingEnd: chunk.pendingEnd, + exact: previous.exact && chunk.exact, }; } else { compacted.push(chunk); @@ -187,185 +216,348 @@ function compactRetainedChunks(chunks: ReadonlyArray) { return compacted; } -function trimOutputChunkStart( - chunk: TerminalOutputChunk, - bytesToDrop: number, -): TerminalOutputChunk { +/** Drops leading characters of `chunk` until at least `bytes` bytes or `lines` lines are gone. */ +function trimChunkStart(chunk: TerminalOutputChunk, bytes: number, lines: number) { let offset = 0; let droppedBytes = 0; - while (droppedBytes < bytesToDrop && offset < chunk.data.length) { - const codepoint = chunk.data.codePointAt(offset)!; - droppedBytes += codepoint <= 0x7f ? 1 : codepoint <= 0x7ff ? 2 : codepoint <= 0xffff ? 3 : 4; - offset += codepoint <= 0xffff ? 1 : 2; + let droppedLines = 0; + while ((droppedBytes < bytes || droppedLines < lines) && offset < chunk.data.length) { + const codePoint = chunk.data.codePointAt(offset)!; + droppedBytes += utf8Width(codePoint); + offset += codePoint <= 0xffff ? 1 : 2; + if (codePoint === 10) droppedLines += 1; + } + return { + chunk: { + ...chunk, + startOffset: chunk.startOffset + offset, + data: chunk.data.slice(offset), + byteLength: chunk.byteLength - droppedBytes, + lineBreaks: chunk.lineBreaks - droppedLines, + }, + droppedBytes, + }; +} + +interface Window { + chunks: TerminalOutputChunk[]; + bytes: number; + lines: number; + historyOffset: number | null; + dropped: boolean; +} + +/** + * Drops the oldest output until the window fits. Output whose server offsets are known + * goes a chunk at a time (live output) or exactly (server text), so the window's start + * stays a known offset older output can be read before. + */ +function trimFront(window: Window, maxBytes: number, maxLines: number): void { + while (window.chunks.length > 0 && (window.bytes > maxBytes || window.lines > maxLines)) { + const first = window.chunks[0]!; + const bytesOver = window.bytes - maxBytes; + const linesOver = window.lines - maxLines; + window.dropped = true; + const whole = first.byteLength <= bytesOver || first.lineBreaks <= linesOver - 1; + if (!whole && (first.exact || (first.serverEnd === null && !first.pendingEnd))) { + const trimmed = trimChunkStart(first, Math.max(0, bytesOver), Math.max(0, linesOver)); + window.bytes -= trimmed.droppedBytes; + window.lines -= first.lineBreaks - trimmed.chunk.lineBreaks; + window.historyOffset = + first.exact && window.historyOffset !== null + ? window.historyOffset + trimmed.droppedBytes + : null; + if (trimmed.chunk.data.length > 0) { + window.chunks[0] = trimmed.chunk; + continue; + } + window.chunks.shift(); + continue; + } + window.chunks.shift(); + window.bytes -= first.byteLength; + window.lines -= first.lineBreaks; + window.historyOffset = + first.serverEnd ?? + (first.exact && window.historyOffset !== null + ? window.historyOffset + first.byteLength + : null); } +} + +function windowOf(state: TerminalOutputState, chunks: ReadonlyArray): Window { return { - ...chunk, - startOffset: chunk.startOffset + offset, - data: chunk.data.slice(offset), - byteLength: chunk.byteLength - droppedBytes, + chunks: [...chunks], + bytes: chunks.reduce((total, chunk) => total + chunk.byteLength, 0), + lines: chunks.reduce((total, chunk) => total + chunk.lineBreaks, 0), + historyOffset: state.historyOffset, + dropped: false, }; } +function fromWindow( + current: TerminalOutputState, + window: Window, + changes: Partial, +): TerminalOutputState { + let chunks = window.chunks; + if (chunks.length > MAX_TERMINAL_OUTPUT_CHUNKS) chunks = compactRetainedChunks(chunks); + const last = chunks.at(-1); + return { + ...current, + chunks, + retainedBytes: window.bytes, + retainedLines: window.lines, + historyOffset: window.historyOffset, + olderHistory: window.historyOffset !== null && (current.olderHistory || window.dropped), + nextOffset: last === undefined ? current.nextOffset : last.startOffset + last.data.length, + ...changes, + }; +} + +/** Live output. While the window is detached it waits aside, so it can follow the window. */ function appendOutput( current: TerminalOutputState, data: string, maxBufferBytes: number, + serverEnd?: number, + maxLines = MAX_TERMINAL_BUFFER_LINES, ): TerminalOutputState { if (data.length === 0) return current; + const detached = current.detached; + if (detached !== null && serverEnd !== undefined) { + const buffered = [...detached.buffered, { data, end: serverEnd }]; + let bufferedFrom = detached.bufferedFrom; + let bytes = buffered.reduce((total, entry) => total + entry.data.length, 0); + while (bytes > MAX_DETACHED_BUFFER_BYTES && buffered.length > 1) { + const dropped = buffered.shift()!; + bytes -= dropped.data.length; + bufferedFrom = dropped.end; + } + return { ...current, detached: { ...detached, buffered, bufferedFrom } }; + } if (maxBufferBytes <= 0) { return { ...current, chunks: [], retainedBytes: 0, + retainedLines: 0, resetVersion: current.resetVersion + 1, nextOffset: current.nextOffset + data.length, historyOffset: null, - historyLength: 0, olderHistory: false, - prepended: false, + detached: null, + anchor: null, }; } - const appended = splitOutputChunks( - data, - current.nextOffset, - Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), - ); - - const chunks = [...current.chunks, ...appended.chunks]; - let retainedBytes = current.retainedBytes + appended.byteLength; - let firstRetainedIndex = 0; - while (retainedBytes > maxBufferBytes && firstRetainedIndex < chunks.length) { - const first = chunks[firstRetainedIndex]!; - const bytesToDrop = retainedBytes - maxBufferBytes; - if (bytesToDrop < first.byteLength) { - const trimmed = trimOutputChunkStart(first, bytesToDrop); - retainedBytes -= first.byteLength - trimmed.byteLength; - if (trimmed.byteLength > 0) { - chunks[firstRetainedIndex] = trimmed; - } else { - firstRetainedIndex += 1; - } - break; - } - retainedBytes -= first.byteLength; - firstRetainedIndex += 1; - } - - let retainedChunks = firstRetainedIndex === 0 ? chunks : chunks.slice(firstRetainedIndex); - if (retainedChunks.length > MAX_TERMINAL_OUTPUT_CHUNKS) { - retainedChunks = compactRetainedChunks(retainedChunks); - const excessChunks = retainedChunks.length - MAX_TERMINAL_OUTPUT_CHUNKS; - if (excessChunks > 0) { - for (const chunk of retainedChunks.slice(0, excessChunks)) { - retainedBytes -= chunk.byteLength; - } - retainedChunks = retainedChunks.slice(excessChunks); - } - } - - const dropped = - (retainedChunks[0]?.startOffset ?? appended.nextOffset) - - (current.chunks[0]?.startOffset ?? current.nextOffset); - return { - ...current, - chunks: retainedChunks, - retainedBytes, - nextOffset: appended.nextOffset, - ...dropHistory(current, dropped), - }; -} - -function dropHistory( - current: TerminalOutputState, - dropped: number, -): Pick { - if (dropped === 0) { - const { historyOffset, historyLength, olderHistory } = current; - return { historyOffset, historyLength, olderHistory }; - } - // Live output differs from what the server keeps, so offsets end with its history. - if (current.historyOffset === null || dropped > current.historyLength) { - return { historyOffset: null, historyLength: 0, olderHistory: false }; - } - return { - historyOffset: current.historyOffset + dropped, - historyLength: current.historyLength - dropped, - olderHistory: true, - }; + const window = windowOf(current, [ + ...current.chunks, + ...makeChunks( + data, + current.nextOffset, + { exact: false, serverEnd: serverEnd ?? null }, + Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), + ), + ]); + trimFront(window, maxBufferBytes, maxLines); + return fromWindow(current, window, { + nextOffset: current.nextOffset + data.length, + }); } +/** Replaces the output, as a snapshot, clear, or restart does. */ function resetOutput( current: TerminalOutputState, data: string, maxBufferBytes: number, - history?: TerminalHistoryAnchor, + history?: { readonly offset: number; readonly end: number; readonly older: boolean }, + maxLines = MAX_TERMINAL_BUFFER_LINES, ): TerminalOutputState { - const retained = trimBufferToBytes(data, maxBufferBytes); - const reset = splitOutputChunks( - retained, - 0, - Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), - ); - const trimmed = data.length - retained.length; + const window: Window = { + chunks: [ + ...makeChunks( + data, + 0, + history === undefined + ? { exact: false, serverEnd: null } + : { exact: true, serverEnd: history.end }, + Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), + ), + ], + bytes: utf8Length(data), + lines: countLineBreaks(data), + historyOffset: history?.offset ?? null, + dropped: false, + }; + if (maxBufferBytes <= 0) { + window.chunks = []; + window.bytes = 0; + window.lines = 0; + } + trimFront(window, Math.max(0, maxBufferBytes), maxLines); return { - generation: current.generation, - chunks: reset.chunks, - retainedBytes: reset.byteLength, + ...fromWindow({ ...current, olderHistory: history?.older ?? false }, window, {}), resetVersion: current.resetVersion + 1, - nextOffset: reset.nextOffset, - historyOffset: history === undefined ? null : history.offset + trimmed, - historyLength: history === undefined ? 0 : retained.length, - olderHistory: history !== undefined && (history.older || trimmed > 0), - prepended: false, + detached: null, + anchor: null, }; } -/** Whether the server keeps older output that fits in front of what is retained. */ -export function canLoadOlderTerminalOutput( - output: TerminalOutputState, - maxBufferBytes: number, -): boolean { - return ( - output.olderHistory && output.historyOffset !== null && output.retainedBytes < maxBufferBytes - ); +/** Where the held output ends on the server, when known. */ +function windowEnd(state: TerminalOutputState): number | null { + if (state.detached !== null) return state.detached.end; + return state.chunks.at(-1)?.serverEnd ?? null; +} + +/** Whether older server output can be read in front of what is held. */ +export function canLoadOlderTerminalOutput(output: TerminalOutputState): boolean { + return output.olderHistory && output.historyOffset !== null && windowEnd(output) !== null; +} + +/** Whether the held output ends before the live output, so newer output can be read in. */ +export function canLoadNewerTerminalOutput(output: TerminalOutputState): boolean { + return output.detached !== null; } /** - * Puts a page of older server output in front of the retained output, keeping only what - * fits. A page that does not end where the retained history starts is stale and ignored. + * Puts a page of older output in front of what is held. Past the budget the newest output + * goes, and the window detaches from the live output until newer pages bring it back. + * A page that does not end where the held output starts is stale and ignored. */ function prependOutput( current: TerminalOutputState, - page: { readonly data: string; readonly offset: number; readonly olderHistory: boolean }, + page: TerminalHistoryPageInput, maxBufferBytes: number, + maxLines = MAX_TERMINAL_BUFFER_LINES, ): TerminalOutputState { - if (current.historyOffset === null || page.offset + page.data.length !== current.historyOffset) { + const end = windowEnd(current); + if (current.historyOffset === null || page.end !== current.historyOffset || end === null) { return current; } - const fitted = trimBufferToBytes(page.data, maxBufferBytes - current.retainedBytes); - const offset = page.offset + page.data.length - fitted.length; - const olderHistory = page.olderHistory || offset > page.offset; - if (fitted.length === 0) { - return olderHistory === current.olderHistory ? current : { ...current, olderHistory }; + if (page.data.length === 0) { + return page.olderHistory === current.olderHistory + ? current + : { ...current, olderHistory: page.olderHistory }; } - const reset = splitOutputChunks( - fitted + terminalOutputText(current), - 0, - Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), - ); + const added = makeChunks(page.data, 0, { exact: true, serverEnd: page.end }); + const chunks = renumber([...added, ...current.chunks]); + let bytes = current.retainedBytes + utf8Length(page.data); + let lines = current.retainedLines + countLineBreaks(page.data); + // Drop the newest output, keeping the end at a known offset, until the window fits. + let newEnd = end; + let droppedNewest = false; + while (chunks.length > added.length && (bytes > maxBufferBytes || lines > maxLines)) { + const last = chunks.pop()!; + bytes -= last.byteLength; + lines -= last.lineBreaks; + droppedNewest = true; + while (chunks.length > added.length && chunks.at(-1)!.serverEnd === null) { + const unknown = chunks.pop()!; + bytes -= unknown.byteLength; + lines -= unknown.lineBreaks; + } + newEnd = chunks.at(-1)!.serverEnd!; + } + const window: Window = { chunks, bytes, lines, historyOffset: page.offset, dropped: false }; + // A page larger than the whole budget keeps its newest part. + trimFront(window, maxBufferBytes, maxLines); + const split = + added.reduce((total, chunk) => total + chunk.data.length, 0) - + (window.chunks[0]?.startOffset ?? 0); + const resetVersion = current.resetVersion + 1; + const detached = + current.detached !== null + ? { ...current.detached, end: newEnd } + : droppedNewest + ? { end: newEnd, buffered: [], bufferedFrom: end } + : null; return { - generation: current.generation, - chunks: reset.chunks, - retainedBytes: reset.byteLength, - resetVersion: current.resetVersion + 1, - nextOffset: reset.nextOffset, - historyOffset: offset, - historyLength: current.historyLength + fitted.length, - olderHistory, - prepended: true, + ...fromWindow( + { ...current, olderHistory: page.olderHistory }, + { ...window, chunks: renumber(window.chunks) }, + {}, + ), + olderHistory: page.olderHistory || window.dropped, + resetVersion, + detached, + anchor: { resetVersion, split: Math.max(0, split), keep: "start" }, }; } +/** + * Appends a page of newer output to a detached window, dropping the oldest output past the + * budget. A page that reached the server's end brings the window back to the live output. + */ +function appendNewerOutput( + current: TerminalOutputState, + page: TerminalHistoryPageInput, + maxBufferBytes: number, + maxLines = MAX_TERMINAL_BUFFER_LINES, +): TerminalOutputState { + const detached = current.detached; + if (detached === null || page.offset !== detached.end) return current; + const pageChunks = makeChunks(page.data, current.nextOffset, { + exact: true, + serverEnd: page.end, + }); + let nextOffset = current.nextOffset + page.data.length; + const appended = [...pageChunks]; + let stillDetached: TerminalDetachedWindow | null = { ...detached, end: page.end }; + if (!page.newerHistory && detached.bufferedFrom <= page.end) { + for (const entry of detached.buffered) { + if (entry.end <= page.end) continue; + const chunks = makeChunks(entry.data, nextOffset, { exact: false, serverEnd: entry.end }); + appended.push(...chunks); + nextOffset += entry.data.length; + } + stillDetached = null; + } + const window = windowOf(current, [...current.chunks, ...appended]); + trimFront(window, maxBufferBytes, maxLines); + const dropped = window.chunks[0]?.startOffset ?? nextOffset; + const firstBefore = current.chunks[0]?.startOffset ?? current.nextOffset; + if (dropped === firstBefore) { + // Nothing was dropped, so readers append. + return fromWindow(current, window, { nextOffset, detached: stillDetached }); + } + const resetVersion = current.resetVersion + 1; + return { + ...fromWindow(current, { ...window, chunks: renumber(window.chunks) }, {}), + nextOffset: nextOffset - dropped, + resetVersion, + detached: stillDetached, + anchor: { resetVersion, split: current.nextOffset - dropped, keep: "end" }, + }; +} + +/** Replaces a detached window with the newest page, and follows the live output again. */ +function showLatestOutput( + current: TerminalOutputState, + page: TerminalHistoryPageInput, + maxBufferBytes: number, + maxLines = MAX_TERMINAL_BUFFER_LINES, +): TerminalOutputState { + const detached = current.detached; + if (detached === null) return current; + const reset = resetOutput( + current, + page.data, + maxBufferBytes, + { offset: page.offset, end: page.end, older: page.olderHistory }, + maxLines, + ); + if (page.newerHistory || detached.bufferedFrom > page.end) { + return { ...reset, detached: { ...detached, end: page.end } }; + } + return detached.buffered.reduce( + (state, entry) => + entry.end <= page.end + ? state + : appendOutput(state, entry.data, maxBufferBytes, entry.end, maxLines), + reset, + ); +} + export function terminalOutputText(output: TerminalOutputState): string { return output.chunks.map((chunk) => chunk.data).join(""); } @@ -385,14 +577,19 @@ export function readTerminalOutputUpdate( cursor.resetVersion !== output.resetVersion || cursor.offset < (firstChunk?.startOffset ?? output.nextOffset) ) { + const anchor = output.anchor; return { type: "reset", data: terminalOutputText(output), cursor: nextCursor, - prepended: - output.prepended && + // Only a reader that had everything before this reset can keep its place. + anchor: + anchor !== null && + anchor.resetVersion === output.resetVersion && cursor.generation === output.generation && - cursor.resetVersion === output.resetVersion - 1, + cursor.resetVersion === output.resetVersion - 1 + ? { split: anchor.split, keep: anchor.keep } + : null, }; } @@ -416,4 +613,4 @@ export function readTerminalOutputUpdate( }; } -export { appendOutput, prependOutput, resetOutput }; +export { appendNewerOutput, appendOutput, prependOutput, resetOutput, showLatestOutput }; diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index dc254eebc4c08..9e9a7a1cb0040 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -5,6 +5,7 @@ import { EnvironmentId, TerminalSessionSnapshot, ThreadId } from "@t3tools/contr import { applyTerminalAttachStreamEvent, applyTerminalMetadataStreamEvent, + canLoadNewerTerminalOutput, canLoadOlderTerminalOutput, combineTerminalSessionState, EMPTY_TERMINAL_BUFFER_STATE, @@ -276,64 +277,77 @@ describe("terminal session reducers", () => { expect(state.lifecycleVersion).toBe(2); }); - it("prepends older pages contiguously and stops at the buffer or the server's start", () => { - const output = (data: string) => - ({ type: "output", threadId: TARGET.threadId, terminalId: TARGET.terminalId, data }) as const; - let state = applyTerminalAttachStreamEvent( - EMPTY_TERMINAL_BUFFER_STATE, - { - type: "snapshot", - snapshot: { ...BASE_SNAPSHOT, history: "c\nd\n", historyOffset: 4, olderHistory: true }, + it("slides its window through server history and back to the live output", () => { + const output = (data: string, historyEnd: number) => + ({ + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + data, + historyEnd, + }) as const; + const page = (data: string, offset: number, end: number, more = true) => ({ + data, + offset, + end, + olderHistory: offset > 0, + newerHistory: more, + }); + const budget = 8; + const apply = ( + state: typeof EMPTY_TERMINAL_BUFFER_STATE, + event: Parameters[1], + ) => applyTerminalAttachStreamEvent(state, event, budget); + let state = apply(EMPTY_TERMINAL_BUFFER_STATE, { + type: "snapshot", + snapshot: { + ...BASE_SNAPSHOT, + history: "c\nd\n", + historyOffset: 4, + historyEnd: 8, + olderHistory: true, }, - 12, - ); + }); + state = apply(state, output("$ ", 10)); let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor; - state = applyTerminalAttachStreamEvent(state, output("$ "), 12); - expect(state.output.historyOffset).toBe(4); - cursor = readTerminalOutputUpdate(state.output, cursor).cursor; + expect(canLoadOlderTerminalOutput(state.output)).toBe(true); - // A page that does not end where the retained history starts is stale. - const stale = { type: "olderHistory", page: { data: "x\n", offset: 1, olderHistory: true } }; - expect(applyTerminalAttachStreamEvent(state, stale as never, 12)).toBe(state); + // A page that does not end where the held output starts is stale. + expect(apply(state, { type: "olderHistory", page: page("x\n", 1, 3) })).toBe(state); - state = applyTerminalAttachStreamEvent( - state, - { type: "olderHistory", page: { data: "b\n", offset: 2, olderHistory: true } }, - 12, - ); - expect(terminalOutputText(state.output)).toBe("b\nc\nd\n$ "); + // Older output past the budget pushes out the newest, and the window detaches. + state = apply(state, { type: "olderHistory", page: page("a\nb\n", 0, 4) }); + expect(terminalOutputText(state.output)).toBe("a\nb\nc\nd\n"); + expect(state.output.detached).toMatchObject({ end: 8, bufferedFrom: 10 }); + expect(canLoadOlderTerminalOutput(state.output)).toBe(false); + expect(canLoadNewerTerminalOutput(state.output)).toBe(true); + const prepended = readTerminalOutputUpdate(state.output, cursor); + expect(prepended).toMatchObject({ type: "reset", anchor: { split: 4, keep: "start" } }); + cursor = prepended.cursor; + + // Live output waits aside while the window shows older output. + state = apply(state, output("x\n", 12)); + expect(readTerminalOutputUpdate(state.output, cursor).type).toBe("none"); + + // A newer page reaching the server's end drops the oldest output and follows live again. + state = apply(state, { type: "newerHistory", page: page("$ x\n", 8, 12, false) }); + expect(terminalOutputText(state.output)).toBe("c\nd\n$ x\n"); + expect(state.output).toMatchObject({ detached: null, historyOffset: 4, olderHistory: true }); expect(readTerminalOutputUpdate(state.output, cursor)).toMatchObject({ type: "reset", - data: "b\nc\nd\n$ ", - prepended: true, + anchor: { split: 4, keep: "end" }, }); - expect(canLoadOlderTerminalOutput(state.output, 12)).toBe(true); - - state = applyTerminalAttachStreamEvent( - state, - { type: "olderHistory", page: { data: "a\n", offset: 0, olderHistory: false } }, - 12, - ); - expect(terminalOutputText(state.output)).toBe("a\nb\nc\nd\n$ "); - expect(canLoadOlderTerminalOutput(state.output, 12)).toBe(false); - - // Live output that pushes out every server character ends paging: it is not server text. - state = applyTerminalAttachStreamEvent(state, output("0123456789X"), 12); - expect(state.output.historyOffset).toBeNull(); - expect(canLoadOlderTerminalOutput(state.output, 12)).toBe(false); + state = apply(state, output("y\n", 14)); + expect(terminalOutputText(state.output)).toBe("d\n$ x\ny\n"); + expect(state.output.historyOffset).toBe(6); - // Trimming part of the server history moves the anchor and leaves older output loadable. - state = applyTerminalAttachStreamEvent( - EMPTY_TERMINAL_BUFFER_STATE, - { - type: "snapshot", - snapshot: { ...BASE_SNAPSHOT, history: "abcdefgh", historyOffset: 10, olderHistory: false }, - }, - 8, - ); - state = applyTerminalAttachStreamEvent(state, output("12"), 8); - expect(state.output).toMatchObject({ historyOffset: 12, historyLength: 6, olderHistory: true }); - expect(canLoadOlderTerminalOutput(state.output, 8)).toBe(false); + // Jumping to the latest output replaces a detached window and replays what came after. + state = apply(state, { type: "olderHistory", page: page("b\nc\n", 2, 6) }); + expect(state.output.detached).not.toBeNull(); + state = apply(state, output("z\n", 16)); + state = apply(state, { type: "latestHistory", page: page("$ x\ny\n", 8, 14, false) }); + expect(terminalOutputText(state.output)).toBe("$ x\ny\nz\n"); + expect(state.output.detached).toBeNull(); }); it("does not reuse a renderer cursor when a fresh attach has matching counters", () => { diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index 35323d3726863..756dcebea788e 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -9,14 +9,17 @@ import type { } from "@t3tools/contracts"; import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts"; import { + appendNewerOutput, appendOutput, EMPTY_TERMINAL_OUTPUT_STATE, prependOutput, resetOutput, + showLatestOutput, type TerminalOutputState, } from "./terminalOutput.ts"; export { + canLoadNewerTerminalOutput, canLoadOlderTerminalOutput, INITIAL_TERMINAL_OUTPUT_CURSOR, readTerminalOutputUpdate, @@ -120,9 +123,13 @@ function terminalBufferStateFromSnapshot( current.output, snapshot.history, maxBufferBytes, - snapshot.historyOffset === undefined + snapshot.historyOffset === undefined || snapshot.historyEnd === undefined ? undefined - : { offset: snapshot.historyOffset, older: snapshot.olderHistory ?? false }, + : { + offset: snapshot.historyOffset, + end: snapshot.historyEnd, + older: snapshot.olderHistory ?? false, + }, ), grid: nextGrid(current.grid, snapshot), status: snapshot.status, @@ -166,20 +173,29 @@ export function combineTerminalSessionState( }; } -/** A page of older output the client asked for, applied in order with the stream's events. */ -export interface TerminalOlderHistoryEvent { - readonly type: "olderHistory"; +/** A page of output the client asked for, applied in order with the stream's events. */ +export interface TerminalHistoryPageEvent { + /** Older output before what is held, newer output after it, or the newest output. */ + readonly type: "olderHistory" | "newerHistory" | "latestHistory"; readonly page: TerminalHistoryPage; } export function applyTerminalAttachStreamEvent( current: TerminalBufferState, - event: TerminalAttachStreamEvent | TerminalOlderHistoryEvent, + event: TerminalAttachStreamEvent | TerminalHistoryPageEvent, maxBufferBytes = DEFAULT_MAX_TERMINAL_BUFFER_BYTES, ): TerminalBufferState { switch (event.type) { - case "olderHistory": { - const output = prependOutput(current.output, event.page, maxBufferBytes); + case "olderHistory": + case "newerHistory": + case "latestHistory": { + const apply = + event.type === "olderHistory" + ? prependOutput + : event.type === "newerHistory" + ? appendNewerOutput + : showLatestOutput; + const output = apply(current.output, event.page, maxBufferBytes); return output === current.output ? current : { ...current, output, version: current.version + 1 }; @@ -207,7 +223,7 @@ export function applyTerminalAttachStreamEvent( case "output": return { ...current, - output: appendOutput(current.output, event.data, maxBufferBytes), + output: appendOutput(current.output, event.data, maxBufferBytes, event.historyEnd), status: current.status === "closed" ? "running" : current.status, error: null, version: current.version + 1, diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index fce3ae3216c55..d97b0919f5aec 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -3,9 +3,13 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; export const DEFAULT_TERMINAL_ID = "term-1"; -/** How much output a client keeps per terminal, including older pages it loaded. */ -export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 8 * 1024 * 1024; -/** The newest output an attach sends, and the size of each older page after it. */ +/** How much output a client holds per terminal; older or newer output is paged in. */ +export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 4 * 1024 * 1024; +/** Line breaks a client holds per terminal, so its rows stay within the view's scrollback. */ +export const MAX_TERMINAL_BUFFER_LINES = 25_000; +/** Rows a terminal view keeps, above what the buffer's lines need for wrapped lines. */ +export const TERMINAL_VIEW_SCROLLBACK_ROWS = 60_000; +/** The newest output an attach sends, and the size of each page after it. */ export const TERMINAL_HISTORY_PAGE_BYTES = 512 * 1024; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; @@ -72,18 +76,28 @@ export const TerminalWriteInput = Schema.Struct({ }); export type TerminalWriteInput = Schema.Codec.Encoded; -/** Output the server keeps from before `before`, an offset from a snapshot or earlier page. */ +const HistoryOffsetSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); + +/** + * A page of the output the server keeps. Offsets count UTF-8 bytes of the terminal's + * history. `before` reads the page ending there, `after` the one starting there, and + * neither the newest page. + */ export const TerminalHistoryInput = Schema.Struct({ ...TerminalSessionInput.fields, - before: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + before: Schema.optional(HistoryOffsetSchema), + after: Schema.optional(HistoryOffsetSchema), }); export type TerminalHistoryInput = Schema.Codec.Encoded; export const TerminalHistoryPage = Schema.Struct({ data: Schema.String, - /** Where `data` starts; pass it as `before` for the page before this one. */ - offset: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + /** Where `data` starts and ends. */ + offset: HistoryOffsetSchema, + end: HistoryOffsetSchema, olderHistory: Schema.Boolean, + /** The server held more output after `end` when it read the page. */ + newerHistory: Schema.Boolean, }); export type TerminalHistoryPage = typeof TerminalHistoryPage.Type; @@ -116,8 +130,9 @@ export const TerminalSessionSnapshot = Schema.Struct({ pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))), /** The newest output; `olderHistory` says the server keeps more before it. */ history: Schema.String, - /** Where `history` starts, for `terminal.history`. Absent from older servers. */ - historyOffset: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + /** Where `history` starts and ends, for `terminal.history`. Absent from older servers. */ + historyOffset: Schema.optional(HistoryOffsetSchema), + historyEnd: Schema.optional(HistoryOffsetSchema), olderHistory: Schema.optional(Schema.Boolean), exitCode: Schema.NullOr(Schema.Int), exitSignal: Schema.NullOr(Schema.Int), @@ -184,6 +199,8 @@ const TerminalOutputEvent = Schema.Struct({ ...TerminalEventBaseSchema.fields, type: Schema.Literal("output"), data: Schema.String, + /** Where the server's history ends after this output. Absent from older servers. */ + historyEnd: Schema.optional(HistoryOffsetSchema), }); const TerminalExitedEvent = Schema.Struct({ From 73c62ba6860eee38f6ed6673e86653d1059aa89e Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Wed, 11 Nov 2026 14:16:02 +0100 Subject: [PATCH 5/5] fix(terminal): keep paged terminal history reachable and its files safe Review of the sliding window found several ways to lose older output or stall: - A live event over 16 KiB is split into chunks and only its last knows the server offset, so trimming an earlier one lost the window's start and "load older" stopped working. Trimming now drops through to that last chunk. - A paused view whose end the server had since trimmed ignored the next page, so "load later" did nothing. The page is accepted after a visible "Earlier output was removed" line; an older page past the server's start ends paging. - In narrow terminals 4 MiB of output can exceed the view's 60,000 rows, so a prepended page fell outside the view. The window now holds no more than fits the rows of the terminal's grid (a row per line plus one per column width of bytes), and the separate line budget is gone. - A page read chose its file range before taking the file lock, so a rewrite in between could make it read before the file's start. The range is re-clamped against the history and file start under the lock. - Memory pages now start at a character boundary. - Failed history writes, as on a full disk, back off from 1 s up to 60 s instead of trying a full rewrite every 250 ms; each failure is still logged, and closing a terminal still writes at once. - Rewrite directories a crash left behind are removed at startup, and history deletion takes the file lock so a rewrite cannot rename a file back. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/History.test.ts | 24 +++ apps/server/src/terminal/History.ts | 44 +++++ apps/server/src/terminal/Manager.test.ts | 64 +++++++ apps/server/src/terminal/Manager.ts | 171 ++++++++++++------ apps/web/src/terminal/ghostty/core.test.ts | 7 +- docs/user/terminal.md | 5 +- .../src/state/terminalOutput.ts | 110 +++++++---- .../src/state/terminalSession.test.ts | 135 +++++++++++++- .../src/state/terminalSession.ts | 12 +- packages/contracts/src/terminal.ts | 4 +- 10 files changed, 470 insertions(+), 106 deletions(-) diff --git a/apps/server/src/terminal/History.test.ts b/apps/server/src/terminal/History.test.ts index 976d470b9027f..212c3dad09bd3 100644 --- a/apps/server/src/terminal/History.test.ts +++ b/apps/server/src/terminal/History.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test"; import { BoundedTerminalHistory, + historyFileRead, planHistoryFileWrite, releaseHistoryMemory, startPageAtLine, @@ -144,4 +145,27 @@ describe("BoundedTerminalHistory", () => { 500 * 1024, ); }); + + it("starts memory pages at a character and file reads within what the file holds", () => { + const history = new BoundedTerminalHistory(100, "a損b", 1_000); + // Byte 2 is inside 損, which starts at 1 and ends at 4. + expect(history.alignForward(2)).toBe(4); + expect(history.alignForward(1)).toBe(1); + expect(history.memoryText(history.alignForward(2))).toBe("b"); + + expect(historyFileRead(100, 200, 50, 40)).toEqual({ + from: 100, + readFrom: 99, + position: 59, + length: 101, + }); + // A rewrite trimmed the history and moved the file's start past the chosen range. + expect(historyFileRead(100, 200, 150, 150)).toEqual({ + from: 150, + readFrom: 150, + position: 0, + length: 50, + }); + expect(historyFileRead(100, 200, 250, 250)).toBeNull(); + }); }); diff --git a/apps/server/src/terminal/History.ts b/apps/server/src/terminal/History.ts index eb4fa7234548a..f018bbbb6a16f 100644 --- a/apps/server/src/terminal/History.ts +++ b/apps/server/src/terminal/History.ts @@ -395,6 +395,27 @@ export class BoundedTerminalHistory { return pieces.join(""); } + /** The first character boundary at or after `offset` in memory. */ + alignForward(offset: number): number { + if (offset <= this.memoryStart) return this.memoryStart; + if (offset >= this.end) return this.end; + let chunkStart = this.memoryStart; + for (let index = this.start; index < this.chunks.length; index += 1) { + const chunk = this.chunks[index]!; + if (chunkStart + chunk.byteLength > offset) { + let consumed = 0; + for (let at = 0; consumed < offset - chunkStart;) { + const codePoint = chunk.data.codePointAt(at)!; + consumed += utf8Width(codePoint); + at += codePoint <= 0xffff ? 1 : 2; + } + return chunkStart + consumed; + } + chunkStart += chunk.byteLength; + } + return this.end; + } + /** Whether the text just before `offset` is a line break, when memory holds it. */ lineBreakBefore(offset: number): boolean | undefined { if (offset <= this.memoryStart || offset > this.end) return undefined; @@ -501,3 +522,26 @@ export function releaseHistoryMemory( if (total <= budget) return; } } + +/** + * Where to read history `[from, to)` in a file holding it from `fileStart`, taken under + * the file's lock: a rewrite can have trimmed the history or moved the file's start since + * the range was chosen. Reads one byte more in front, to tell whether the range starts a + * line. Null when the file holds none of it. + */ +export function historyFileRead( + from: number, + to: number, + historyStart: number, + fileStart: number, +): { + readonly from: number; + readonly readFrom: number; + readonly position: number; + readonly length: number; +} | null { + const lower = Math.max(from, historyStart, fileStart); + if (to <= lower) return null; + const readFrom = Math.max(fileStart, lower - 1); + return { from: lower, readFrom, position: readFrom - fileStart, length: to - readFrom }; +} diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index a318da166f2f3..cc5dc72044c06 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1071,6 +1071,70 @@ it.layer( }), ); + it.effect("waits longer after each failed history write", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + let attempts = 0; + const full = FileSystem.FileSystem.of({ + ...fs, + makeTempFileScoped: () => { + attempts += 1; + return Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "makeTempFileScoped", + cause: { code: "ENOSPC" }, + }), + ); + }, + }); + const { manager, ptyAdapter } = yield* createManager(5, { + processTable: Effect.succeed([]), + }).pipe(Effect.provideService(FileSystem.FileSystem, full)); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const quarterSeconds = (count: number) => + Effect.forEach(Array.from({ length: count }), () => TestClock.adjust("250 millis"), { + discard: true, + }); + process.emitData("a\n"); + yield* quarterSeconds(1); + expect(attempts).toBe(1); + // Output keeps arriving, but the next attempt waits a second, then two. + for (const output of ["b\n", "c\n", "d\n"]) process.emitData(output); + yield* quarterSeconds(3); + expect(attempts).toBe(1); + yield* quarterSeconds(2); + expect(attempts).toBe(2); + process.emitData("e\n"); + yield* quarterSeconds(6); + expect(attempts).toBe(2); + yield* quarterSeconds(4); + expect(attempts).toBe(3); + // Closing writes at once, whatever the delay; it waits out a pending debounce. + const closing = yield* manager + .close({ threadId: "thread-1" }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* quarterSeconds(1); + yield* Fiber.join(closing); + expect(attempts).toBe(4); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("removes rewrites a crash left behind when it starts", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { join } = yield* Path.Path; + const logsDir = join(yield* fs.makeTempDirectoryScoped(), "terminals"); + yield* fs.makeDirectory(join(logsDir, ".history-abc123"), { recursive: true }); + yield* fs.writeFileString(join(logsDir, ".history-abc123", "f00d"), "partial"); + yield* fs.writeFileString(join(logsDir, "kept.log"), "history\n"); + yield* TerminalManager.makeWithOptions({ logsDir, ptyAdapter: new FakePtyAdapter() }); + expect(yield* fs.readDirectory(logsDir)).toEqual(["kept.log"]); + }), + ); + it.effect("replaces a mostly trimmed history file by renaming a complete copy", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e2df04465a74a..c66eb959d358d 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -37,7 +37,10 @@ import { CodexSettings, ProviderInstanceId, } from "@t3tools/contracts"; -import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; +import { + makeKeyedCoalescingWorker, + type KeyedCoalescingWorker, +} from "@t3tools/shared/KeyedCoalescingWorker"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -48,6 +51,7 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Config from "effect/Config"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -80,6 +84,7 @@ import { terminalOutputStream } from "./OutputProtocol.ts"; import { BoundedTerminalHistory, DEFAULT_HISTORY_BYTE_LIMIT, + historyFileRead, planHistoryFileWrite, releaseHistoryMemory, startPageAtLine, @@ -112,6 +117,10 @@ const DEFAULT_HISTORY_MEMORY_BUDGET = 512 * 1024 * 1024; // A terminal keeps at least this much in memory, so attaching never reads its file. const MIN_HISTORY_MEMORY_BYTES = 2 * TERMINAL_HISTORY_PAGE_BYTES; const HISTORY_FILE_BLOCK_BYTES = 1024 * 1024; +const HISTORY_TEMP_PREFIX = ".history-"; +// After a failed history write, the next waits this long, doubling to the maximum. +const PERSIST_RETRY_BASE_MS = 1_000; +const PERSIST_RETRY_MAX_MS = 60_000; // eCryptfs permits 143-byte names. const MAX_HISTORY_FILENAME_BYTES = 143; const DEFAULT_PERSIST_DEBOUNCE_MS = 250; @@ -415,7 +424,7 @@ function terminalWireLabel(session: TerminalSessionState): string { /** The newest output held in memory, up to one page, starting at a line. */ function newestHistoryPage(history: BoundedTerminalHistory): HistoryPage { const end = history.endOffset; - const from = Math.max(history.memoryStart, end - TERMINAL_HISTORY_PAGE_BYTES); + const from = history.alignForward(end - TERMINAL_HISTORY_PAGE_BYTES); const page = startPageAtLine( history.memoryText(from, end), from, @@ -1523,6 +1532,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void); yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); + // A crash during a rewrite leaves its temporary directory behind. + yield* fileSystem.readDirectory(logsDir).pipe( + Effect.flatMap((entries) => + Effect.forEach( + entries.filter((name) => name.startsWith(HISTORY_TEMP_PREFIX)), + (name) => fileSystem.remove(path.join(logsDir, name), { recursive: true, force: true }), + { discard: true }, + ), + ), + Effect.catch((error) => + Effect.logWarning("failed to remove leftover terminal history rewrites", { error }), + ), + ); const managerStateRef = yield* SynchronizedRef.make({ sessions: new Map(), @@ -1859,7 +1881,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* Effect.gen(function* () { const temporaryPath = yield* fileSystem.makeTempFileScoped({ directory: logsDir, - prefix: ".history-", + prefix: HISTORY_TEMP_PREFIX, }); yield* Effect.gen(function* () { const out = yield* fileSystem.open(temporaryPath, { flag: "w" }); @@ -1884,50 +1906,70 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func history.persisted = write.persisted; }); - const persistWorker = yield* makeKeyedCoalescingWorker< - string, - PersistHistoryRequest, - never, - never - >({ - merge: (current, next) => ({ - history: next.history, - immediate: current.immediate || next.immediate, - }), - process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { - if (!request.immediate) { - yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS); - } + // Consecutive failed writes per terminal and when the next may run, so a full disk does + // not cost a rewrite attempt every debounce. + const persistRetries = new Map(); - const [threadId, terminalId] = sessionKey.split("\u0000"); - if (!threadId || !terminalId) { - return; - } + const persistWorker: KeyedCoalescingWorker = + yield* makeKeyedCoalescingWorker({ + merge: (current, next) => ({ + history: next.history, + immediate: current.immediate || next.immediate, + }), + process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { + if (!request.immediate) { + yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS); + // After a failure, wait out the retry delay, but let an immediate write through. + const retry = persistRetries.get(sessionKey); + if (retry !== undefined && (yield* Clock.currentTimeMillis) < retry.at) { + yield* persistWorker.enqueue(sessionKey, request); + return; + } + } - yield* historyFileLocks - .withLock( - sessionKey, - writeHistoryFile(historyPath(threadId, terminalId), request.history).pipe( - Effect.tap(() => Effect.sync(() => request.history.spill(historyMemoryBytes))), - ), - ) - .pipe( - Effect.catchCause((cause) => - Effect.logWarning("failed to persist terminal history", { - threadId, - terminalId, - cause, - }), - ), + const [threadId, terminalId] = sessionKey.split("\u0000"); + if (!threadId || !terminalId) { + return; + } + + yield* historyFileLocks + .withLock( + sessionKey, + writeHistoryFile(historyPath(threadId, terminalId), request.history).pipe( + Effect.tap(() => Effect.sync(() => request.history.spill(historyMemoryBytes))), + ), + ) + .pipe( + Effect.tap(() => Effect.sync(() => persistRetries.delete(sessionKey))), + Effect.catchCause((cause) => + Effect.gen(function* () { + const failures = (persistRetries.get(sessionKey)?.failures ?? 0) + 1; + const delayMs = Math.min( + PERSIST_RETRY_MAX_MS, + PERSIST_RETRY_BASE_MS * 2 ** (failures - 1), + ); + persistRetries.set(sessionKey, { + failures, + at: (yield* Clock.currentTimeMillis) + delayMs, + }); + yield* Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + failures, + retryInMs: delayMs, + cause, + }); + }), + ), + ); + const { sessions } = yield* readManagerState; + releaseHistoryMemory( + [...sessions.values()].map((session) => session.history), + historyMemoryBudget, + MIN_HISTORY_MEMORY_BYTES, ); - const { sessions } = yield* readManagerState; - releaseHistoryMemory( - [...sessions.values()].map((session) => session.history), - historyMemoryBudget, - MIN_HISTORY_MEMORY_BYTES, - ); - }), - }); + }), + }); const queuePersist = Effect.fn("terminal.queuePersist")(function* ( threadId: string, @@ -2071,31 +2113,46 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ) { // Read memory first: releasing output to the file while reading only moves it on disk. const memoryStart = history.memoryStart; - const memoryPart = history.memoryText(Math.max(from, memoryStart), to); + const memoryFrom = history.alignForward(from); + const memoryPart = history.memoryText(memoryFrom, to); const persisted = history.persisted; if (from >= memoryStart || persisted === null) { return { data: memoryPart, - from: Math.max(from, memoryStart), + from: memoryFrom, to, - lineBreakBefore: history.lineBreakBefore(Math.max(from, memoryStart)) ?? false, + lineBreakBefore: history.lineBreakBefore(memoryFrom) ?? false, }; } const diskEnd = Math.min(to, memoryStart); - // One byte more in front tells whether the range starts a line. - const readFrom = Math.max(persisted.fileStart, from - 1); - const bytes = yield* historyFileLocks.withLock( + const read = yield* historyFileLocks.withLock( toSessionKey(threadId, terminalId), Effect.suspend(() => { - const current = history.persisted ?? persisted; - return readFileRange( - historyPath(threadId, terminalId), - readFrom - current.fileStart, - diskEnd - current.fileStart, + const plan = historyFileRead( + from, + diskEnd, + history.startOffset, + (history.persisted ?? persisted).fileStart, ); + return plan === null + ? Effect.succeed(null) + : readFileRange( + historyPath(threadId, terminalId), + plan.position, + plan.position + plan.length, + ).pipe(Effect.map((bytes) => ({ ...plan, bytes }))); }), ); - let start = from - readFrom; + if (read === null) { + return { + data: memoryPart, + from: memoryStart, + to, + lineBreakBefore: history.lineBreakBefore(memoryStart) ?? false, + }; + } + const { bytes, readFrom } = read; + let start = read.from - readFrom; const lineBreakBefore = start > 0 && bytes[start - 1] === 10; while (start < bytes.length && isContinuationByte(bytes[start])) start += 1; let stop = bytes.length; @@ -2127,6 +2184,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* fileSystem.remove(filePath, { force: true }); } }).pipe( + // A rewrite in flight would rename its file back after the removal. + (removal) => historyFileLocks.withLock(toSessionKey(threadId, terminalId), removal), Effect.catch((error) => Effect.logWarning("failed to delete terminal history", { threadId, diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index b1f3ba975320e..6240e5ef9de6c 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -320,16 +320,15 @@ describe("GhosttyTerminalCore snapshots", () => { const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR); writeTerminalOutputUpdate(core, initial); const reset = vi.spyOn(core, "resetAndWrite"); - // Long lines, so the byte budget binds before the line budget. const data = `${"line".repeat(100)}\r\n`.repeat(128); const appends = Math.ceil((1.5 * DEFAULT_MAX_TERMINAL_BUFFER_BYTES) / data.length); for (let index = 0; index < appends; index += 1) state = append(state, data); const recovery = readTerminalOutputUpdate(state.output, initial.cursor); if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`); - expect(new TextEncoder().encode(recovery.data).byteLength).toBe( - DEFAULT_MAX_TERMINAL_BUFFER_BYTES, - ); + // The recovery replays only what the bounded buffer holds. + expect(new TextEncoder().encode(recovery.data).byteLength).toBe(state.output.retainedBytes); + expect(state.output.retainedBytes).toBeLessThanOrEqual(DEFAULT_MAX_TERMINAL_BUFFER_BYTES); writeTerminalOutputUpdate(core, recovery); reference.resetAndWrite(recovery.data); expect(core.snapshot()).toEqual(reference.snapshot()); diff --git a/docs/user/terminal.md b/docs/user/terminal.md index ae1e5cfc70e33..7670f7dcd8229 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -8,8 +8,9 @@ truncated. To change the limits, set `T3CODE_TERMINAL_HISTORY_MAX_LINES` or When you open or reconnect to a terminal, it shows the most recent output first. On web and desktop, scrolling to the top loads earlier output, and you can keep -going back to the oldest output the server keeps. A terminal view holds about -4 MiB of output at a time, so when you read far back, the newest output is set +going back to the oldest output the server keeps. A terminal view holds up to +4 MiB of output at a time (less in narrow terminals, so all of it fits in the +view's scrollback), so when you read far back, the newest output is set aside and a **Jump to latest** button appears; scrolling down loads later output again. On iPhone, iPad, and Android, use **Load earlier output**, **Load later output**, and **Jump to latest output** in the terminal menu. diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts index 2814bfcc3f385..5da7b206f54d0 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -1,4 +1,4 @@ -import { MAX_TERMINAL_BUFFER_LINES, TERMINAL_HISTORY_PAGE_BYTES } from "@t3tools/contracts"; +import { TERMINAL_HISTORY_PAGE_BYTES, TERMINAL_VIEW_SCROLLBACK_ROWS } from "@t3tools/contracts"; export interface TerminalOutputChunk { readonly startOffset: number; @@ -89,6 +89,8 @@ const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024; const MAX_TERMINAL_OUTPUT_CHUNKS = 2_048; // Live output kept aside while the held output ends before it. const MAX_DETACHED_BUFFER_BYTES = TERMINAL_HISTORY_PAGE_BYTES; +const TRIMMED_OUTPUT_MARKER = + "\r\n\u001b[0;2m[Earlier output was removed from this terminal's history]\u001b[0m\r\n"; const textEncoder = new TextEncoder(); // A BOM at a retained chunk boundary is terminal data, not an encoding marker. const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }); @@ -247,41 +249,61 @@ interface Window { dropped: boolean; } +// Columns assumed before the terminal reports its grid. +const DEFAULT_TERMINAL_COLS = 80; +// Rows the held output may take in a view, short of its scrollback for an estimate's slack. +const VIEW_ROW_BUDGET = Math.floor(TERMINAL_VIEW_SCROLLBACK_ROWS * 0.9); + +/** + * Bytes the window may hold: its budget, and few enough that its rows fit the view's + * scrollback, counting a row per line plus one per `cols` bytes, an upper bound for any + * mix of short and wrapped lines. Past the view's rows, older output would not show. + */ +function byteBudget(maxBytes: number, lines: number, cols: number): number { + return Math.min(maxBytes, (VIEW_ROW_BUDGET - lines) * Math.max(1, cols)); +} + /** * Drops the oldest output until the window fits. Output whose server offsets are known * goes a chunk at a time (live output) or exactly (server text), so the window's start * stays a known offset older output can be read before. */ -function trimFront(window: Window, maxBytes: number, maxLines: number): void { - while (window.chunks.length > 0 && (window.bytes > maxBytes || window.lines > maxLines)) { +function trimFront(window: Window, maxBytes: number, cols: number): void { + for (;;) { + const budget = byteBudget(maxBytes, window.lines, cols); + if (window.chunks.length === 0 || window.bytes <= budget) return; const first = window.chunks[0]!; - const bytesOver = window.bytes - maxBytes; - const linesOver = window.lines - maxLines; + const bytesOver = window.bytes - Math.max(0, budget); window.dropped = true; - const whole = first.byteLength <= bytesOver || first.lineBreaks <= linesOver - 1; - if (!whole && (first.exact || (first.serverEnd === null && !first.pendingEnd))) { - const trimmed = trimChunkStart(first, Math.max(0, bytesOver), Math.max(0, linesOver)); + if ( + first.byteLength > bytesOver && + (first.exact || (first.serverEnd === null && !first.pendingEnd)) + ) { + const trimmed = trimChunkStart(first, bytesOver, 0); window.bytes -= trimmed.droppedBytes; window.lines -= first.lineBreaks - trimmed.chunk.lineBreaks; window.historyOffset = first.exact && window.historyOffset !== null ? window.historyOffset + trimmed.droppedBytes : null; - if (trimmed.chunk.data.length > 0) { - window.chunks[0] = trimmed.chunk; - continue; - } - window.chunks.shift(); + if (trimmed.chunk.data.length > 0) window.chunks[0] = trimmed.chunk; + else window.chunks.shift(); continue; } - window.chunks.shift(); - window.bytes -= first.byteLength; - window.lines -= first.lineBreaks; + // Live output split into chunks knows its offset only at its last one: drop through it. + let dropped = first; + let droppedBytes = 0; + for (;;) { + window.chunks.shift(); + window.bytes -= dropped.byteLength; + window.lines -= dropped.lineBreaks; + droppedBytes += dropped.byteLength; + if (dropped.serverEnd !== null || !dropped.pendingEnd || window.chunks.length === 0) break; + dropped = window.chunks[0]!; + } window.historyOffset = - first.serverEnd ?? - (first.exact && window.historyOffset !== null - ? window.historyOffset + first.byteLength - : null); + dropped.serverEnd ?? + (dropped.exact && window.historyOffset !== null ? window.historyOffset + droppedBytes : null); } } @@ -321,7 +343,7 @@ function appendOutput( data: string, maxBufferBytes: number, serverEnd?: number, - maxLines = MAX_TERMINAL_BUFFER_LINES, + cols = DEFAULT_TERMINAL_COLS, ): TerminalOutputState { if (data.length === 0) return current; const detached = current.detached; @@ -359,7 +381,7 @@ function appendOutput( Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), ), ]); - trimFront(window, maxBufferBytes, maxLines); + trimFront(window, maxBufferBytes, cols); return fromWindow(current, window, { nextOffset: current.nextOffset + data.length, }); @@ -371,7 +393,7 @@ function resetOutput( data: string, maxBufferBytes: number, history?: { readonly offset: number; readonly end: number; readonly older: boolean }, - maxLines = MAX_TERMINAL_BUFFER_LINES, + cols = DEFAULT_TERMINAL_COLS, ): TerminalOutputState { const window: Window = { chunks: [ @@ -394,7 +416,7 @@ function resetOutput( window.bytes = 0; window.lines = 0; } - trimFront(window, Math.max(0, maxBufferBytes), maxLines); + trimFront(window, Math.max(0, maxBufferBytes), cols); return { ...fromWindow({ ...current, olderHistory: history?.older ?? false }, window, {}), resetVersion: current.resetVersion + 1, @@ -428,12 +450,15 @@ function prependOutput( current: TerminalOutputState, page: TerminalHistoryPageInput, maxBufferBytes: number, - maxLines = MAX_TERMINAL_BUFFER_LINES, + cols = DEFAULT_TERMINAL_COLS, ): TerminalOutputState { const end = windowEnd(current); - if (current.historyOffset === null || page.end !== current.historyOffset || end === null) { - return current; + if (current.historyOffset === null || end === null) return current; + // The server no longer keeps output before what is held. + if (page.end > current.historyOffset || (page.data.length === 0 && !page.olderHistory)) { + return current.olderHistory ? { ...current, olderHistory: false } : current; } + if (page.end !== current.historyOffset) return current; if (page.data.length === 0) { return page.olderHistory === current.olderHistory ? current @@ -446,7 +471,7 @@ function prependOutput( // Drop the newest output, keeping the end at a known offset, until the window fits. let newEnd = end; let droppedNewest = false; - while (chunks.length > added.length && (bytes > maxBufferBytes || lines > maxLines)) { + while (chunks.length > added.length && bytes > byteBudget(maxBufferBytes, lines, cols)) { const last = chunks.pop()!; bytes -= last.byteLength; lines -= last.lineBreaks; @@ -460,7 +485,7 @@ function prependOutput( } const window: Window = { chunks, bytes, lines, historyOffset: page.offset, dropped: false }; // A page larger than the whole budget keeps its newest part. - trimFront(window, maxBufferBytes, maxLines); + trimFront(window, maxBufferBytes, cols); const split = added.reduce((total, chunk) => total + chunk.data.length, 0) - (window.chunks[0]?.startOffset ?? 0); @@ -492,16 +517,25 @@ function appendNewerOutput( current: TerminalOutputState, page: TerminalHistoryPageInput, maxBufferBytes: number, - maxLines = MAX_TERMINAL_BUFFER_LINES, + cols = DEFAULT_TERMINAL_COLS, ): TerminalOutputState { const detached = current.detached; - if (detached === null || page.offset !== detached.end) return current; - const pageChunks = makeChunks(page.data, current.nextOffset, { + if (detached === null || page.offset < detached.end) return current; + // The server trimmed output the paused view had not reached; say so where it was. + const marker = + page.offset > detached.end + ? makeChunks(TRIMMED_OUTPUT_MARKER, current.nextOffset, { + exact: false, + serverEnd: page.offset, + }) + : []; + let nextOffset = current.nextOffset + (marker.length > 0 ? TRIMMED_OUTPUT_MARKER.length : 0); + const pageChunks = makeChunks(page.data, nextOffset, { exact: true, serverEnd: page.end, }); - let nextOffset = current.nextOffset + page.data.length; - const appended = [...pageChunks]; + nextOffset += page.data.length; + const appended = [...marker, ...pageChunks]; let stillDetached: TerminalDetachedWindow | null = { ...detached, end: page.end }; if (!page.newerHistory && detached.bufferedFrom <= page.end) { for (const entry of detached.buffered) { @@ -513,7 +547,7 @@ function appendNewerOutput( stillDetached = null; } const window = windowOf(current, [...current.chunks, ...appended]); - trimFront(window, maxBufferBytes, maxLines); + trimFront(window, maxBufferBytes, cols); const dropped = window.chunks[0]?.startOffset ?? nextOffset; const firstBefore = current.chunks[0]?.startOffset ?? current.nextOffset; if (dropped === firstBefore) { @@ -535,7 +569,7 @@ function showLatestOutput( current: TerminalOutputState, page: TerminalHistoryPageInput, maxBufferBytes: number, - maxLines = MAX_TERMINAL_BUFFER_LINES, + cols = DEFAULT_TERMINAL_COLS, ): TerminalOutputState { const detached = current.detached; if (detached === null) return current; @@ -544,7 +578,7 @@ function showLatestOutput( page.data, maxBufferBytes, { offset: page.offset, end: page.end, older: page.olderHistory }, - maxLines, + cols, ); if (page.newerHistory || detached.bufferedFrom > page.end) { return { ...reset, detached: { ...detached, end: page.end } }; @@ -553,7 +587,7 @@ function showLatestOutput( (state, entry) => entry.end <= page.end ? state - : appendOutput(state, entry.data, maxBufferBytes, entry.end, maxLines), + : appendOutput(state, entry.data, maxBufferBytes, entry.end, cols), reset, ); } diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index 9e9a7a1cb0040..9aa79b9ce5dc3 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vite-plus/test"; -import { EnvironmentId, TerminalSessionSnapshot, ThreadId } from "@t3tools/contracts"; +import { + EnvironmentId, + TERMINAL_VIEW_SCROLLBACK_ROWS, + TerminalSessionSnapshot, + ThreadId, +} from "@t3tools/contracts"; import { applyTerminalAttachStreamEvent, @@ -350,6 +355,134 @@ describe("terminal session reducers", () => { expect(state.output.detached).toBeNull(); }); + it("keeps its start at a known offset when live output arrives in large events", () => { + let state = applyTerminalAttachStreamEvent( + EMPTY_TERMINAL_BUFFER_STATE, + { + type: "snapshot", + snapshot: { ...BASE_SNAPSHOT, history: "", historyOffset: 0, historyEnd: 0 }, + }, + 256 * 1024, + ); + let end = 0; + // Each event splits into chunks; only the last knows its server offset. + const event = `${"x".repeat(41 * 1024 - 1)}\n`; + for (let index = 0; index < 20; index += 1) { + end += event.length; + state = applyTerminalAttachStreamEvent( + state, + { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + data: event, + historyEnd: end, + }, + 256 * 1024, + ); + // Once the window drops output, its start is where an event ended. + if (end <= 256 * 1024) continue; + expect(canLoadOlderTerminalOutput(state.output)).toBe(true); + expect((end - state.output.historyOffset!) % event.length).toBe(0); + } + }); + + it("holds no more output than a narrow view can show", () => { + let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { + type: "activity", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + hasRunningSubprocess: false, + label: "Terminal 1", + cols: 40, + rows: 20, + }); + state = applyTerminalAttachStreamEvent(state, { + type: "snapshot", + snapshot: { + ...BASE_SNAPSHOT, + history: "", + historyOffset: 0, + historyEnd: 0, + cols: 40, + rows: 20, + }, + }); + const line = `${"y".repeat(399)}\n`; + let end = 0; + for (let index = 0; index < 100; index += 1) { + const data = line.repeat(256); + end += data.length; + state = applyTerminalAttachStreamEvent(state, { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + data, + historyEnd: end, + }); + } + // Each 400-character line takes ten rows at 40 columns. + const rows = state.output.retainedLines * 10; + expect(rows).toBeLessThanOrEqual(TERMINAL_VIEW_SCROLLBACK_ROWS); + // An older page still fits, pushing out the newest output instead. + const page = line.repeat(64); + state = applyTerminalAttachStreamEvent(state, { + type: "olderHistory", + page: { + data: page, + offset: state.output.historyOffset! - page.length, + end: state.output.historyOffset!, + olderHistory: true, + newerHistory: true, + }, + }); + expect(terminalOutputText(state.output).startsWith(page)).toBe(true); + expect(state.output.retainedLines * 10).toBeLessThanOrEqual(TERMINAL_VIEW_SCROLLBACK_ROWS); + }); + + it("shows where the server trimmed output a paused view had not reached", () => { + let state = applyTerminalAttachStreamEvent( + EMPTY_TERMINAL_BUFFER_STATE, + { + type: "snapshot", + snapshot: { ...BASE_SNAPSHOT, history: "c\nd\n", historyOffset: 4, historyEnd: 8 }, + }, + 8, + ); + state = applyTerminalAttachStreamEvent( + state, + { + type: "output", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + data: "$ ", + historyEnd: 10, + }, + 8, + ); + state = applyTerminalAttachStreamEvent( + state, + { + type: "olderHistory", + page: { data: "a\nb\n", offset: 0, end: 4, olderHistory: false, newerHistory: true }, + }, + 8, + ); + expect(state.output.detached).toMatchObject({ end: 8 }); + // The server trimmed past the paused view's end; its next page starts later. + state = applyTerminalAttachStreamEvent( + state, + { + type: "newerHistory", + page: { data: "new\n", offset: 20, end: 24, olderHistory: false, newerHistory: false }, + }, + 256, + ); + expect(terminalOutputText(state.output)).toContain("Earlier output was removed"); + expect(terminalOutputText(state.output).endsWith("new\n")).toBe(true); + expect(state.output.detached).toBeNull(); + }); + it("does not reuse a renderer cursor when a fresh attach has matching counters", () => { const first = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), { type: "snapshot", diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index 756dcebea788e..8166edae9a5ad 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -130,6 +130,8 @@ function terminalBufferStateFromSnapshot( end: snapshot.historyEnd, older: snapshot.olderHistory ?? false, }, + // The output must fit the rows of views drawing this grid. + nextGrid(current.grid, snapshot)?.cols, ), grid: nextGrid(current.grid, snapshot), status: snapshot.status, @@ -195,7 +197,7 @@ export function applyTerminalAttachStreamEvent( : event.type === "newerHistory" ? appendNewerOutput : showLatestOutput; - const output = apply(current.output, event.page, maxBufferBytes); + const output = apply(current.output, event.page, maxBufferBytes, current.grid?.cols); return output === current.output ? current : { ...current, output, version: current.version + 1 }; @@ -223,7 +225,13 @@ export function applyTerminalAttachStreamEvent( case "output": return { ...current, - output: appendOutput(current.output, event.data, maxBufferBytes, event.historyEnd), + output: appendOutput( + current.output, + event.data, + maxBufferBytes, + event.historyEnd, + current.grid?.cols, + ), status: current.status === "closed" ? "running" : current.status, error: null, version: current.version + 1, diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index d97b0919f5aec..563fc42866c42 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -5,9 +5,7 @@ import { ProviderInstanceId } from "./providerInstance.ts"; export const DEFAULT_TERMINAL_ID = "term-1"; /** How much output a client holds per terminal; older or newer output is paged in. */ export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 4 * 1024 * 1024; -/** Line breaks a client holds per terminal, so its rows stay within the view's scrollback. */ -export const MAX_TERMINAL_BUFFER_LINES = 25_000; -/** Rows a terminal view keeps, above what the buffer's lines need for wrapped lines. */ +/** Rows a terminal view keeps; a client holds no more output than fits in them. */ export const TERMINAL_VIEW_SCROLLBACK_ROWS = 60_000; /** The newest output an attach sends, and the size of each page after it. */ export const TERMINAL_HISTORY_PAGE_BYTES = 512 * 1024;