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:
@@ -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 &&
|
||||
|
||||
Reference in New Issue
Block a user