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..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 = 10000; +// 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 fde3393b911e4..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 = 512 * 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 b25c18cd0b659..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 = 512 * 1024 + private let limit = 4 * 1024 * 1024 var data: Data { storage.subdata(in: retainedStart..= limit { storage = storage.subdata(in: retainedStart.. 0 ? ( + hasSearchQuery && (threadSearch.hasMore || threadSearch.partial) ? ( + + ) : settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? ( void; readonly onOpenNewTerminal: () => void; readonly onSelectTerminal: (terminalId: string) => void; + /** 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 ( 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, + }, + ]), + ...(props.onLoadNewerOutput === null + ? [] + : [ + { + id: "terminal-load-newer", + title: "Load later output", + icon: "arrow.down", + subtitle: "Showing earlier output; live output is paused here", + onPress: props.onLoadNewerOutput, + }, + ]), + ...(props.onShowLatestOutput === null + ? [] + : [ + { + id: "terminal-show-latest", + title: "Jump to latest output", + icon: "arrow.down.circle", + onPress: props.onShowLatestOutput, + }, + ]), { id: "terminal-new", disabled: !props.canOperateTerminal, @@ -511,6 +552,11 @@ function ThreadTerminal(props: { ? { threadId: selectedThread.id, terminalId } : null, }); + const outputTarget = { + environmentId: selectedThread.environmentId, + threadId: selectedThread.id, + terminalId, + }; useAtomMount( terminalSessionDriver.driver( canOperateTerminal @@ -829,6 +875,36 @@ function ThreadTerminal(props: { onIncreaseFontSize={handleIncreaseFontSize} onOpenNewTerminal={handleOpenNewTerminal} onSelectTerminal={handleSelectTerminal} + onLoadOlderOutput={ + canLoadOlderTerminalOutput(terminal.output) + ? () => + void terminalEnvironment.loadOlderOutput( + appAtomRegistry, + 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/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..85f7c117d2c07 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 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/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 6d724ac3b0168..337b0a14b210f 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -58,6 +58,7 @@ import { ThreadListV2Row, ThreadListV2SettledShelfHeader, ThreadListV2ShowMoreRow, + ThreadSearchMoreRow, ThreadListV2SnoozedShelfHeader, ThreadListV2WorkingShelfHeader, } from "./thread-list-v2-items"; @@ -556,6 +557,15 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { }} /> ); + const searchMoreRow = + props.searchQuery.trim().length > 0 && (threadSearch.hasMore || threadSearch.partial) ? ( + + ) : null; const listEmpty = ( @@ -667,6 +678,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..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,6 +364,40 @@ export const ThreadListV2ShowMoreRow = memo(function ThreadListV2ShowMoreRow(pro ); }); +/** 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.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 })} + > + + {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..d5db54dddec2b 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -56,6 +56,8 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = 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")); @@ -206,6 +208,11 @@ export function useThreadSearch( scope: ThreadSearchScope = {}, ): { 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; readonly isPending: boolean; @@ -262,6 +269,11 @@ export function useThreadSearch( matches: visible.matches, 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/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/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/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/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..a652ab5a55bc2 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 = 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. */ @@ -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/server/src/terminal/History.test.ts b/apps/server/src/terminal/History.test.ts new file mode 100644 index 0000000000000..212c3dad09bd3 --- /dev/null +++ b/apps/server/src/terminal/History.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + BoundedTerminalHistory, + historyFileRead, + 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, + ); + }); + + 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 new file mode 100644 index 0000000000000..f018bbbb6a16f --- /dev/null +++ b/apps/server/src/terminal/History.ts @@ -0,0 +1,547 @@ +// 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(""); + } + + /** 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; + 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; + } +} + +/** + * 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 ed4645b18becf..cc5dc72044c06 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,6 +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.memoryText(history.startOffset)).toBe(expected); + expect(history.endOffset - history.startOffset).toBe(Buffer.byteLength(expected)); } } } @@ -1017,6 +1027,138 @@ it.layer( }), ); + 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: 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); + 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({ ...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(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("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; + 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); + }), + ); + it.effect("bounds persisted and attached history without truncating live output", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(5, { historyByteLimit: 10 }); @@ -1488,23 +1630,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 e2061df592d00..c66eb959d358d 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, @@ -35,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"; @@ -45,6 +50,8 @@ 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 Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -74,6 +81,17 @@ 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, + historyFileRead, + planHistoryFileWrite, + releaseHistoryMemory, + startPageAtLine, + type HistoryPage, +} from "./History.ts"; + +export { BoundedTerminalHistory }; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; export { @@ -91,11 +109,20 @@ 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; +// 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; +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 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; @@ -108,7 +135,9 @@ 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; +// 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, @@ -207,6 +236,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: ( @@ -337,6 +371,7 @@ type DrainProcessEventAction = terminalId: string; sequence: number; history: BoundedTerminalHistory | null; + historyEnd: number; data: string; } | { @@ -386,7 +421,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 = history.alignForward(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 = newestHistoryPage(session.history); return { threadId: session.threadId, terminalId: session.terminalId, @@ -394,7 +444,10 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: newest.data, + historyOffset: newest.offset, + historyEnd: newest.end, + olderHistory: newest.olderHistory, exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -870,187 +923,6 @@ const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnaps return processTableSnapshotFromProcesses(processes); }); -interface TerminalHistoryChunk { - data: string; - byteLength: number; - lineBreaks: number; -} - -export class BoundedTerminalHistory { - private readonly maxLines: number; - private readonly maxBytes: number; - private chunks: Array = []; - private start = 0; - private byteLength = 0; - private lineBreaks = 0; - // Reading the old string's tail on each append can force chunk concatenation. - private lastCodeUnit: number | undefined; - private cachedValue: string | null = ""; - - constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) { - this.maxLines = maxLines; - this.maxBytes = maxBytes; - this.append(initial); - } - - 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"); - 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.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.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; - } - - 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; - } - - 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.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; - } -} - // 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 = @@ -1058,23 +930,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); @@ -1083,11 +954,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 { @@ -1418,6 +1289,12 @@ interface TerminalManagerOptions { subprocessPollIntervalMs?: number; 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; @@ -1495,8 +1372,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( @@ -1522,6 +1420,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; @@ -1623,10 +1526,25 @@ 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); 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(), @@ -1922,39 +1840,136 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* registerKillFiber(process, fiber); }); - 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); - } + // 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 [threadId, terminalId] = sessionKey.split("\u0000"); - if (!threadId || !terminalId) { - return; + 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, 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" }); } + 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_TEMP_PREFIX, + }); + 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; + }); - yield* fileSystem - .writeFileString(historyPath(threadId, terminalId), request.history.value()) - .pipe( - Effect.catch((error) => - Effect.logWarning("failed to persist terminal history", { - threadId, - terminalId, - error, - }), - ), + // 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 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; + } + } + + 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 queuePersist = Effect.fn("terminal.queuePersist")(function* ( threadId: string, @@ -1986,28 +2001,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; + 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 }); } - return { - history: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(start, length)), - truncated: offset > 0n, + 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* ( @@ -2026,38 +2068,25 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func )) ) continue; - const { history: raw, truncated } = 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); - 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( - Effect.mapError( - (cause) => - new TerminalHistoryError({ - operation: migrating ? "migrate" : "truncate", - threadId, - terminalId, - cause, - }), - ), - ); - } if (migrating) { + // 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", { @@ -2068,11 +2097,81 @@ 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 memoryFrom = history.alignForward(from); + const memoryPart = history.memoryText(memoryFrom, to); + const persisted = history.persisted; + if (from >= memoryStart || persisted === null) { + return { + data: memoryPart, + from: memoryFrom, + to, + lineBreakBefore: history.lineBreakBefore(memoryFrom) ?? false, + }; + } + const diskEnd = Math.min(to, memoryStart); + const read = yield* historyFileLocks.withLock( + toSessionKey(threadId, terminalId), + Effect.suspend(() => { + 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 }))); + }), + ); + 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; + 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, @@ -2085,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, @@ -2169,7 +2270,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.memoryBytes, + 0, + ); + if ( + inactiveSessions.length <= maxRetainedInactiveSessions && + inactiveBytes <= maxRetainedInactiveHistoryBytes + ) { return [undefined, state] as const; } @@ -2182,11 +2290,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.memoryBytes; } return [undefined, { ...state, sessions }] as const; @@ -2241,6 +2358,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; } @@ -2290,6 +2408,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func terminalId: action.terminalId, sequence: action.sequence, data: action.data, + historyEnd: action.historyEnd, }); continue; } @@ -2840,16 +2959,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 history = new BoundedTerminalHistory( - historyLineLimit, - neutralizeInheritedHistory( - inherited.value(), - historyLineLimit, - Math.min(historyByteLimit, DEFAULT_MAX_TERMINAL_BUFFER_BYTES), - ), - historyByteLimit, - ); + 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 = { @@ -3479,9 +3590,68 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* closeIdle(input); }); + 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, 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/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8fa58d8456f75..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, @@ -3270,6 +3274,24 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); })} + {threadSearch.hasMore ? ( + + ) : 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/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 049589d0b671a..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, @@ -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.anchor !== null && terminal.resetAndWriteAnchored) { + terminal.resetAndWriteAnchored(update.data, update.anchor); + } 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 { @@ -624,11 +628,37 @@ 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) => appAtomRegistry.subscribe(terminalSessionAtom, listener), ); + const loadOlderOutput = useEffectEvent(() => { + void terminalEnvironment.loadOlderOutput( + appAtomRegistry, + { environmentId, threadId, terminalId }, + 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, @@ -731,6 +761,8 @@ function TerminalSessionViewport({ canActivateLink: (text) => canActivateTerminalLink(text), 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); @@ -941,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; } @@ -1214,11 +1247,20 @@ function TerminalSessionViewport({ }; }; return ( -
+
+
+ {viewingOlderOutput ? ( +
+ +
+ ) : null} +
); } diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index e67937375849b..41758b8186858 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -53,6 +53,8 @@ const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = 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")); @@ -105,6 +107,11 @@ export function useThreadSearch( scope: ThreadSearchScope = {}, ): { 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; } { @@ -160,6 +167,11 @@ export function useThreadSearch( matches: visible.matches, 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/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index 5e51c7b4be378..6240e5ef9de6c 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -320,14 +320,15 @@ 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); - for (let index = 0; index < 16; index += 1) state = append(state, data); + 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/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index b8ca5a624636f..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 = 10_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 f1db43056f76f..86cd6922427c7 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -531,6 +531,10 @@ 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; + /** The user scrolled down to the newest row the view holds. */ + readonly onScrollbackEnd?: () => void; } export class GhosttyTerminalSurface { @@ -569,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; @@ -776,8 +781,42 @@ export class GhosttyTerminalSurface { this.requestRender(); } + /** + * 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`. + */ + resetAndWriteAnchored(data: string, anchor: { split: number; keep: "start" | "end" }): void { + if (this.disposed) return; + const before = this.core.scrollbarState(); + 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 || 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); @@ -1923,14 +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; + } } + 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 dd921eb9a9650..7670f7dcd8229 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -1,18 +1,26 @@ # 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, and you can keep +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. 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 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/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 09ce63e2a3e65..ccd70f48366cb 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -231,7 +231,11 @@ 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. +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/terminal.ts b/packages/client-runtime/src/state/terminal.ts index a39e47b1340b4..0b4492197f5e4 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -1,6 +1,7 @@ import { type EnvironmentId, type TerminalAttachInput, + type TerminalAttachStreamEvent, type TerminalCloseInput, type TerminalOpenInput, type TerminalResizeInput, @@ -10,6 +11,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 +30,13 @@ import { EMPTY_TERMINAL_BUFFER_STATE, nextTerminalAttachSeedState, type TerminalBufferState, + type TerminalHistoryPageEvent, } from "./terminalSession.ts"; -import { terminalOutputText } from "./terminalOutput.ts"; +import { + canLoadOlderTerminalOutput, + terminalOutputText, + type TerminalOutputState, +} from "./terminalOutput.ts"; export function createTerminalEnvironmentAtoms( runtime: Atom.AtomRuntime, @@ -51,30 +58,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 }; + // 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 withHistoryPages = ( + input: { readonly threadId: string; readonly terminalId: string }, + stream: Stream.Stream, + ) => + stream.pipe( + Stream.merge( + Stream.callback((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const key = historyKey(input); + const listener = (event: TerminalHistoryPageEvent) => { + Queue.offerUnsafe(queue, event); + }; + let listeners = historyListeners.get(key); + if (!listeners) historyListeners.set(key, (listeners = new Set())); + listeners.add(listener); + return () => { + listeners.delete(listener); + if (listeners.size === 0) historyListeners.delete(key); + }; + }), + (release) => Effect.sync(release), + ), + ), + { haltStrategy: "left" }, + ), + Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent), + ); + const pendingHistory = 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(() => 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 subscribeDynamic(WS_METHODS.terminalAttach, () => - Effect.sync(() => (replied ? { ...input, resume: true } : input)), - ).pipe( - Stream.onFirst(() => - Effect.sync(() => { - replied = true; - }), + return withHistoryPages( + 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 +153,82 @@ 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(() => { + 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 }); + } + }), + }), }; + 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: Target, + position: { readonly before: number } | { readonly after: number } | null, + ): Promise => { + const key = JSON.stringify([target.environmentId, target.threadId, target.terminalId]); + if (pendingHistory.has(key)) return; + pendingHistory.add(key); + try { + await runAtomCommand( + registry, + atoms.history, + { + environmentId: target.environmentId, + input: { threadId: target.threadId, terminalId: target.terminalId, ...position }, + }, + // An older server lacks the method; the view keeps what it has. + { reportFailure: false }, + ); + } finally { + 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 df4d2ee03955c..5da7b206f54d0 100644 --- a/packages/client-runtime/src/state/terminalOutput.ts +++ b/packages/client-runtime/src/state/terminalOutput.ts @@ -1,15 +1,48 @@ +import { TERMINAL_HISTORY_PAGE_BYTES, TERMINAL_VIEW_SCROLLBACK_ROWS } 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 offset where the held output starts, or null when unknown. */ + readonly historyOffset: number | null; + /** The server keeps output before `historyOffset`. */ + readonly olderHistory: boolean; + readonly detached: TerminalDetachedWindow | null; + readonly anchor: (TerminalOutputAnchor & { readonly resetVersion: number }) | null; } export interface TerminalOutputCursor { @@ -33,6 +66,8 @@ export type TerminalOutputUpdate = readonly type: "reset"; readonly data: string; readonly cursor: TerminalOutputCursor; + /** 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"; @@ -40,8 +75,22 @@ 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; -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; +// 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 }); @@ -50,96 +99,98 @@ export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze({ generation: 0, chunks: Object.freeze([]), retainedBytes: 0, + retainedLines: 0, resetVersion: 0, nextOffset: 0, + historyOffset: null, + olderHistory: 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) { @@ -155,6 +206,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); @@ -163,107 +218,380 @@ 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, - startOffset: chunk.startOffset + offset, - data: chunk.data.slice(offset), - byteLength: chunk.byteLength - droppedBytes, + 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; +} + +// 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, 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 - Math.max(0, budget); + window.dropped = true; + 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; + else window.chunks.shift(); + continue; + } + // 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 = + dropped.serverEnd ?? + (dropped.exact && window.historyOffset !== null ? window.historyOffset + droppedBytes : null); + } +} + +function windowOf(state: TerminalOutputState, chunks: ReadonlyArray): Window { + return { + 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, + cols = DEFAULT_TERMINAL_COLS, ): 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 { - generation: current.generation, + ...current, chunks: [], retainedBytes: 0, + retainedLines: 0, resetVersion: current.resetVersion + 1, nextOffset: current.nextOffset + data.length, + historyOffset: null, + olderHistory: false, + detached: null, + anchor: null, }; } - const appended = splitOutputChunks( - data, - current.nextOffset, - Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), - ); + 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, cols); + return fromWindow(current, window, { + nextOffset: current.nextOffset + data.length, + }); +} - 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; +/** Replaces the output, as a snapshot, clear, or restart does. */ +function resetOutput( + current: TerminalOutputState, + data: string, + maxBufferBytes: number, + history?: { readonly offset: number; readonly end: number; readonly older: boolean }, + cols = DEFAULT_TERMINAL_COLS, +): TerminalOutputState { + 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), cols); + return { + ...fromWindow({ ...current, olderHistory: history?.older ?? false }, window, {}), + resetVersion: current.resetVersion + 1, + detached: null, + anchor: null, + }; +} - 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); +/** 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 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: TerminalHistoryPageInput, + maxBufferBytes: number, + cols = DEFAULT_TERMINAL_COLS, +): TerminalOutputState { + const end = windowEnd(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 + : { ...current, olderHistory: page.olderHistory }; + } + 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 > byteBudget(maxBufferBytes, lines, cols)) { + 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, cols); + 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: retainedChunks, - retainedBytes, - resetVersion: current.resetVersion, - nextOffset: appended.nextOffset, + ...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" }, }; } -function resetOutput( +/** + * 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, - data: string, + page: TerminalHistoryPageInput, maxBufferBytes: number, + cols = DEFAULT_TERMINAL_COLS, ): TerminalOutputState { - const retained = trimBufferToBytes(data, maxBufferBytes); - const reset = splitOutputChunks( - retained, - 0, - Math.min(DEFAULT_TERMINAL_CHUNK_BYTES, Math.max(1, maxBufferBytes)), - ); + const detached = current.detached; + 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, + }); + 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) { + 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, cols); + 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 { - generation: current.generation, - chunks: reset.chunks, - retainedBytes: reset.byteLength, - resetVersion: current.resetVersion + 1, - nextOffset: reset.nextOffset, + ...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, + cols = DEFAULT_TERMINAL_COLS, +): 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 }, + cols, + ); + 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, cols), + reset, + ); +} + export function terminalOutputText(output: TerminalOutputState): string { return output.chunks.map((chunk) => chunk.data).join(""); } @@ -283,7 +611,20 @@ export function readTerminalOutputUpdate( cursor.resetVersion !== output.resetVersion || cursor.offset < (firstChunk?.startOffset ?? output.nextOffset) ) { - return { type: "reset", data: terminalOutputText(output), cursor: nextCursor }; + const anchor = output.anchor; + return { + type: "reset", + data: terminalOutputText(output), + cursor: nextCursor, + // 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 + ? { split: anchor.split, keep: anchor.keep } + : null, + }; } // Appends and compaction preserve offset order, so unread chunks form a suffix. @@ -306,4 +647,4 @@ export function readTerminalOutputUpdate( }; } -export { appendOutput, 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 4eef70e099750..9aa79b9ce5dc3 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -1,10 +1,17 @@ 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, applyTerminalMetadataStreamEvent, + canLoadNewerTerminalOutput, + canLoadOlderTerminalOutput, combineTerminalSessionState, EMPTY_TERMINAL_BUFFER_STATE, INITIAL_TERMINAL_OUTPUT_CURSOR, @@ -275,6 +282,207 @@ describe("terminal session reducers", () => { expect(state.lifecycleVersion).toBe(2); }); + 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, + }, + }); + state = apply(state, output("$ ", 10)); + let cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor; + expect(canLoadOlderTerminalOutput(state.output)).toBe(true); + + // 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); + + // 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", + anchor: { split: 4, keep: "end" }, + }); + state = apply(state, output("y\n", 14)); + expect(terminalOutputText(state.output)).toBe("d\n$ x\ny\n"); + expect(state.output.historyOffset).toBe(6); + + // 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("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 e03dc30507685..8166edae9a5ad 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, @@ -8,13 +9,18 @@ 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, terminalOutputText, @@ -113,7 +119,20 @@ 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 || snapshot.historyEnd === undefined + ? undefined + : { + offset: snapshot.historyOffset, + 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, error: null, @@ -156,12 +175,33 @@ export function combineTerminalSessionState( }; } +/** 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, + event: TerminalAttachStreamEvent | TerminalHistoryPageEvent, maxBufferBytes = DEFAULT_MAX_TERMINAL_BUFFER_BYTES, ): TerminalBufferState { switch (event.type) { + 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, current.grid?.cols); + return output === current.output + ? current + : { ...current, output, version: current.version + 1 }; + } case "snapshot": { if (current.version === 0) { return terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes, current); @@ -185,7 +225,13 @@ export function applyTerminalAttachStreamEvent( case "output": return { ...current, - output: appendOutput(current.output, event.data, maxBufferBytes), + 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/client-runtime/src/state/threadSearch.test.ts b/packages/client-runtime/src/state/threadSearch.test.ts index d9f2cca584fbc..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, rows: [] }); - expect(malformedState).toEqual({ matches: [], isLoading: 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(); @@ -101,6 +113,8 @@ it("merges successful environments and silently ignores failures", () => { expect(state).toEqual({ matches: [{ ...result.matches[0], environmentId: envA }], isLoading: false, + hasMore: false, + partial: false, rows: [], }); expect(threadSearchMatchKey(state.matches[0]!)).toBe('["env-a","thread-a"]'); @@ -108,6 +122,61 @@ it("merges successful environments and silently ignores failures", () => { registry.dispose(); }); +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"), + source: "user" as const, + snippet: "needle", + messageCreatedAt: null, + }); + // Keyed by the page's cursor. Pages 50..30 find nothing; 20 does. + const pages: Record = { + 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")] }, + }; + 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 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(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({ + query: "needle", + cursor: { before: 20 }, + excludedThreadIds: ["a"], + }); + search.loadMore(registry, key); + expect(threadIds()).toEqual(["a", "b", "c"]); + expect(state()).toMatchObject({ hasMore: false, partial: 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..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, @@ -9,7 +10,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, @@ -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 @@ -52,6 +56,10 @@ 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; + /** 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; @@ -117,11 +125,21 @@ 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, + partial: false, + rows: EMPTY_SEARCH_ROWS, + }; } const [environmentIds, query, scope = {}] = parsedKey.value; @@ -131,6 +149,8 @@ export function createThreadSearchResultsAtomFamily(options: { const matches: EnvironmentThreadSearchMatch[] = []; const rows: Array = []; let isLoading = false; + let hasMore = false; + let partial = false; for (const environmentId of environmentIds) { const before = options.olderSettledBefore @@ -162,9 +182,56 @@ export function createThreadSearchResultsAtomFamily(options: { }); } } + // 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 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, + 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; + if (nextValue.matches.length > 0) satisfied = true; + else emptyPages += 1; + } + hasMore ||= cursor !== undefined; } - return { matches, isLoading, rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows }; + return { + matches, + isLoading, + hasMore, + partial, + rows: rows.length === 0 ? EMPTY_SEARCH_ROWS : rows, + }; }).pipe(Atom.withLabel(`${options.labelPrefix}:${key}`)), ); const rowsAtom = Atom.family((rowsKey: string) => { @@ -182,6 +249,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/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..563fc42866c42 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -3,7 +3,12 @@ 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 holds per terminal; older or newer output is paged in. */ +export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 4 * 1024 * 1024; +/** 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; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check( @@ -69,6 +74,31 @@ export const TerminalWriteInput = Schema.Struct({ }); export type TerminalWriteInput = Schema.Codec.Encoded; +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.optional(HistoryOffsetSchema), + after: Schema.optional(HistoryOffsetSchema), +}); +export type TerminalHistoryInput = Schema.Codec.Encoded; + +export const TerminalHistoryPage = Schema.Struct({ + data: Schema.String, + /** 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; + export const TerminalResizeInput = Schema.Struct({ ...TerminalSessionInput.fields, cols: TerminalColsSchema, @@ -96,7 +126,12 @@ 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 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), label: Schema.String.check(Schema.isMaxLength(128)), @@ -162,6 +197,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({ diff --git a/packages/contracts/src/threadSearch.ts b/packages/contracts/src/threadSearch.ts index 42c87ebb610cd..0de32b8d005c4 100644 --- a/packages/contracts/src/threadSearch.ts +++ b/packages/contracts/src/threadSearch.ts @@ -15,14 +15,29 @@ 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. +/** 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)), +}); +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).check(Schema.isMaxLength(THREAD_SEARCH_MAX_EXCLUDED_THREADS)), + ), }); export type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type; @@ -48,6 +63,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;