feat(ssh): bound relay PTY output end to end (#11005)

* docs: design SSH relay PTY backpressure

* fix(ssh): bound relay frame decoding

* fix(relay): bound PTY output publication

* fix(ssh): bound PTY model admission

* fix(ssh): settle closed model admissions

* feat(ssh): negotiate bounded PTY consumer sessions

* fix(ssh): fence exit on renderer settlement

* feat(ssh): track PTY source credit end to end

* fix(ssh): recover bounded PTY output across reconnect

* feat(ssh): complete relay PTY output backpressure

* fix(ssh): close final PTY source credit races

* docs(ssh): record final backpressure validation

* feat(ssh): complete relay PTY source-credit lifecycle

* test(ssh): complete provider notification fixture

* fix(ssh): preserve terminal source credit across rotation

* fix(ssh): fail closed on recovery cancellation

* fix(ssh): prioritize mux control writes after drain

* fix(ssh): retire canceled relay restore deliveries

* fix(ssh): order exit cancellation cleanup

* fix(ssh): gate provisional source activation

* test(ssh): register mux drain-priority coverage

* fix(ssh): type stale owner recovery mismatches

* fix(ssh): close projection replacement races

* fix(relay): contain streaming edge failures

* fix(ssh): secure relay endpoint credentials

* docs(ssh): reconcile final backpressure lifecycle

* fix(ssh): bound main IPC output lifecycle

* fix(ssh): close recovery ownership gaps

* docs(ssh): record exact artifact validation

* fix(ssh): reject reclaimed snapshot replacements

* fix(ssh): fence model admission across reconnect

* fix(ssh): contain migration failure per PTY

* docs(ssh): record final exact-head validation

* test(ssh): align deploy fixtures with credential publication

* feat(ssh): add per-target bounded output setting

* fix(ssh): close source recovery review gaps

* fix(ssh): latch source credit environment override

* feat(ssh): make PTY source credit the default

* docs(ssh): record always-on relay validation

* docs(ssh): bind validation to current main

* test(ssh): grant source credit in IPC fixture

* test(ssh): grant source credit in fake relay

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
Jinjing
2026-07-29 17:03:15 -07:00
committed by GitHub
co-authored by OrcaWin
parent c676b6aa3b
commit 5f7807497e
189 changed files with 34164 additions and 2410 deletions
+137 -25
View File
@@ -16,6 +16,13 @@ import { parseFileUriPathParts } from '../daemon/osc7-file-uri'
import type { AgentStatus } from '../../shared/agent-detection'
import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges'
import type { TerminalOscColorQueryReplyColors } from '../../shared/terminal-osc-color-reply'
import type { TerminalOutputSourceRange } from '../../shared/terminal-output-source-range'
import type {
RemoteTerminalSourceRangeConsumerHooks,
RemoteTerminalSourceRangeReplacementPublication,
RemoteTerminalSourceRangeReplacementReservation,
RemoteTerminalSourceRangeStreamIdentity
} from './remote-terminal-source-range-consumer'
import {
createTerminalTitleTracker,
stripBrailleSpinnerGlyphs,
@@ -1431,6 +1438,19 @@ type RuntimeHeadlessTerminal = {
writeChain: Promise<void>
}
export type RuntimePtyDataAdmission = Readonly<{
sequence: number
completion: Promise<void>
}>
export type RuntimeTerminalDataMeta = Readonly<{
seq?: number
rawLength?: number
transformed?: boolean
cwd?: string
sourceRanges?: readonly TerminalOutputSourceRange[]
}>
type RuntimeVisibleTerminalState = {
lines: string[]
isAlternateScreen: boolean
@@ -2669,13 +2689,10 @@ export class OrcaRuntimeService {
// without polling. Keyed by ptyId for O(1) lookup per data event.
private dataListeners = new Map<
string,
Set<
(
data: string,
meta?: { seq?: number; rawLength?: number; transformed?: boolean; cwd?: string }
) => void
>
Set<(data: string, meta?: RuntimeTerminalDataMeta) => void>
>()
private remoteTerminalSourceRangeConsumerHooks: RemoteTerminalSourceRangeConsumerHooks | null =
null
// Why: startup draft paste can subscribe after the agent already emitted its
// ready marker. Keep a bounded raw buffer so fast startup output is replayed.
private recentPtyOutputById = new Map<string, RecentPtyOutputBuffer>()
@@ -8616,16 +8633,49 @@ export class OrcaRuntimeService {
}
}
resetPtyModelAfterMigrationFailure(ptyId: string): void {
this.providerSnapshotPreferredPtys.add(ptyId)
this.disposeHeadlessTerminal(ptyId)
}
/**
* Handles incoming data from a PTY process, running agent detection,
* updating terminal tail buffers, and triggering foreground agent refreshes.
*/
acceptPtyDataBounded(
ptyId: string,
data: string,
at: number,
sequenceChars = data.length,
transformed = false,
sourceRanges?: readonly TerminalOutputSourceRange[]
): RuntimePtyDataAdmission {
let completion: Promise<void> | null = null
const sequence = this.onPtyData(
ptyId,
data,
at,
sequenceChars,
transformed,
(receipt) => {
completion = receipt
},
sourceRanges
)
if (!completion) {
throw new Error('PTY model admission receipt was not captured')
}
return Object.freeze({ sequence, completion })
}
onPtyData(
ptyId: string,
data: string,
at: number,
sequenceChars = data.length,
transformed = false
transformed = false,
captureModelReceipt?: (completion: Promise<void>) => void,
sourceRanges?: readonly TerminalOutputSourceRange[]
): number {
const outputSequence = (this.ptyOutputSequenceById.get(ptyId) ?? 0) + sequenceChars
this.ptyOutputSequenceById.set(ptyId, outputSequence)
@@ -8664,7 +8714,13 @@ export class OrcaRuntimeService {
// applyTrackedPtyTitle) in byte order, superseding main's inline
// extractLastOscTitleForPty block (#7880/#7852 title/status semantics are
// preserved via the tracker + detectAgentStatusFromTitle path).
this.trackHeadlessTerminalData(ptyId, data, outputSequence, forwardQueryReplies)
const modelCompletion = this.trackHeadlessTerminalData(
ptyId,
data,
outputSequence,
forwardQueryReplies
)
captureModelReceipt?.(modelCompletion)
const pty = this.getOrCreatePtyWorktreeRecord(ptyId)
const ptyTailBefore = pty
@@ -8846,7 +8902,8 @@ export class OrcaRuntimeService {
seq: outputSequence,
rawLength: sequenceChars,
...(transformed ? { transformed: true } : {}),
...(cwdChanged && cwd !== null ? { cwd } : {})
...(cwdChanged && cwd !== null ? { cwd } : {}),
...(sourceRanges && sourceRanges.length > 0 ? { sourceRanges } : {})
}
for (const listener of listeners) {
try {
@@ -9721,14 +9778,71 @@ export class OrcaRuntimeService {
subscribeToTerminalData(
ptyId: string,
listener: (
data: string,
meta?: { seq?: number; rawLength?: number; transformed?: boolean; cwd?: string }
) => void
listener: (data: string, meta?: RuntimeTerminalDataMeta) => void
): () => void {
return addListenerToMap(this.dataListeners, ptyId, listener)
}
setRemoteTerminalSourceRangeConsumerHooks(
hooks: RemoteTerminalSourceRangeConsumerHooks | null
): void {
this.remoteTerminalSourceRangeConsumerHooks = hooks
}
attachRemoteTerminalSourceRangeConsumer(
identity: RemoteTerminalSourceRangeStreamIdentity
): boolean {
return this.remoteTerminalSourceRangeConsumerHooks?.attach(identity) ?? false
}
settleRemoteTerminalSourceRanges(
identity: RemoteTerminalSourceRangeStreamIdentity,
ranges: readonly TerminalOutputSourceRange[]
): void {
this.remoteTerminalSourceRangeConsumerHooks?.settle(identity, ranges)
}
reserveRemoteTerminalSourceRangeReplacement(
identity: RemoteTerminalSourceRangeStreamIdentity,
requiredSeq: number,
reason: string
): RemoteTerminalSourceRangeReplacementReservation | null {
return (
this.remoteTerminalSourceRangeConsumerHooks?.reserveReplacement(
identity,
requiredSeq,
reason
) ?? null
)
}
commitRemoteTerminalSourceRangeReplacement(
reservation: RemoteTerminalSourceRangeReplacementReservation,
publication: RemoteTerminalSourceRangeReplacementPublication
): boolean {
return (
this.remoteTerminalSourceRangeConsumerHooks?.commitReplacement(reservation, publication) ??
false
)
}
rollbackRemoteTerminalSourceRangeReplacement(
reservation: RemoteTerminalSourceRangeReplacementReservation,
reason: string
): boolean {
return (
this.remoteTerminalSourceRangeConsumerHooks?.rollbackReplacement(reservation, reason) ?? false
)
}
cancelRemoteTerminalSourceRanges(
identity: RemoteTerminalSourceRangeStreamIdentity,
ranges: readonly TerminalOutputSourceRange[],
reason: string
): void {
this.remoteTerminalSourceRangeConsumerHooks?.cancel(identity, ranges, reason)
}
/** Set by pty IPC: fires when a PTY gains/loses remote view subscribers so
* the daemon background mark (keep-tail stream thinning) can resync — a
* live mobile/web view consumes raw bytes and must never be thinned, even
@@ -10186,19 +10300,17 @@ export class OrcaRuntimeService {
data: string,
outputSequence: number,
forwardQueryReplies = false
): void {
): Promise<void> {
const state = this.getOrCreateHeadlessTerminal(ptyId)
state.writeChain = state.writeChain
.then(async () => {
// Why: the ingestion-time ownership decision is closed over this
// chain link; async scheduling cannot retroactively change it.
await state.emulator.write(data, { forwardQueryReplies })
state.outputSequence = outputSequence
})
.catch(() => {
// Best-effort state tracking; live streaming must continue even if
// xterm rejects a malformed or raced write during shutdown.
})
const completion = state.writeChain.then(async () => {
// Why: the ingestion-time ownership decision is closed over this
// chain link; async scheduling cannot retroactively change it.
await state.emulator.write(data, { forwardQueryReplies })
state.outputSequence = outputSequence
})
// Legacy callers remain best-effort; bounded SSH admission observes the raw receipt.
state.writeChain = completion.catch(() => {})
return completion
}
/** Shared factory for the per-PTY runtime emulators (seed, hydration, and
@@ -0,0 +1,44 @@
import type { TerminalOutputSourceRange } from '../../shared/terminal-output-source-range'
export type RemoteTerminalSourceRangeStreamIdentity = Readonly<{
ptyId: string
consumerId: string
streamGeneration: string
}>
export type RemoteTerminalSourceRangeReplacementReservation = Readonly<{
reservationId: string
identity: RemoteTerminalSourceRangeStreamIdentity
requiredSeq: number
}>
export type RemoteTerminalSourceRangeReplacementPublication = Readonly<{
source: 'headless' | 'renderer'
seq: number
}>
export type RemoteTerminalSourceRangeConsumerHooks = {
attach: (identity: RemoteTerminalSourceRangeStreamIdentity) => boolean
settle: (
identity: RemoteTerminalSourceRangeStreamIdentity,
ranges: readonly TerminalOutputSourceRange[]
) => void
reserveReplacement: (
identity: RemoteTerminalSourceRangeStreamIdentity,
requiredSeq: number,
reason: string
) => RemoteTerminalSourceRangeReplacementReservation | null
commitReplacement: (
reservation: RemoteTerminalSourceRangeReplacementReservation,
publication: RemoteTerminalSourceRangeReplacementPublication
) => boolean
rollbackReplacement: (
reservation: RemoteTerminalSourceRangeReplacementReservation,
reason: string
) => boolean
cancel: (
identity: RemoteTerminalSourceRangeStreamIdentity,
ranges: readonly TerminalOutputSourceRange[],
reason: string
) => void
}
+378 -82
View File
@@ -1,5 +1,6 @@
/* oxlint-disable max-lines -- Why: terminal RPC methods are co-located for discoverability; splitting would scatter related handlers across files. */
import { z } from 'zod'
import { randomUUID } from 'node:crypto'
import {
InvalidArgumentError,
defineMethod,
@@ -19,6 +20,7 @@ import {
} from '../../../../shared/terminal-stream-protocol'
import {
iterateTerminalOutputFrameChunks,
sliceTerminalOutputSourceRanges,
type TerminalOutputFrameChunk,
type TerminalOutputMeta
} from '../terminal-output-frame-chunks'
@@ -61,6 +63,13 @@ import {
TERMINAL_OUTPUT_BATCH_MAX_BYTES
} from '../../../../shared/terminal-multiplex-flow-control'
import { drainTerminalMultiplexRoundRobin } from '../terminal-multiplex-round-robin'
import type { TerminalSourceRangeLedger } from '../terminal-source-range-ledger'
import { TerminalSourceRangeRegistry } from '../terminal-source-range-registry'
import {
sameTerminalOutputSourceIdentity,
type TerminalOutputSourceRange
} from '../../../../shared/terminal-output-source-range'
import type { RemoteTerminalSourceRangeReplacementReservation } from '../../remote-terminal-source-range-consumer'
const REQUESTED_SNAPSHOT_BYTE_BUDGET = 2 * 1024 * 1024
const TERMINAL_OUTPUT_FLUSH_MS = 5
@@ -112,6 +121,11 @@ type TerminalMultiplexStream = {
client: TerminalViewportClient | undefined
isMobile: boolean
ackOutput: boolean
ackOutputSourceRanges: boolean
streamGeneration: string
sourceRangeLedger: TerminalSourceRangeLedger | null
sourceRangeConsumerAttached: boolean
sourceRangeReplacement: RemoteTerminalSourceRangeReplacementReservation | null
ackInFlightBytes: number
ackWindowBytes: number
supportsDesktopViewportClaims: boolean
@@ -157,6 +171,7 @@ function createTerminalOutputBatcher(onFlush: (data: string, meta?: TerminalOutp
let lastSeq: number | undefined
let pendingCwd: string | undefined
let pendingRawLength = 0
let pendingSourceRanges: TerminalOutputSourceRange[] = []
let timer: ReturnType<typeof setTimeout> | null = null
const clearTimer = (): void => {
@@ -174,10 +189,13 @@ function createTerminalOutputBatcher(onFlush: (data: string, meta?: TerminalOutp
}
const data = chunks.length === 1 ? chunks[0]! : chunks.join('')
const meta =
typeof lastSeq === 'number' || pendingCwd !== undefined
typeof lastSeq === 'number' || pendingCwd !== undefined || pendingSourceRanges.length > 0
? {
...(typeof lastSeq === 'number' ? { seq: lastSeq, rawLength: pendingRawLength } : {}),
...(pendingCwd !== undefined ? { cwd: pendingCwd } : {})
...(pendingCwd !== undefined ? { cwd: pendingCwd } : {}),
...(pendingSourceRanges.length > 0
? { sourceRanges: Object.freeze(pendingSourceRanges.slice()) }
: {})
}
: undefined
chunks = []
@@ -185,6 +203,7 @@ function createTerminalOutputBatcher(onFlush: (data: string, meta?: TerminalOutp
lastSeq = undefined
pendingCwd = undefined
pendingRawLength = 0
pendingSourceRanges = []
onFlush(data, meta)
}
@@ -199,12 +218,26 @@ function createTerminalOutputBatcher(onFlush: (data: string, meta?: TerminalOutp
onFlush(data, { ...meta, rawLength, transformed: true })
return
}
const nextSourceRanges = meta?.sourceRanges ?? []
const lastSourceRange = pendingSourceRanges.at(-1)
const firstNextSourceRange = nextSourceRanges[0]
if (
chunks.length > 0 &&
(pendingSourceRanges.length > 0 !== nextSourceRanges.length > 0 ||
(lastSourceRange &&
firstNextSourceRange &&
(!sameTerminalOutputSourceIdentity(lastSourceRange, firstNextSourceRange) ||
lastSourceRange.displayEnd !== firstNextSourceRange.displayStart)))
) {
flush()
}
if (meta?.cwd !== undefined) {
flush()
pendingCwd = meta.cwd
}
chunks.push(data)
pendingRawLength += rawLength
pendingSourceRanges.push(...nextSourceRanges)
const remainingBudget = Math.max(1, TERMINAL_OUTPUT_BATCH_MAX_BYTES - bytes)
const measurement = measureTerminalStreamByteLength(data, {
stopAfterBytes: remainingBudget
@@ -231,6 +264,7 @@ function createTerminalOutputBatcher(onFlush: (data: string, meta?: TerminalOutp
chunks = []
bytes = 0
pendingRawLength = 0
pendingSourceRanges = []
}
}
}
@@ -380,22 +414,38 @@ function appendPendingMultiplexOutput(
function getOutputAfterSnapshotSeq(
chunk: TerminalOutputChunk,
snapshotSeq: number | undefined
): string | null {
): TerminalOutputChunk | null {
if (
typeof snapshotSeq !== 'number' ||
typeof chunk.meta?.seq !== 'number' ||
typeof chunk.meta.rawLength !== 'number'
) {
return chunk.data
return chunk
}
if (chunk.meta.seq <= snapshotSeq) {
return null
}
const chunkStartSeq = chunk.meta.seq - chunk.meta.rawLength
if (chunkStartSeq >= snapshotSeq) {
return chunk.data
return chunk
}
if (chunk.meta.transformed) {
return null
}
const offset = snapshotSeq - chunkStartSeq
return {
data: chunk.data.slice(offset),
bytes: chunk.bytes,
meta: {
...chunk.meta,
rawLength: chunk.meta.rawLength - offset,
sourceRanges: sliceTerminalOutputSourceRanges(
chunk.meta.sourceRanges,
offset,
chunk.data.length
)
}
}
return chunk.data.slice(snapshotSeq - chunkStartSeq)
}
function stripSnapshotBoundaryQuerySuffixes(
@@ -551,36 +601,45 @@ async function serializeBudgetedRequestedSnapshot(
}
function sendSnapshotFrames(
sendFrame: (opcode: TerminalStreamOpcode, payload?: Uint8Array<ArrayBufferLike>) => void,
sendFrame: (
opcode: TerminalStreamOpcode,
payload?: Uint8Array<ArrayBufferLike>
) => boolean | void,
options: SnapshotFrameOptions
): { bytes: number; chunks: number } {
sendFrame(
TerminalStreamOpcode.SnapshotStart,
encodeTerminalStreamJson({
kind: options.kind,
cols: options.cols,
rows: options.rows,
requestId: options.requestId,
displayMode: options.displayMode,
reason: options.reason,
seq: options.seq,
cwd: options.cwd,
source: options.source,
oscLinks: options.oscLinks,
pendingEscapeTailAnsi: options.pendingEscapeTailAnsi,
truncated: options.truncated === true,
truncatedByByteBudget: options.truncatedByByteBudget === true
})
)
): { bytes: number; chunks: number; published: boolean } {
if (
sendFrame(
TerminalStreamOpcode.SnapshotStart,
encodeTerminalStreamJson({
kind: options.kind,
cols: options.cols,
rows: options.rows,
requestId: options.requestId,
displayMode: options.displayMode,
reason: options.reason,
seq: options.seq,
cwd: options.cwd,
source: options.source,
oscLinks: options.oscLinks,
pendingEscapeTailAnsi: options.pendingEscapeTailAnsi,
truncated: options.truncated === true,
truncatedByByteBudget: options.truncatedByByteBudget === true
})
) === false
) {
return { bytes: 0, chunks: 0, published: false }
}
let chunks = 0
let bytes = 0
for (const chunk of iterateTerminalStreamTextPayloads(options.data)) {
if (sendFrame(TerminalStreamOpcode.SnapshotChunk, chunk) === false) {
return { bytes, chunks, published: false }
}
chunks++
bytes += chunk.byteLength
sendFrame(TerminalStreamOpcode.SnapshotChunk, chunk)
}
sendFrame(TerminalStreamOpcode.SnapshotEnd)
return { bytes, chunks }
const published = sendFrame(TerminalStreamOpcode.SnapshotEnd) !== false
return { bytes, chunks, published }
}
async function serializeBudgetedMobileSnapshot(
@@ -953,14 +1012,24 @@ const TerminalMultiplexSubscribeFrame = TerminalHandle.extend({
capabilities: z
.object({
ackOutput: z.literal(1).optional(),
ackOutputSourceRanges: z.literal(1).optional(),
desktopViewportClaims: z.literal(1).optional()
})
.optional()
})
const TerminalMultiplexAckFrame = z.object({
bytes: z.number().int().nonnegative()
})
const TerminalMultiplexLegacyAckFrame = z
.object({
bytes: z.number().int().nonnegative()
})
.strict()
const TerminalMultiplexSourceRangeAckFrame = z
.object({
streamGeneration: z.string().min(1),
ackedEndByte: z.number().int().nonnegative()
})
.strict()
const TerminalMultiplexSnapshotRequestFrame = z.object({
requestId: z.number().int().positive().optional(),
@@ -1514,6 +1583,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
let closed = false
let cursor = 0
const streams = new Map<number, TerminalMultiplexStream>()
const sourceRangeRegistry = new TerminalSourceRangeRegistry()
const pendingPtyWaitControllers = new Map<number, Set<AbortController>>()
let ackTotalInFlightBytes = 0
let ackTotalWindowBytes = TERMINAL_MULTIPLEX_ACK_TOTAL_INITIAL_WINDOW_BYTES
@@ -1526,9 +1596,11 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
streamId: number,
opcode: TerminalStreamOpcode,
payload: Uint8Array<ArrayBufferLike> = new Uint8Array(),
seq?: number
seq?: number,
onRejected?: () => void
): boolean => {
if (closed) {
onRejected?.()
return false
}
// Why: a seq-less Output chunk must carry sentinel 0, not the control-frame cursor, or it poisons the client's frame-drop tracker.
@@ -1540,10 +1612,12 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
encodeTerminalStreamFrame({ opcode, streamId, seq: resolvedSeq, payload })
)
} catch {
onRejected?.()
closeMultiplex()
return false
}
if (sent === false) {
onRejected?.()
// Why: false means the transport discarded this frame; reconnect is the only available retry boundary with an authoritative snapshot.
closeMultiplex()
return false
@@ -1577,22 +1651,43 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
}
return (
stream.ackInFlightBytes + bytes <= stream.ackWindowBytes &&
ackTotalInFlightBytes + bytes <= ackTotalWindowBytes
ackTotalInFlightBytes + bytes <= ackTotalWindowBytes &&
(!stream.ackOutputSourceRanges || stream.sourceRangeLedger?.canAccept(bytes) === true)
)
}
const sendAckGatedOutput = (
stream: TerminalMultiplexStream,
chunk: TerminalOutputFrameChunk
): boolean => {
const prepared = stream.ackOutputSourceRanges
? stream.sourceRangeLedger?.prepareAccept(
chunk.bytes.byteLength,
chunk.displayLength,
chunk.sourceRanges ?? [],
chunk.seq
)
: undefined
if (stream.ackOutputSourceRanges && prepared?.status !== 'ready') {
if (prepared?.status !== 'capacity') {
detachStream(stream.streamId, true)
}
return false
}
const admission = prepared?.status === 'ready' ? prepared.admission : undefined
const sent = sendFrame(
stream.streamId,
chunk.opcode ?? TerminalStreamOpcode.Output,
chunk.bytes,
chunk.seq
chunk.seq,
admission?.rollback
)
if (!sent) {
return false
}
if (admission && !admission.commit()) {
detachStream(stream.streamId, true)
return false
}
if (stream.ackOutput) {
stream.ackInFlightBytes += chunk.bytes.byteLength
ackTotalInFlightBytes += chunk.bytes.byteLength
@@ -1625,6 +1720,7 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
return
}
stream.ackRecoverySnapshotInFlight = true
let replacement: RemoteTerminalSourceRangeReplacementReservation | null = null
try {
const serialized = await serializeBudgetedRequestedSnapshot(runtime, stream.ptyId, 0)
if (closed || streams.get(stream.streamId) !== stream) {
@@ -1633,21 +1729,75 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
if (!serialized) {
throw new Error('Remote terminal recovery snapshot unavailable.')
}
if (
stream.ackOutputSourceRanges &&
(serialized.source === undefined || typeof serialized.seq !== 'number')
) {
throw new Error('Remote terminal recovery snapshot source identity unavailable.')
}
if (
stream.ackOutputSourceRanges &&
serialized.source !== undefined &&
typeof serialized.seq === 'number'
) {
replacement = runtime.reserveRemoteTerminalSourceRangeReplacement(
{
ptyId: stream.ptyId,
consumerId: stream.remoteDesktopSubscriptionKey,
streamGeneration: stream.streamGeneration
},
serialized.seq,
'ack-pending-overflow'
)
stream.sourceRangeReplacement = replacement
}
const displayMode = runtime.getMobileDisplayMode(stream.ptyId)
// Why: dropped ACK-pending output breaks live replay; send a fresh snapshot before resuming output.
sendSnapshotFrames((opcode, payload) => sendFrame(stream.streamId, opcode, payload), {
kind: 'scrollback',
cols: serialized.cols,
rows: serialized.rows,
displayMode,
reason: 'ack-pending-overflow',
seq: serialized.seq,
source: serialized.source,
truncatedByByteBudget: serialized.truncatedByByteBudget,
data: serialized.data
})
const publication = sendSnapshotFrames(
(opcode, payload) =>
!closed &&
streams.get(stream.streamId) === stream &&
sendFrame(stream.streamId, opcode, payload),
{
kind: 'scrollback',
cols: serialized.cols,
rows: serialized.rows,
displayMode,
reason: 'ack-pending-overflow',
seq: serialized.seq,
source: serialized.source,
truncatedByByteBudget: serialized.truncatedByByteBudget,
data: serialized.data
}
)
if (!publication.published) {
throw new Error('Remote terminal recovery snapshot was not published.')
}
if (closed || streams.get(stream.streamId) !== stream) {
throw new Error('Remote terminal recovery snapshot stream detached.')
}
const localReplacement = replacement
? typeof serialized.seq === 'number'
? stream.sourceRangeLedger?.planSourceRangeReplacement(serialized.seq)
: null
: null
if (replacement && !localReplacement) {
throw new Error('Remote terminal recovery source ledger replacement unavailable.')
}
if (
replacement &&
(!serialized.source ||
typeof serialized.seq !== 'number' ||
!runtime.commitRemoteTerminalSourceRangeReplacement(replacement, {
source: serialized.source,
seq: serialized.seq
}))
) {
throw new Error('Remote terminal recovery snapshot replacement was not accepted.')
}
localReplacement?.commit()
stream.sourceRangeReplacement = null
replacement = null
if (typeof serialized.seq === 'number') {
// Why: chunks queued before the snapshot serialized are already in it; replaying them would duplicate output.
const snapshotSeq = serialized.seq
const retained = stream.ackPendingOutput.filter(
(chunk) => !(typeof chunk.seq === 'number' && chunk.seq <= snapshotSeq)
@@ -1660,11 +1810,23 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
}
stream.ackPendingOutputOverflowed = false
} catch (error) {
if (replacement) {
if (stream.sourceRangeReplacement === replacement) {
stream.sourceRangeReplacement = null
runtime.rollbackRemoteTerminalSourceRangeReplacement(
replacement,
'ack-pending-overflow-unpublished'
)
}
replacement = null
}
if (closed || streams.get(stream.streamId) !== stream) {
return
}
sendStreamError(
stream.streamId,
error instanceof Error ? error.message : 'Remote terminal recovery snapshot failed.'
)
// Why: retrying the same failed recovery from finally creates an unbounded error loop.
detachStream(stream.streamId, true)
} finally {
if (streams.get(stream.streamId) === stream) {
@@ -1735,6 +1897,56 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
ackTotalInFlightBytes = Math.max(0, ackTotalInFlightBytes - acknowledged)
flushAllAckPendingOutput()
}
const acknowledgeSourceRanges = (
stream: TerminalMultiplexStream,
streamGeneration: string,
ackedEndByte: number
): void => {
if (!stream.ackOutputSourceRanges) {
return
}
const result = stream.sourceRangeLedger?.acknowledge(streamGeneration, ackedEndByte)
if (!result) {
return
}
if (result.status !== 'accepted') {
return
}
if (result.settled.length > 0) {
runtime.settleRemoteTerminalSourceRanges(
{
ptyId: stream.ptyId,
consumerId: stream.remoteDesktopSubscriptionKey,
streamGeneration: stream.streamGeneration
},
result.settled
)
}
acknowledgeOutput(stream, result.acknowledgedBytes)
}
const detachSourceRangeConsumer = (stream: TerminalMultiplexStream, reason: string): void => {
if (!stream.sourceRangeConsumerAttached) {
return
}
stream.sourceRangeConsumerAttached = false
const ledger = stream.sourceRangeLedger
stream.sourceRangeLedger = null
if (!ledger) {
return
}
const identity = {
ptyId: stream.ptyId,
consumerId: stream.remoteDesktopSubscriptionKey,
streamGeneration: stream.streamGeneration
}
const transfer = ledger.beginTransfer()
const ranges = transfer.frames.flatMap((frame) => frame.sourceRanges)
try {
runtime.cancelRemoteTerminalSourceRanges(identity, ranges, reason)
} finally {
transfer.commit()
}
}
const detachStream = (
streamId: number,
emitEnd: boolean,
@@ -1744,8 +1956,17 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
if (!stream) {
return
}
const replacement = stream.sourceRangeReplacement
stream.sourceRangeReplacement = null
if (replacement) {
runtime.rollbackRemoteTerminalSourceRangeReplacement(
replacement,
'stream-detached-replacement-aborted'
)
}
stream.outputBatcher.flush()
stream.outputBatcher.dispose()
detachSourceRangeConsumer(stream, 'stream-detached')
ackTotalInFlightBytes = Math.max(0, ackTotalInFlightBytes - stream.ackInFlightBytes)
stream.ackInFlightBytes = 0
stream.ackPendingOutput = []
@@ -1827,11 +2048,21 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
return
}
if (frame.opcode === TerminalStreamOpcode.Ack) {
const parsed = TerminalMultiplexAckFrame.safeParse(
decodeTerminalStreamJson<unknown>(frame.payload) ?? {}
)
if (parsed.success) {
acknowledgeOutput(stream, parsed.data.bytes)
const payload = decodeTerminalStreamJson<unknown>(frame.payload) ?? {}
if (stream.ackOutputSourceRanges) {
const parsed = TerminalMultiplexSourceRangeAckFrame.safeParse(payload)
if (parsed.success) {
acknowledgeSourceRanges(
stream,
parsed.data.streamGeneration,
parsed.data.ackedEndByte
)
}
} else {
const parsed = TerminalMultiplexLegacyAckFrame.safeParse(payload)
if (parsed.success) {
acknowledgeOutput(stream, parsed.data.bytes)
}
}
return
}
@@ -2024,12 +2255,12 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
// high-water, so covered bytes would render twice; tagged
// snapshots feed a side consumer and the live view still
// needs every buffered chunk.
const uncoveredData =
const uncovered =
typeof requestId === 'number'
? chunk.data
? chunk
: getOutputAfterSnapshotSeq(chunk, sentSnapshotOutputSeq)
if (uncoveredData) {
stream.outputBatcher.push(uncoveredData, chunk.meta)
if (uncovered) {
stream.outputBatcher.push(uncovered.data, uncovered.meta)
}
}
}
@@ -2140,6 +2371,23 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
detachStream(request.streamId, false)
const ptyId = leaf.ptyId
const remoteDesktopSubscriptionKey = `multiplex:${connectionId}:${request.streamId}`
const streamGeneration = randomUUID()
const requestedSourceRangeConsumer =
request.capabilities?.ackOutput === 1 && request.capabilities?.ackOutputSourceRanges === 1
const sourceRangeLedger = requestedSourceRangeConsumer
? sourceRangeRegistry.open(streamGeneration)
: null
const sourceRangeConsumerAttached =
sourceRangeLedger !== null &&
runtime.attachRemoteTerminalSourceRangeConsumer({
ptyId,
consumerId: remoteDesktopSubscriptionKey,
streamGeneration
})
if (!sourceRangeConsumerAttached) {
sourceRangeLedger?.close()
}
const stream: TerminalMultiplexStream = {
streamId: request.streamId,
terminal: request.terminal,
@@ -2147,13 +2395,18 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
client: request.client,
isMobile,
ackOutput: request.capabilities?.ackOutput === 1,
ackOutputSourceRanges: sourceRangeConsumerAttached,
streamGeneration,
sourceRangeLedger: sourceRangeConsumerAttached ? sourceRangeLedger : null,
sourceRangeConsumerAttached,
sourceRangeReplacement: null,
ackInFlightBytes: 0,
ackWindowBytes: TERMINAL_MULTIPLEX_ACK_STREAM_INITIAL_WINDOW_BYTES,
supportsDesktopViewportClaims: request.capabilities?.desktopViewportClaims === 1,
desktopClaimTail: Promise.resolve(true),
registeredRemoteDesktopDriver: false,
// Why: streamId is client-local, so key the width floor by connectionId or two connections sharing stream 1 for one PTY clobber each other's floor.
remoteDesktopSubscriptionKey: `multiplex:${connectionId}:${request.streamId}`,
remoteDesktopSubscriptionKey,
pendingRemoteDesktopViewport: null,
buffering: true,
ackPendingOutput: [],
@@ -2273,35 +2526,77 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
rows: serialized?.rows ?? size?.rows,
displayMode,
seq: layoutSeq,
...(stream.ackOutputSourceRanges
? {
streamGeneration: stream.streamGeneration,
capabilities: { ackOutputSourceRanges: 1 as const }
}
: {}),
truncated:
initialOutputOverflowed ||
(serialized ? read.truncated : isTerminalReadPayloadIncomplete(read))
})
sendSnapshotFrames((opcode, payload) => sendFrame(request.streamId, opcode, payload), {
kind: 'scrollback',
cols: serialized?.cols ?? size?.cols ?? 80,
rows: serialized?.rows ?? size?.rows ?? 24,
displayMode,
seq: snapshotFrameSeq,
cwd: serialized?.cwd,
truncated:
initialOutputOverflowed ||
(serialized ? read.truncated : isTerminalReadPayloadIncomplete(read)),
truncatedByByteBudget: serialized?.truncatedByByteBudget,
source: serialized?.source,
oscLinks: serialized?.oscLinks,
pendingEscapeTailAnsi: serialized?.pendingEscapeTailAnsi,
data: serialized?.data ?? (read.tail.length > 0 ? `${read.tail.join('\r\n')}\r\n` : '')
})
stream.sourceRangeReplacement =
stream.ackOutputSourceRanges &&
serialized?.source !== undefined &&
typeof serialized.seq === 'number'
? runtime.reserveRemoteTerminalSourceRangeReplacement(
{
ptyId,
consumerId: stream.remoteDesktopSubscriptionKey,
streamGeneration: stream.streamGeneration
},
serialized.seq,
'initial-snapshot'
)
: null
const snapshotPublication = sendSnapshotFrames(
(opcode, payload) => sendFrame(request.streamId, opcode, payload),
{
kind: 'scrollback',
cols: serialized?.cols ?? size?.cols ?? 80,
rows: serialized?.rows ?? size?.rows ?? 24,
displayMode,
seq: snapshotFrameSeq,
cwd: serialized?.cwd,
truncated:
initialOutputOverflowed ||
(serialized ? read.truncated : isTerminalReadPayloadIncomplete(read)),
truncatedByByteBudget: serialized?.truncatedByByteBudget,
source: serialized?.source,
oscLinks: serialized?.oscLinks,
pendingEscapeTailAnsi: serialized?.pendingEscapeTailAnsi,
data:
serialized?.data ?? (read.tail.length > 0 ? `${read.tail.join('\r\n')}\r\n` : '')
}
)
const replacement = stream.sourceRangeReplacement
stream.sourceRangeReplacement = null
if (replacement) {
const committed =
snapshotPublication.published &&
serialized?.source !== undefined &&
typeof serialized.seq === 'number' &&
runtime.commitRemoteTerminalSourceRangeReplacement(replacement, {
source: serialized.source,
seq: serialized.seq
})
if (!committed) {
runtime.rollbackRemoteTerminalSourceRangeReplacement(
replacement,
'initial-snapshot-unpublished'
)
}
}
// Why: baseline for resize re-stream gating; the client already rewrapped to these cols via the initial snapshot replay.
stream.lastResizeCols = serialized?.cols ?? size?.cols
stream.buffering = false
const pendingOutput = stream.pendingOutput.splice(0)
if (!initialOutputOverflowed) {
for (const chunk of pendingOutput) {
const uncoveredData = getOutputAfterSnapshotSeq(chunk, snapshotOutputSeq)
if (uncoveredData) {
stream.outputBatcher.push(uncoveredData, chunk.meta)
const uncovered = getOutputAfterSnapshotSeq(chunk, snapshotOutputSeq)
if (uncovered) {
stream.outputBatcher.push(uncovered.data, uncovered.meta)
}
}
}
@@ -2982,9 +3277,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
if (stableRendererSnapshot?.data.length) {
serialized = stableRendererSnapshot
const trailingOutput = pendingOutput.flatMap((item) => {
const data = getOutputAfterSnapshotSeq(item, stableRendererSnapshot.seq)
const output = getOutputAfterSnapshotSeq(item, stableRendererSnapshot.seq)
const seq = item.meta?.seq
return data && typeof seq === 'number' ? [{ data, seq }] : []
return output && typeof seq === 'number' ? [{ data: output.data, seq }] : []
})
runtime.replaceHeadlessTerminalFromRendererSnapshotForRecovery(
ptyId,
@@ -3118,8 +3413,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
}
if (!initialOutputOverflowed) {
for (const item of bufferedOutput) {
let uncoveredData = getOutputAfterSnapshotSeq(item, snapshotOutputSeq)
let uncoveredMeta = item.meta
const uncovered = getOutputAfterSnapshotSeq(item, snapshotOutputSeq)
let uncoveredData = uncovered?.data ?? null
let uncoveredMeta = uncovered?.meta
if (
uncoveredData &&
uncoveredData !== item.data &&
File diff suppressed because it is too large Load Diff
@@ -47,12 +47,13 @@ function* legacyIterateTerminalOutputFrameChunks(
yield {
opcode: TerminalStreamOpcode.OutputSpan,
bytes: encodeTerminalStreamJson({ data, rawLength, transformed: true }),
displayLength: data.length,
seq: meta?.seq
}
return
}
if (!legacyByteLengthExceeds(data, TERMINAL_STREAM_CHUNK_BYTES)) {
yield { bytes: encodeTerminalStreamText(data), seq: meta?.seq }
yield { bytes: encodeTerminalStreamText(data), displayLength: data.length, seq: meta?.seq }
return
}
const canPreserveChunkSeq = typeof meta?.seq === 'number' && rawLength === data.length
@@ -83,11 +84,18 @@ function* legacyIterateTerminalOutputFrameChunks(
if (nextChunk) {
if (shouldDelayFinalSeq) {
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text) }
yield {
bytes: encodeTerminalStreamText(delayedChunk.text),
displayLength: delayedChunk.text.length
}
}
delayedChunk = nextChunk
} else {
yield { bytes: encodeTerminalStreamText(nextChunk.text), seq: nextChunk.seq }
yield {
bytes: encodeTerminalStreamText(nextChunk.text),
displayLength: nextChunk.text.length,
seq: nextChunk.seq
}
}
}
}
@@ -99,17 +107,28 @@ function* legacyIterateTerminalOutputFrameChunks(
if (shouldDelayFinalSeq) {
if (finalChunk) {
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text) }
yield {
bytes: encodeTerminalStreamText(delayedChunk.text),
displayLength: delayedChunk.text.length
}
}
delayedChunk = finalChunk
}
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text), seq: meta.seq }
yield {
bytes: encodeTerminalStreamText(delayedChunk.text),
displayLength: delayedChunk.text.length,
seq: meta.seq
}
}
return
}
if (finalChunk) {
yield { bytes: encodeTerminalStreamText(finalChunk.text), seq: finalChunk.seq }
yield {
bytes: encodeTerminalStreamText(finalChunk.text),
displayLength: finalChunk.text.length,
seq: finalChunk.seq
}
}
}
@@ -4,6 +4,7 @@ import {
encodeTerminalStreamText
} from '../../../shared/terminal-stream-protocol'
import { TERMINAL_STREAM_CHUNK_BYTES } from '../../../shared/terminal-multiplex-flow-control'
import type { TerminalOutputSourceRange } from '../../../shared/terminal-output-source-range'
import { terminalStreamByteLength } from './terminal-stream-byte-length'
export type TerminalOutputMeta = {
@@ -11,12 +12,15 @@ export type TerminalOutputMeta = {
rawLength?: number
transformed?: boolean
cwd?: string
sourceRanges?: readonly TerminalOutputSourceRange[]
}
export type TerminalOutputFrameChunk = {
bytes: Uint8Array<ArrayBufferLike>
displayLength: number
seq?: number
opcode?: TerminalStreamOpcode
sourceRanges?: readonly TerminalOutputSourceRange[]
}
export const TERMINAL_STREAM_BYTE_PROBE_CODE_UNITS = 8 * 1024
@@ -55,12 +59,19 @@ export function* iterateTerminalOutputFrameChunks(
yield {
opcode: TerminalStreamOpcode.OutputSpan,
bytes: encodeTerminalStreamJson({ data, rawLength, transformed: true }),
seq: meta?.seq
displayLength: data.length,
seq: meta?.seq,
sourceRanges: meta?.sourceRanges
}
return
}
if (!exceedsTerminalStreamChunkBytes(data)) {
yield { bytes: encodeTerminalStreamText(data), seq: meta?.seq }
yield {
bytes: encodeTerminalStreamText(data),
displayLength: data.length,
seq: meta?.seq,
sourceRanges: meta?.sourceRanges
}
return
}
const canPreserveChunkSeq = typeof meta?.seq === 'number' && rawLength === data.length
@@ -109,11 +120,23 @@ export function* iterateTerminalOutputFrameChunks(
const nextChunk = takeChunk(index)
if (shouldDelayFinalSeq) {
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text) }
yield {
bytes: encodeTerminalStreamText(delayedChunk.text),
displayLength: delayedChunk.text.length
}
}
delayedChunk = nextChunk
} else {
yield { bytes: encodeTerminalStreamText(nextChunk.text), seq: nextChunk.seq }
yield {
bytes: encodeTerminalStreamText(nextChunk.text),
displayLength: nextChunk.text.length,
seq: nextChunk.seq,
sourceRanges: sliceTerminalOutputSourceRanges(
meta?.sourceRanges,
chunkStart - nextChunk.text.length,
chunkStart
)
}
}
}
chunkBytes += partBytes
@@ -124,10 +147,65 @@ export function* iterateTerminalOutputFrameChunks(
if (shouldDelayFinalSeq) {
// Why: only the final frame can safely carry the high-water mark when rawLength can't map back to UTF-16 offsets.
if (delayedChunk) {
yield { bytes: encodeTerminalStreamText(delayedChunk.text) }
yield {
bytes: encodeTerminalStreamText(delayedChunk.text),
displayLength: delayedChunk.text.length
}
}
yield {
bytes: encodeTerminalStreamText(finalChunk.text),
displayLength: finalChunk.text.length,
seq: meta.seq
}
yield { bytes: encodeTerminalStreamText(finalChunk.text), seq: meta.seq }
return
}
yield { bytes: encodeTerminalStreamText(finalChunk.text), seq: finalChunk.seq }
yield {
bytes: encodeTerminalStreamText(finalChunk.text),
displayLength: finalChunk.text.length,
seq: finalChunk.seq,
sourceRanges: sliceTerminalOutputSourceRanges(
meta?.sourceRanges,
data.length - finalChunk.text.length,
data.length
)
}
}
export function sliceTerminalOutputSourceRanges(
sourceRanges: readonly TerminalOutputSourceRange[] | undefined,
displayStartOffset: number,
displayEndOffset: number
): readonly TerminalOutputSourceRange[] | undefined {
if (!sourceRanges || sourceRanges.length === 0) {
return undefined
}
const baseDisplayStart = sourceRanges[0]!.displayStart
const sliceStart = baseDisplayStart + displayStartOffset
const sliceEnd = baseDisplayStart + displayEndOffset
const selected: TerminalOutputSourceRange[] = []
for (const range of sourceRanges) {
const start = Math.max(sliceStart, range.displayStart)
const end = Math.min(sliceEnd, range.displayEnd)
if (end <= start) {
continue
}
if (!range.splittable && (start !== range.displayStart || end !== range.displayEnd)) {
throw new Error('terminal_source_range_indivisible_split')
}
const sourceStartSu = range.sourceStartSu + (start - range.displayStart)
selected.push(
Object.freeze({
...range,
displayStart: start,
displayEnd: end,
sourceStartSu,
sourceEndSu: sourceStartSu + (end - start),
transform: Object.freeze({
...range.transform,
rawLengthSu: end - start
})
})
)
}
return Object.freeze(selected)
}
@@ -0,0 +1,96 @@
import { describe, expect, it } from 'vitest'
import { TERMINAL_STREAM_CHUNK_BYTES } from '../../../shared/terminal-multiplex-flow-control'
import type { TerminalOutputSourceRange } from '../../../shared/terminal-output-source-range'
import { iterateTerminalOutputFrameChunks } from './terminal-output-frame-chunks'
function range(overrides: Partial<TerminalOutputSourceRange>): TerminalOutputSourceRange {
return {
id: 'pty-1',
spanId: 'span-1',
providerGeneration: 2,
clientGeneration: 3,
ownerGeneration: 4,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'token-1',
sourceStartSu: 0,
sourceEndSu: 1,
displayStart: 0,
displayEnd: 1,
splittable: true,
transform: { transformed: false, rawLengthSu: 1, scalarSafe: true },
...overrides
}
}
describe('terminal output frame source ranges', () => {
it('maps encoded chunk boundaries to exact ordered source subranges', () => {
const data = 'a'.repeat(TERMINAL_STREAM_CHUNK_BYTES + 2)
const frames = Array.from(
iterateTerminalOutputFrameChunks(data, {
seq: data.length,
rawLength: data.length,
sourceRanges: [
range({
sourceEndSu: TERMINAL_STREAM_CHUNK_BYTES - 1,
displayEnd: TERMINAL_STREAM_CHUNK_BYTES - 1,
transform: {
transformed: false,
rawLengthSu: TERMINAL_STREAM_CHUNK_BYTES - 1,
scalarSafe: true
}
}),
range({
spanId: 'span-2',
sourceStartSu: TERMINAL_STREAM_CHUNK_BYTES - 1,
sourceEndSu: data.length,
displayStart: TERMINAL_STREAM_CHUNK_BYTES - 1,
displayEnd: data.length,
transform: {
transformed: false,
rawLengthSu: data.length - TERMINAL_STREAM_CHUNK_BYTES + 1,
scalarSafe: true
}
})
]
})
)
expect(frames).toHaveLength(2)
expect(frames[0]?.sourceRanges).toEqual([
expect.objectContaining({
spanId: 'span-1',
sourceStartSu: 0,
sourceEndSu: TERMINAL_STREAM_CHUNK_BYTES - 1
}),
expect.objectContaining({
spanId: 'span-2',
sourceStartSu: TERMINAL_STREAM_CHUNK_BYTES - 1,
sourceEndSu: TERMINAL_STREAM_CHUNK_BYTES
})
])
expect(frames[1]?.sourceRanges).toEqual([
expect.objectContaining({
spanId: 'span-2',
sourceStartSu: TERMINAL_STREAM_CHUNK_BYTES,
sourceEndSu: data.length
})
])
})
it('keeps transformed source ranges indivisible', () => {
const sourceRange = range({
sourceEndSu: 9,
displayEnd: 3,
splittable: false,
transform: { transformed: true, rawLengthSu: 9, scalarSafe: false }
})
const [frame] = iterateTerminalOutputFrameChunks('xyz', {
seq: 9,
rawLength: 9,
transformed: true,
sourceRanges: [sourceRange]
})
expect(frame?.sourceRanges).toEqual([sourceRange])
})
})
@@ -0,0 +1,332 @@
import { describe, expect, it, vi } from 'vitest'
import type { TerminalOutputSourceRange } from '../../../shared/terminal-output-source-range'
import {
TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES,
TerminalSourceRangeLedger
} from './terminal-source-range-ledger'
import { TerminalSourceRangeRegistry } from './terminal-source-range-registry'
function range(overrides: Partial<TerminalOutputSourceRange> = {}): TerminalOutputSourceRange {
return {
id: 'pty-1',
spanId: 'span-1',
providerGeneration: 4,
clientGeneration: 2,
ownerGeneration: 3,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'token-1',
sourceStartSu: 0,
sourceEndSu: 4,
displayStart: 0,
displayEnd: 4,
splittable: true,
transform: { transformed: false, rawLengthSu: 4, scalarSafe: true },
...overrides
}
}
describe('TerminalSourceRangeLedger', () => {
it('advances partial byte credit without settling its covering source frame', () => {
const release = vi.fn()
const ledger = new TerminalSourceRangeLedger('generation-1', {
canReserve: () => true,
reserve: () => true,
release,
close: () => {}
})
ledger.accept(100, 100, [
range({
sourceEndSu: 100,
displayEnd: 100,
transform: { transformed: false, rawLengthSu: 100, scalarSafe: true }
})
])
expect(ledger.acknowledge('stale-generation', 40)).toEqual({
status: 'stale-generation',
settled: []
})
expect(ledger.acknowledge('generation-1', 40)).toEqual({
status: 'accepted',
acknowledgedBytes: 40,
settled: []
})
expect(ledger.getDebugSnapshot()).toMatchObject({
ackedEndByte: 40,
retainedBytes: 60,
frames: 1
})
expect(release).toHaveBeenLastCalledWith(40)
expect(ledger.acknowledge('generation-1', 100)).toMatchObject({
status: 'accepted',
acknowledgedBytes: 60,
settled: [{ spanId: 'span-1', sourceStartSu: 0, sourceEndSu: 100 }]
})
expect(ledger.getDebugSnapshot()).toMatchObject({
ackedEndByte: 100,
retainedBytes: 0,
frames: 0
})
expect(release.mock.calls).toEqual([[40], [60]])
})
it('admits a contiguous recovered delivery while the prior token remains unsettled', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
expect(ledger.accept(4, 4, [range()])).not.toBeNull()
expect(
ledger.accept(4, 4, [
range({
spanId: 'span-recovered',
clientGeneration: 3,
ownerGeneration: 4,
deliveryToken: 'token-2',
sourceStartSu: 4,
sourceEndSu: 8,
displayStart: 4,
displayEnd: 8
})
])
).not.toBeNull()
expect(ledger.acknowledge('generation-1', 4)).toMatchObject({
status: 'accepted',
settled: [{ spanId: 'span-1', deliveryToken: 'token-1' }]
})
expect(ledger.acknowledge('generation-1', 8)).toMatchObject({
status: 'accepted',
settled: [{ spanId: 'span-recovered', deliveryToken: 'token-2' }]
})
expect(
ledger.prepareAccept(4, 4, [
range({
spanId: 'span-stale',
sourceStartSu: 8,
sourceEndSu: 12,
displayStart: 8,
displayEnd: 12
})
]).status
).toBe('cross-generation')
})
it('settles only complete frames when a cumulative ACK crosses frame boundaries', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
ledger.accept(5, 4, [range()])
ledger.accept(7, 5, [
range({
spanId: 'span-2',
sourceStartSu: 4,
sourceEndSu: 9,
displayStart: 4,
displayEnd: 9,
transform: { transformed: false, rawLengthSu: 5, scalarSafe: true }
})
])
expect(ledger.acknowledge('generation-1', 3)).toEqual({
status: 'accepted',
acknowledgedBytes: 3,
settled: []
})
expect(ledger.getDebugSnapshot()).toMatchObject({
ackedEndByte: 3,
retainedBytes: 9,
frames: 2
})
expect(ledger.acknowledge('generation-1', 12)).toMatchObject({
status: 'accepted',
acknowledgedBytes: 9,
settled: [{ spanId: 'span-1' }, { spanId: 'span-2' }]
})
})
it('rejects malformed coverage, gaps, and later cross-token mappings', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
expect(ledger.accept(5, 3, [range()])).toBeNull()
expect(ledger.accept(5, 4, [range()])).not.toBeNull()
expect(
ledger.accept(5, 4, [
range({
spanId: 'gap',
sourceStartSu: 5,
sourceEndSu: 9,
displayStart: 4,
displayEnd: 8
})
])
).toBeNull()
expect(
ledger.prepareAccept(5, 4, [
range({
spanId: 'other',
deliveryToken: 'token-2',
sourceStartSu: 4,
sourceEndSu: 8,
displayStart: 4,
displayEnd: 8
})
]).status
).toBe('cross-generation')
expect(ledger.getDebugSnapshot()).toMatchObject({ retainedBytes: 5, frames: 1 })
})
it('rejects mixing mapped and unmapped output in either order', () => {
const mapped = new TerminalSourceRangeLedger('mapped')
expect(mapped.accept(5, 4, [range()])).not.toBeNull()
expect(mapped.prepareAccept(1, 1, []).status).toBe('invalid')
const unmapped = new TerminalSourceRangeLedger('unmapped')
expect(unmapped.accept(1, 1, [])).not.toBeNull()
expect(unmapped.prepareAccept(5, 4, [range()]).status).toBe('invalid')
})
it('rejects excessive, stale, notification-shaped, and late settlement', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
ledger.accept(5, 4, [range()])
expect(ledger.acknowledge('generation-2', 5).status).toBe('stale-generation')
expect(ledger.acknowledge('generation-1', 6).status).toBe('excessive')
expect(ledger.acknowledge('generation-1', Number.NaN).status).toBe('invalid')
const transfer = ledger.beginTransfer()
transfer.commit()
expect(ledger.acknowledge('generation-1', 5).status).toBe('invalid')
expect(ledger.getDebugSnapshot()).toMatchObject({ ackedEndByte: 0, closed: true })
})
it('restores all mappings when an atomic transfer rolls back', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
ledger.accept(5, 4, [range()])
const transfer = ledger.beginTransfer()
expect(transfer.frames).toHaveLength(1)
expect(ledger.canAccept(1)).toBe(false)
transfer.rollback()
expect(ledger.getDebugSnapshot()).toMatchObject({
retainedBytes: 5,
frames: 1,
transferring: false,
closed: false
})
const retry = ledger.beginTransfer()
retry.commit()
expect(ledger.getDebugSnapshot()).toMatchObject({
retainedBytes: 0,
frames: 0,
closed: true
})
})
it('replaces covered mappings without synthesizing encoded-byte credit', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
ledger.accept(5, 4, [range()], 4)
ledger.accept(
7,
4,
[
range({
spanId: 'span-trailing',
sourceStartSu: 4,
sourceEndSu: 8,
displayStart: 4,
displayEnd: 8
})
],
8
)
const replacement = ledger.planSourceRangeReplacement(8)
expect(replacement).not.toBeNull()
expect(() => replacement?.commit()).not.toThrow()
expect(ledger.acknowledge('generation-1', 12)).toMatchObject({
status: 'accepted',
acknowledgedBytes: 12,
settled: []
})
expect(
ledger.accept(
3,
2,
[
range({
spanId: 'span-live',
sourceStartSu: 8,
sourceEndSu: 10,
displayStart: 8,
displayEnd: 10,
transform: { transformed: false, rawLengthSu: 2, scalarSafe: true }
})
],
10
)
).not.toBeNull()
})
it('rejects an admitted trailing mapping before authoritative commit', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
ledger.accept(5, 4, [range()], 4)
ledger.accept(
7,
4,
[
range({
spanId: 'span-trailing',
sourceStartSu: 4,
sourceEndSu: 8,
displayStart: 4,
displayEnd: 8
})
],
8
)
expect(ledger.planSourceRangeReplacement(4)).toBeNull()
})
it('rejects an unsequenced mapped frame before replacement commit', () => {
const ledger = new TerminalSourceRangeLedger('generation-1')
ledger.accept(5, 4, [range()])
expect(ledger.planSourceRangeReplacement(4)).toBeNull()
})
it('rolls back a pre-send admission without accepting a byte boundary', () => {
const registry = new TerminalSourceRangeRegistry()
const ledger = registry.open('generation-1')!
const prepared = ledger.prepareAccept(5, 4, [range()])
expect(prepared.status).toBe('ready')
if (prepared.status !== 'ready') {
throw new Error('expected source range admission')
}
expect(registry.getDebugSnapshot().retainedBytes).toBe(5)
prepared.admission.rollback()
expect(ledger.getDebugSnapshot()).toMatchObject({
acceptedEndByte: 0,
retainedBytes: 0,
frames: 0
})
expect(registry.getDebugSnapshot().retainedBytes).toBe(0)
})
it('bounds aggregate retained mapping bytes and releases them on ACK and close', () => {
const registry = new TerminalSourceRangeRegistry()
const ledgers = Array.from({ length: 9 }, (_, index) => registry.open(`stream-${index}`)!)
for (const ledger of ledgers.slice(0, 8)) {
expect(ledger.accept(TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES, 0, [])).not.toBeNull()
}
expect(ledgers[8]!.canAccept(1)).toBe(false)
expect(registry.getDebugSnapshot().retainedBytes).toBe(16 * 1024 * 1024)
expect(ledgers[0]!.acknowledge('stream-0', TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES).status).toBe(
'accepted'
)
expect(ledgers[8]!.accept(1, 0, [])).not.toBeNull()
for (const ledger of ledgers) {
ledger.close()
}
expect(registry.getDebugSnapshot()).toEqual({ streams: 0, retainedBytes: 0 })
})
})
@@ -0,0 +1,310 @@
import {
sameTerminalOutputSourceIdentity,
type TerminalOutputSourceRange
} from '../../../shared/terminal-output-source-range'
import {
canPlanTerminalSourceRangeReplacement,
freezeTerminalOutputSourceRanges,
replaceTerminalSourceRangeFrames,
type TerminalSourceRangeFrame,
validateTerminalSourceRangeFrame
} from './terminal-source-range-validation'
export type { TerminalSourceRangeFrame } from './terminal-source-range-validation'
export const TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES = 2 * 1024 * 1024
export type TerminalSourceRangeAckResult =
| {
status: 'accepted'
acknowledgedBytes: number
settled: readonly TerminalOutputSourceRange[]
}
| { status: 'duplicate'; settled: readonly [] }
| {
status: 'invalid' | 'stale-generation' | 'excessive' | 'cross-generation'
settled: readonly []
}
export type TerminalSourceRangeAdmission = Readonly<{
frame: TerminalSourceRangeFrame
commit: () => boolean
rollback: () => void
}>
export type TerminalSourceRangeAdmissionResult =
| { status: 'ready'; admission: TerminalSourceRangeAdmission }
| { status: 'capacity' | 'invalid' | 'cross-generation' }
export type TerminalSourceRangeTransfer = Readonly<{
frames: readonly TerminalSourceRangeFrame[]
commit: () => void
rollback: () => void
}>
export type TerminalSourceRangeBudget = {
canReserve: (bytes: number) => boolean
reserve: (bytes: number) => boolean
release: (bytes: number) => void
close: () => void
}
const STANDALONE_BUDGET: TerminalSourceRangeBudget = {
canReserve: () => true,
reserve: () => true,
release: () => {},
close: () => {}
}
function isRecoveredSourceIdentity(
previous: TerminalOutputSourceRange,
next: TerminalOutputSourceRange
): boolean {
return (
previous.id === next.id &&
previous.providerGeneration === next.providerGeneration &&
previous.ptyIncarnation === next.ptyIncarnation &&
next.clientGeneration > previous.clientGeneration &&
next.ownerGeneration > previous.ownerGeneration &&
next.deliveryToken !== previous.deliveryToken
)
}
export class TerminalSourceRangeLedger {
private acceptedEndByte = 0
private ackedEndByte = 0
private retainedBytes = 0
private frames: TerminalSourceRangeFrame[] = []
private mappingMode: 'mapped' | 'unmapped' | null = null
private boundRange: TerminalOutputSourceRange | null = null
private mappedSourceEndSu: number | null = null
private mappedDisplayEnd: number | null = null
private pending: TerminalSourceRangeAdmission | null = null
private transferring = false
private closed = false
constructor(
readonly streamGeneration: string,
private readonly budget: TerminalSourceRangeBudget = STANDALONE_BUDGET
) {
if (!streamGeneration) {
throw new Error('terminal_source_range_generation_required')
}
}
canAccept(encodedBytes: number): boolean {
return (
!this.closed &&
!this.transferring &&
!this.pending &&
Number.isSafeInteger(encodedBytes) &&
encodedBytes > 0 &&
this.retainedBytes + encodedBytes <= TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES &&
this.budget.canReserve(encodedBytes)
)
}
prepareAccept(
encodedBytes: number,
displayLength: number,
sourceRanges: readonly TerminalOutputSourceRange[],
outputSeq?: number
): TerminalSourceRangeAdmissionResult {
if (!this.canAccept(encodedBytes)) {
return { status: 'capacity' }
}
if (!validateTerminalSourceRangeFrame(displayLength, sourceRanges)) {
return { status: 'invalid' }
}
const nextMappingMode = sourceRanges.length > 0 ? 'mapped' : 'unmapped'
if (this.mappingMode && this.mappingMode !== nextMappingMode) {
return { status: 'invalid' }
}
const first = sourceRanges[0]
if (
first &&
(this.boundRange
? !sameTerminalOutputSourceIdentity(this.boundRange, first) &&
!isRecoveredSourceIdentity(this.boundRange, first)
: !sourceRanges.every((range) => sameTerminalOutputSourceIdentity(first, range)))
) {
return { status: 'cross-generation' }
}
if (
first &&
((this.mappedSourceEndSu !== null && first.sourceStartSu !== this.mappedSourceEndSu) ||
(this.mappedDisplayEnd !== null && first.displayStart !== this.mappedDisplayEnd))
) {
return { status: 'invalid' }
}
if (!this.budget.reserve(encodedBytes)) {
return { status: 'capacity' }
}
const ranges = freezeTerminalOutputSourceRanges(sourceRanges)
const frame = Object.freeze({
encodedStartByte: this.acceptedEndByte,
encodedEndByte: this.acceptedEndByte + encodedBytes,
displayLength,
...(typeof outputSeq === 'number' ? { outputSeq } : {}),
sourceRanges: ranges
})
let finished = false
const admission: TerminalSourceRangeAdmission = Object.freeze({
frame,
commit: () => {
if (finished || this.pending !== admission || this.closed || this.transferring) {
return false
}
finished = true
this.pending = null
this.acceptedEndByte = frame.encodedEndByte
this.retainedBytes += encodedBytes
this.frames.push(frame)
this.mappingMode ??= nextMappingMode
const last = ranges.at(-1)
if (first && last) {
this.boundRange = first
this.mappedSourceEndSu = last.sourceEndSu
this.mappedDisplayEnd = last.displayEnd
}
return true
},
rollback: () => {
if (finished) {
return
}
finished = true
if (this.pending === admission) {
this.pending = null
}
this.budget.release(encodedBytes)
}
})
this.pending = admission
return { status: 'ready', admission }
}
accept(
encodedBytes: number,
displayLength: number,
sourceRanges: readonly TerminalOutputSourceRange[],
outputSeq?: number
): TerminalSourceRangeFrame | null {
const prepared = this.prepareAccept(encodedBytes, displayLength, sourceRanges, outputSeq)
if (prepared.status !== 'ready' || !prepared.admission.commit()) {
return null
}
return prepared.admission.frame
}
acknowledge(streamGeneration: string, ackedEndByte: number): TerminalSourceRangeAckResult {
if (streamGeneration !== this.streamGeneration) {
return { status: 'stale-generation', settled: [] }
}
if (this.closed || this.transferring || this.pending) {
return { status: 'invalid', settled: [] }
}
if (
!Number.isSafeInteger(ackedEndByte) ||
ackedEndByte < 0 ||
ackedEndByte < this.ackedEndByte
) {
return { status: 'invalid', settled: [] }
}
if (ackedEndByte > this.acceptedEndByte) {
return { status: 'excessive', settled: [] }
}
if (ackedEndByte === this.ackedEndByte) {
return { status: 'duplicate', settled: [] }
}
const acknowledgedBytes = ackedEndByte - this.ackedEndByte
const settled: TerminalOutputSourceRange[] = []
let frameCount = 0
for (const frame of this.frames) {
if (frame.encodedEndByte > ackedEndByte) {
break
}
settled.push(...frame.sourceRanges)
frameCount++
}
this.ackedEndByte = ackedEndByte
this.frames.splice(0, frameCount)
this.retainedBytes -= acknowledgedBytes
this.budget.release(acknowledgedBytes)
return { status: 'accepted', acknowledgedBytes, settled: Object.freeze(settled) }
}
planSourceRangeReplacement(snapshotSeq: number): Readonly<{ commit: () => void }> | null {
const unavailable = this.closed || this.transferring || this.pending
if (unavailable || !canPlanTerminalSourceRangeReplacement(this.frames, snapshotSeq)) {
return null
}
const replacement = replaceTerminalSourceRangeFrames(this.frames, snapshotSeq)
let committed = false
return Object.freeze({
commit: () => {
if (committed || this.closed) {
return
}
committed = true
Object.assign(this, replacement)
}
})
}
beginTransfer(): TerminalSourceRangeTransfer {
if (this.closed || this.transferring || this.pending) {
throw new Error('terminal_source_range_transfer_invalid')
}
this.transferring = true
let finished = false
const frames = Object.freeze(this.frames.slice())
return Object.freeze({
frames,
commit: () => {
if (finished) {
return
}
finished = true
this.budget.release(this.retainedBytes)
this.frames = []
this.retainedBytes = 0
this.transferring = false
this.closed = true
this.budget.close()
},
rollback: () => {
if (finished) {
return
}
finished = true
this.transferring = false
}
})
}
close(): void {
if (this.closed) {
return
}
this.pending?.rollback()
this.budget.release(this.retainedBytes)
this.frames = []
this.retainedBytes = 0
this.transferring = false
this.closed = true
this.budget.close()
}
getDebugSnapshot() {
return {
acceptedEndByte: this.acceptedEndByte,
ackedEndByte: this.ackedEndByte,
retainedBytes: this.retainedBytes,
frames: this.frames.length,
transferring: this.transferring,
closed: this.closed,
bound: this.boundRange !== null
}
}
}
@@ -0,0 +1,43 @@
import { TERMINAL_MULTIPLEX_MAX_STREAMS_PER_CONNECTION } from '../../../shared/terminal-multiplex-flow-control'
import {
TerminalSourceRangeLedger,
type TerminalSourceRangeBudget
} from './terminal-source-range-ledger'
export const TERMINAL_SOURCE_RANGE_CONNECTION_MAX_BYTES = 16 * 1024 * 1024
export class TerminalSourceRangeRegistry {
private readonly ledgers = new Set<TerminalSourceRangeLedger>()
private retainedBytes = 0
open(streamGeneration: string): TerminalSourceRangeLedger | null {
if (this.ledgers.size >= TERMINAL_MULTIPLEX_MAX_STREAMS_PER_CONNECTION) {
return null
}
let ledger: TerminalSourceRangeLedger
const budget: TerminalSourceRangeBudget = {
canReserve: (bytes) =>
this.retainedBytes + bytes <= TERMINAL_SOURCE_RANGE_CONNECTION_MAX_BYTES,
reserve: (bytes) => {
if (this.retainedBytes + bytes > TERMINAL_SOURCE_RANGE_CONNECTION_MAX_BYTES) {
return false
}
this.retainedBytes += bytes
return true
},
release: (bytes) => {
this.retainedBytes = Math.max(0, this.retainedBytes - bytes)
},
close: () => {
this.ledgers.delete(ledger)
}
}
ledger = new TerminalSourceRangeLedger(streamGeneration, budget)
this.ledgers.add(ledger)
return ledger
}
getDebugSnapshot() {
return { streams: this.ledgers.size, retainedBytes: this.retainedBytes }
}
}
@@ -0,0 +1,99 @@
import {
assertTerminalOutputSourceRange,
sameTerminalOutputSourceIdentity,
type TerminalOutputSourceRange
} from '../../../shared/terminal-output-source-range'
export type TerminalSourceRangeFrame = Readonly<{
encodedStartByte: number
encodedEndByte: number
displayLength: number
outputSeq?: number
sourceRanges: readonly TerminalOutputSourceRange[]
}>
export function freezeTerminalOutputSourceRanges(
ranges: readonly TerminalOutputSourceRange[]
): readonly TerminalOutputSourceRange[] {
return Object.freeze(
ranges.map((range) =>
Object.freeze({
...range,
transform: Object.freeze({ ...range.transform })
})
)
)
}
export function validateTerminalSourceRangeFrame(
displayLength: number,
ranges: readonly TerminalOutputSourceRange[]
): boolean {
if (!Number.isSafeInteger(displayLength) || displayLength < 0) {
return false
}
if (ranges.length === 0) {
return true
}
try {
for (const range of ranges) {
assertTerminalOutputSourceRange(range)
}
} catch {
return false
}
const first = ranges[0]!
let previous = first
for (const range of ranges.slice(1)) {
if (
!sameTerminalOutputSourceIdentity(first, range) ||
range.sourceStartSu !== previous.sourceEndSu ||
range.displayStart !== previous.displayEnd
) {
return false
}
previous = range
}
return previous.displayEnd - first.displayStart === displayLength
}
export function replaceTerminalSourceRangeFrames(
frames: readonly TerminalSourceRangeFrame[],
snapshotSeq: number
): Readonly<{
frames: TerminalSourceRangeFrame[]
mappingMode: 'mapped' | null
boundRange: TerminalOutputSourceRange | null
mappedSourceEndSu: number | null
mappedDisplayEnd: number | null
}> {
const replaced = frames.map((frame) =>
typeof frame.outputSeq === 'number' && frame.outputSeq <= snapshotSeq
? Object.freeze({ ...frame, sourceRanges: Object.freeze([]) })
: frame
)
const remainingRanges = replaced.flatMap((frame) => frame.sourceRanges)
const last = remainingRanges.at(-1)
return Object.freeze({
frames: replaced,
mappingMode: remainingRanges.length > 0 ? 'mapped' : null,
boundRange: last ?? null,
mappedSourceEndSu: last?.sourceEndSu ?? null,
mappedDisplayEnd: last?.displayEnd ?? null
})
}
export function canPlanTerminalSourceRangeReplacement(
frames: readonly TerminalSourceRangeFrame[],
snapshotSeq: number
): boolean {
return (
Number.isSafeInteger(snapshotSeq) &&
snapshotSeq >= 0 &&
frames.every(
(frame) =>
frame.sourceRanges.length === 0 ||
(typeof frame.outputSeq === 'number' && frame.outputSeq <= snapshotSeq)
)
)
}