Skip to content
TypeScript

perf(client): find unread terminal chunks from the tail (#23779)

Utkarsh Patil8cb9182021bc
diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts
index 5c4f8422c1f..df4d2ee0395 100644
--- a/packages/client-runtime/src/state/terminalOutput.ts
+++ b/packages/client-runtime/src/state/terminalOutput.ts
@@ -286,9 +286,14 @@ export function readTerminalOutputUpdate(
return { type: "reset", data: terminalOutputText(output), cursor: nextCursor };
}
- const appended = output.chunks.filter(
- (chunk) => chunk.startOffset + chunk.data.length > cursor.offset,
- );
+ // Appends and compaction preserve offset order, so unread chunks form a suffix.
+ let firstUnread = output.chunks.length;
+ while (firstUnread > 0) {
+ const chunk = output.chunks[firstUnread - 1]!;
+ if (!(chunk.startOffset + chunk.data.length > cursor.offset)) break;
+ firstUnread -= 1;
+ }
+ const appended = output.chunks.slice(firstUnread);
if (appended.length === 0) {
return { type: "none", cursor: nextCursor };
}
diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts
index a04504e00ee..7cbcd14f819 100644
--- a/packages/client-runtime/src/state/terminalSession.test.ts
+++ b/packages/client-runtime/src/state/terminalSession.test.ts
@@ -166,6 +166,46 @@ describe("terminal session reducers", () => {
expect(readTerminalOutputUpdate(state.output, update.cursor).type).toBe("none");
});
+ it("bounds historical chunk inspection when reading new tail output", () => {
+ let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
+ type: "snapshot",
+ snapshot: { ...BASE_SNAPSHOT, history: "" },
+ });
+ for (let index = 0; index < 512; index += 1) {
+ state = applyTerminalAttachStreamEvent(state, {
+ type: "output",
+ threadId: TARGET.threadId,
+ terminalId: TARGET.terminalId,
+ data: "history\r\n",
+ });
+ }
+ const cursor = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR).cursor;
+ const next = applyTerminalAttachStreamEvent(state, {
+ type: "output",
+ threadId: TARGET.threadId,
+ terminalId: TARGET.terminalId,
+ data: "latest\r\n",
+ });
+ let historicalChunkReads = 0;
+ const chunks = next.output.chunks.map((chunk, index) =>
+ index < state.output.chunks.length
+ ? {
+ ...chunk,
+ get startOffset() {
+ historicalChunkReads += 1;
+ return chunk.startOffset;
+ },
+ }
+ : chunk,
+ );
+
+ expect(readTerminalOutputUpdate({ ...next.output, chunks }, cursor)).toMatchObject({
+ type: "append",
+ data: "latest\r\n",
+ });
+ expect(historicalChunkReads).toBeLessThanOrEqual(2);
+ });
+
it("preserves the byte-limited tail and resets a cursor before a partially trimmed chunk", () => {
const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
type: "snapshot",