* ✨ feat(session): persist and synchronize read state * 🌐 fix(client): complete Japanese labels after base update * 📝 docs: refresh session read-state dependency graph * 🧪 test(web): align session menu and read-state snapshots * 🌐 fix(session): complete Japanese plugin metadata * 🧪 test(web): distinguish unread from pending user input * 🐛 修复会话阅读状态的故障隔离与生命周期 * 🐛 修复阅读状态依赖检查并补齐自动已读覆盖 * 🐛 恢复会话绿点并移除未读标题加粗 * ♻️ Keep shared session reading state in Host memory * 🌐 Complete reading-state metadata for supported locales * 📝 Refresh module graph after removing storage dependency * 🧹 Move storage dependency policy out of memory-only reading * 🐛 Wait for sidebar catalog before replay navigation * 🔧 Give Host TypeScript checks 8 GiB of heap * ✅ Align Host heap checks and Windows diagnostics * ♻️ Keep CI repairs outside the session reading PR * 🐛 Show failed unread turns with an error indicator * 🔧 Adjust npm layout budget for the reading package * 🧪 Scope projection stream assertions to observed units * 🧪 Scope permission and title assertions to their projections * ♻️ Simplify session reading updates to explicit positions * 🐛 Align session reading package with release version * 🧪 Load reading state in LiveShare viewer fixtures * 🧹 Remove persistence-only type link from memory PR * 🧪 Align context menu expectations with reading actions * 🐛 Sync reading package with the release version * 🧪 Include turn boundaries in session summary expectations * ♻️ Derive reading failure facts from Host events instead of a projection The reading service took each completion from the Agent turn-boundary projection, which forced a stateVersion bump and put that projection's whole internal state on the wire for every Session list row. The service now records `turn/end` itself, so `core/agent` and the persisted projection schema are untouched. History that ended before the service started raises no reminder, which keeps "existing history reads as read" without a startup scan. The failure flag therefore describes only turns this Host observed: marking a Session whose last turn failed before a restart shows the ordinary unread reminder. * 🐛 Preserve manual unread until explicit Session interaction * 🧪 Align cold Session reading snapshot with unloaded title * 🔖 chore(session): align session-read-state with 0.2.2-rc.2 Master moved the root and every released manifest to 0.2.2-rc.2, but the new dsh-session-read-state package still declared 0.2.2-rc.1, failing constraints, verify-version-sync, verify-npm-install-layout, and release:verify after the master merge. * ♻️ refactor(gateway): recognize Remote stream carrier loss by error code RemoteStream now decides whether a generation end or failure is a retryable carrier loss by the stable code 'gateway/carrier-lost' instead of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps working and carries that code, so existing callers are unchanged, while a Client feature package can return a coded Error from `ended` without importing the class. The new RemoteStreamCarrierFailure type describes such errors; terminal-controller classifies disconnects the same way. * ♻️ refactor(session): move Session reading into ui-session-status Fold the reading feature into the single package packages/client/ui-session-status and delete session-read-state. - Host face: SessionStatusService keeps in-memory reading records and serves the sessionStatus Remote namespace (mark, follow) with session-status/* error codes; its service key is registered only for Gateway discovery and is not declared on Context. - Client face: a package-internal reading model follows the Host stream through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the records into completionUnread and completionFailed and exposes mark and readingReady; main-view acknowledgement and the session-status/read-intent event live here. No reading service or type is exported. - verify-client-packages lets a packages/client feature package request packages/api rows through dsh.client.external; feature-to-feature requests stay rejected. - ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client test runtime, docs, Agent Notes, and the upgrade guide follow. * ♻️ refactor(session): clear manual unread only when the main view switches to the Session Remove the session-status/read-intent event. ui-session-status now clears an existing manual unread mark when the main view switches to a different Session, including the first selection after a page load, once the reading baseline is ready and the body arrives. Window focus, visibility changes, a replaced binding for the same Session, and activity in the open Session preserve manual unread. ui-conversation returns to master (only the ui-session-status client tsconfig reference remains), and ui-workspace navigation no longer emits the event. Tests, the session-reading Web e2e case, READMEs, and the reading Agent Note follow the new rule. * 🐛 fix(session): address the Session status review findings - Open the reading stream only while ctx.remoteAccess allows sessionStatus/follow, so a LiveShare viewer opens no owner-only stream, keeps readingReady false, and logs no synchronization failure; access changes start or stop the stream. - Hide the unacknowledged completion of the Session the visible, focused main view retains; manual marks stay visible, completionFailed follows completionUnread, and the reminder returns on blur, hiding, or a switch. - Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and SERVICE_ROLES entries; the service and SessionRead* types document on docs/subsystems/web-client.md, which now owns the reading section with the failed field. - Document that a Host plugin reload can leave the Client with a terminal error until a page reload; drop the redundant types import and the unused publish() result. - Archived Sessions read as read and offer no reading mark in the row menu or the toggle-read shortcut. - session.toggleRead names the open dialog, open panel, or archived Session that blocks it instead of asking to select a Session. - isRemoteStreamCarrierFailure rejects a RemoteError from the Host even when it carries gateway/carrier-lost; the code is Client-local. - ./types is types-only like ui-trajectory, and files no longer ship lib/types JavaScript. * 🐛 fix(session): close the remaining Session status review gaps - The Gateway Client exports isRemoteStreamCarrierFailure, and the terminal view uses it, so a Host RemoteError carrying the carrier code shows as failed rather than disconnected. - Each access grant's reading stream carries a token: frames a revoked or superseded stream still delivers are discarded, and cleanup waits for disposal before leaving reading unavailable unless a newer grant is active. - The status table hides the viewed Session's natural reminder only while that Session is open; the panel case is a documented limitation. - The README limitation and the upgrade guide state that only the main-view switch rule, including a reload restore, clears manual unread automatically. - Add the missing blank line before the next heading in the web-client reading section. * ♻️ refactor(session): install reading under the Session status table - apply returns to master's form plus one line: UiSessionStatus is the root, published as the useSessionStatus source, and installReading() from the new src/client/read.ts follows Host reading records into it. UiSessionStatus takes master's three constructor parameters and creates its own SessionReadModel as the package-internal `reading` member; installSessionStatus is removed and acknowledge.ts stays a separate file. - The viewed Session's snapshot subscription republishes the table only when its openState changes, so streamed events do not rebuild it. - Remove the obsolete Dev Note sentence about failure outcomes. - session.toggleRead passes when the Peer may not mark reading, matching the row menu, and reports readingUnavailable only while unsynchronized. --------- Co-authored-by: imccyu <[email protected]> Co-authored-by: imccyu <[email protected]>
418 lines
19 KiB
TypeScript
418 lines
19 KiB
TypeScript
/** React-free browser terminal state and reconnecting Remote-stream ownership. */
|
|
import { preferredShell, rememberShell } from './shell-preference.ts'
|
|
import type { TerminalInventory } from './inventory.ts'
|
|
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
|
import { Deque } from '@deepseek-ai/dsh-deque'
|
|
import { isRemoteStreamCarrierFailure, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client'
|
|
import { RemoteError, remoteErrorOf, type RemoteResult, type RemoteStreamHandle, type RemoteUplinkWindow } from '@deepseek-ai/dsh-typert-protocol'
|
|
import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote'
|
|
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
|
import type {
|
|
TerminalInput, TerminalEnvironment, TerminalFrame,
|
|
WebTerminalId, WebTerminalInfo,
|
|
} from '../types.ts'
|
|
|
|
/** The generated terminal namespace's browser-facing operations. */
|
|
export type TerminalRemote = ClientRemote['terminal']
|
|
|
|
/** Product error identifiers translated by the terminal UI. */
|
|
export type TerminalViewIssue = 'missingTerminal' | 'inputFull' | 'attachmentEnded' | 'invalidOutput' | 'terminalLimit'
|
|
|
|
declare module '@deepseek-ai/dsh-typert-protocol' {
|
|
interface RemoteErrorDetailsMap {
|
|
/** Client terminal failure preserved through the Remote stream supervisor. */
|
|
'terminal/view': { readonly issue: TerminalViewIssue }
|
|
}
|
|
}
|
|
|
|
class TerminalViewError extends RemoteError<'terminal/view'> {
|
|
constructor(issue: TerminalViewIssue, message: string = issue) { super('terminal/view', message, { issue }) }
|
|
}
|
|
|
|
/** One screen write awaiting the DOM emulator's callback. */
|
|
export interface TerminalRenderFrame {
|
|
readonly revision: number
|
|
readonly frame: Extract<TerminalFrame, { type: 'snapshot' | 'output' }>
|
|
}
|
|
|
|
/** Observable state of one sidebar occurrence. */
|
|
export interface TerminalViewState {
|
|
readonly phase: 'idle' | 'loading' | 'creating' | 'connecting' | 'connected' | 'disconnected' | 'closing' | 'closed' | 'failed'
|
|
readonly environment?: TerminalEnvironment | undefined
|
|
readonly title?: string | undefined
|
|
readonly info?: WebTerminalInfo | undefined
|
|
readonly writable: boolean
|
|
readonly render?: TerminalRenderFrame | undefined
|
|
readonly error?: string | undefined
|
|
readonly issue?: TerminalViewIssue | undefined
|
|
}
|
|
|
|
interface InputCost {
|
|
readonly inputBytes: number
|
|
readonly frameBytes: number
|
|
}
|
|
|
|
interface TerminalInputAttachment {
|
|
readonly handle: RemoteStreamHandle<TerminalFrame, TerminalInput>
|
|
readonly signal: AbortSignal
|
|
sequence: number
|
|
acknowledged: number
|
|
readonly pending: Map<number, InputCost>
|
|
readonly queued: Deque<InputCost & { readonly command: TerminalInput }>
|
|
window: RemoteUplinkWindow | undefined
|
|
bytes: number
|
|
bufferedBytes: number
|
|
inFlightBytes: number
|
|
}
|
|
|
|
/** A view survives DOM unmount; its process only ends on explicit close. */
|
|
export class TerminalView {
|
|
/** Observable controls, process metadata and the next screen update awaiting acknowledgement. */
|
|
readonly state: SnapshotStore<TerminalViewState> = createSnapshotStore<TerminalViewState>({ phase: 'idle', writable: false })
|
|
private readonly lifetime = new AbortController()
|
|
private stream: RemoteStream<TerminalFrame> | undefined
|
|
private mounted = false
|
|
private attachment: TerminalInputAttachment | undefined
|
|
private pendingRender: { revision: number; resolve: () => void } | undefined
|
|
private revision = 0
|
|
private creation: Promise<void> | undefined
|
|
private loading: Promise<void> | undefined
|
|
private closing: Promise<void> | undefined
|
|
private readonly detaching = new Set<Promise<void>>()
|
|
|
|
/**
|
|
* @param sessionId - Session owning the terminal.
|
|
* @param remote - typed terminal Remote operations.
|
|
* @param gateway - reconnecting stream factory.
|
|
* @param inventory - Session-owned terminal list shared by all views.
|
|
* @param id - Host terminal identity, reused when recovering an item from its Session list.
|
|
* @param createWhenMissing - allow allocation only for a new tab, never a listed terminal.
|
|
* @param shellPath - explicit shell chosen at the guide; omission uses the remembered available shell.
|
|
* @param retain - window hold acknowledgement required before output attachment.
|
|
*/
|
|
constructor(
|
|
private readonly sessionId: SessionId,
|
|
private readonly remote: TerminalRemote,
|
|
private readonly gateway: Pick<ClientRemote, '$stream'>,
|
|
private readonly inventory: TerminalInventory,
|
|
readonly id: WebTerminalId,
|
|
private createWhenMissing = true,
|
|
private readonly shellPath?: string,
|
|
private readonly retain?: (signal: AbortSignal) => Promise<void>,
|
|
) {}
|
|
|
|
/**
|
|
* Attach the DOM lifetime, starting the chosen shell or reconnecting the saved process.
|
|
* @returns a detach callback that leaves the terminal process alive.
|
|
*/
|
|
mount(): () => void {
|
|
this.mounted = true
|
|
const state = this.state.getSnapshot()
|
|
if (state.phase === 'idle') void this.refresh()
|
|
else if (state.info !== undefined && state.phase !== 'failed' && state.phase !== 'closed') this.connect()
|
|
return () => {
|
|
this.mounted = false
|
|
this.detach()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Start or explicitly retry this tab, sharing Session discovery with other views.
|
|
* New identities allocate directly; confirmed or restored terminals cannot be replaced.
|
|
* @returns after environment lookup and creation or recovery settle.
|
|
*/
|
|
refresh(): Promise<void> {
|
|
if (this.creation !== undefined) return this.creation
|
|
if (this.loading !== undefined) return this.loading
|
|
if (this.closing !== undefined || this.lifetime.signal.aborted) return Promise.resolve()
|
|
const retry = this.state.getSnapshot().phase !== 'idle'
|
|
this.patch({ phase: 'loading', error: undefined, issue: undefined })
|
|
this.loading = (async () => {
|
|
const [environment, available] = await Promise.all([
|
|
this.remote.environment(this.sessionId, this.lifetime.signal),
|
|
this.createWhenMissing ? undefined : this.inventory.read(retry),
|
|
])
|
|
if (this.stopped()) return
|
|
this.patch({ environment: valueOf(environment) })
|
|
const info = available?.get(this.id)
|
|
if (info !== undefined) this.adopt(info)
|
|
else if (this.createWhenMissing) {
|
|
let path = this.shellPath
|
|
if (path === undefined) {
|
|
const shells = valueOf(await this.remote.shells(this.sessionId, this.lifetime.signal))
|
|
const previous = preferredShell()
|
|
path = shells.find(shell => shell.path === previous)?.path ?? shells[0]?.path
|
|
}
|
|
if (this.stopped()) return
|
|
if (path !== undefined) rememberShell(path)
|
|
await this.create(valueOf(environment), path)
|
|
}
|
|
else throw new TerminalViewError('missingTerminal')
|
|
})().catch((error: unknown) => { this.fail(error) }).finally(() => { this.loading = undefined })
|
|
return this.loading
|
|
}
|
|
|
|
private stopped(): boolean { return this.lifetime.signal.aborted || this.closing !== undefined }
|
|
|
|
private async create(environment: TerminalEnvironment, shellPath?: string): Promise<void> {
|
|
this.patch({ phase: 'creating', error: undefined, issue: undefined })
|
|
this.creation = (async () => {
|
|
const info = valueOf(await this.remote.create(this.sessionId, {
|
|
id: this.id, ...shellPath === undefined ? {} : { shellPath },
|
|
cols: Math.min(80, environment.maxCols), rows: Math.min(24, environment.maxRows),
|
|
}, this.lifetime.signal))
|
|
if (!this.lifetime.signal.aborted) {
|
|
this.inventory.update(info)
|
|
this.adopt(info)
|
|
}
|
|
})().catch((error: unknown) => { this.fail(error) }).finally(() => { this.creation = undefined })
|
|
await this.creation
|
|
}
|
|
|
|
private adopt(info: WebTerminalInfo): void {
|
|
this.createWhenMissing = false
|
|
this.patch({ info, title: info.title })
|
|
if (this.retain === undefined) { if (this.mounted && this.closing === undefined) this.connect(); return }
|
|
void this.retain(this.lifetime.signal).then(() => {
|
|
if (this.mounted && this.closing === undefined) this.connect()
|
|
}).catch((error: unknown) => { if (!this.stopped()) this.fail(error) })
|
|
}
|
|
|
|
/** Reattach with a fresh screen and regain input control. */
|
|
connect(): void {
|
|
const info = this.state.getSnapshot().info
|
|
if (info === undefined || !this.mounted || this.closing !== undefined || this.lifetime.signal.aborted) return
|
|
this.detach()
|
|
const stream = this.gateway.$stream<TerminalFrame>({
|
|
name: 'Browser terminal output',
|
|
open: async function* (this: TerminalView, signal: AbortSignal) {
|
|
await this.retain?.(signal)
|
|
signal.throwIfAborted()
|
|
const handle = this.remote.attach(this.sessionId, info.id, signal)
|
|
const attachment: TerminalInputAttachment = {
|
|
handle, signal, sequence: 0, acknowledged: 0,
|
|
pending: new Map(), queued: new Deque(), window: undefined,
|
|
bytes: 0, bufferedBytes: 0, inFlightBytes: 0,
|
|
}
|
|
this.attachment = attachment
|
|
try {
|
|
for await (const frame of handle) {
|
|
if (frame.type === 'snapshot') attachment.window = frame.inputWindow
|
|
yield frame
|
|
}
|
|
}
|
|
finally { if (this.attachment === attachment) this.attachment = undefined }
|
|
}.bind(this),
|
|
ended: () => new TerminalViewError('attachmentEnded'),
|
|
carrierFailed: () => { if (this.stream === stream) this.patch({ phase: 'disconnected', writable: false }) },
|
|
})
|
|
this.stream = stream
|
|
this.patch({ phase: 'connecting', writable: false, error: undefined, issue: undefined, render: undefined })
|
|
void this.consume(stream)
|
|
}
|
|
|
|
/**
|
|
* Release the next stream item after xterm has parsed this frame.
|
|
* @param revision - locally delivered render revision.
|
|
*/
|
|
acknowledge(revision: number): void {
|
|
if (this.pendingRender?.revision !== revision) return
|
|
this.pendingRender.resolve()
|
|
this.pendingRender = undefined
|
|
}
|
|
|
|
/**
|
|
* Queue input within the raw UTF-8 and encoded-frame budgets, waiting for carrier capacity.
|
|
* @param data - input from the terminal emulator; never replayed after disconnection.
|
|
* @param typed - whether the person produced the input, as opposed to a terminal-protocol reply.
|
|
*/
|
|
write(data: string, typed: boolean = false): void {
|
|
const state = this.state.getSnapshot()
|
|
const attachment = this.attachment
|
|
if (!state.writable || state.info === undefined || attachment === undefined || attachment.signal.aborted) return
|
|
if (data.length === 0) return
|
|
const bytes = new TextEncoder().encode(data).byteLength
|
|
if (attachment.bytes + bytes > (state.environment?.maxInputBytes ?? 0)) { this.failInput(new TerminalViewError('inputFull')); return }
|
|
this.send(attachment, { type: 'write', sequence: attachment.sequence + 1, data, ...typed ? { typed: true } : {} }, bytes)
|
|
}
|
|
|
|
/**
|
|
* Resize only from the currently writable view, ordered with keyboard input.
|
|
* @param cols - measured column count.
|
|
* @param rows - measured row count.
|
|
*/
|
|
resize(cols: number, rows: number): void {
|
|
const state = this.state.getSnapshot()
|
|
const attachment = this.attachment
|
|
if (!state.writable || state.info === undefined || attachment === undefined || attachment.signal.aborted) return
|
|
if (state.info.cols === cols && state.info.rows === rows) return
|
|
cols = Math.min(cols, state.environment?.maxCols ?? cols)
|
|
rows = Math.min(rows, state.environment?.maxRows ?? rows)
|
|
this.send(attachment, { type: 'resize', sequence: attachment.sequence + 1, cols, rows }, 0)
|
|
}
|
|
|
|
private send(attachment: TerminalInputAttachment, command: TerminalInput, bytes: number): void {
|
|
const frameBytes = new TextEncoder().encode(JSON.stringify(command)).byteLength + (attachment.window?.frameOverheadBytes ?? 0)
|
|
if (attachment.bufferedBytes + frameBytes > (this.state.getSnapshot().environment?.maxBufferedBytes ?? 0)
|
|
|| (attachment.window !== undefined && frameBytes > attachment.window.maxBytes)) {
|
|
this.failInput(new TerminalViewError('inputFull'))
|
|
return
|
|
}
|
|
attachment.queued.pushBack({ command, inputBytes: bytes, frameBytes })
|
|
attachment.sequence = command.sequence
|
|
attachment.bytes += bytes
|
|
attachment.bufferedBytes += frameBytes
|
|
this.flushInput(attachment)
|
|
}
|
|
|
|
private flushInput(attachment: TerminalInputAttachment): void {
|
|
while (this.attachment === attachment && !attachment.signal.aborted && this.state.getSnapshot().writable) {
|
|
const next = attachment.queued.popFront()
|
|
if (next === undefined) return
|
|
if (attachment.window !== undefined && attachment.inFlightBytes + next.frameBytes > attachment.window.maxBytes) {
|
|
attachment.queued.pushFront(next)
|
|
return
|
|
}
|
|
try { attachment.handle.send(next.command) }
|
|
catch (error) { this.failInput(error); return }
|
|
attachment.pending.set(next.command.sequence, { inputBytes: next.inputBytes, frameBytes: next.frameBytes })
|
|
attachment.inFlightBytes += next.frameBytes
|
|
}
|
|
}
|
|
|
|
private failInput(error: unknown): void {
|
|
this.fail(error)
|
|
this.detach()
|
|
}
|
|
|
|
/**
|
|
* Update the Host terminal's display name.
|
|
* @param title - user-entered terminal title.
|
|
* @returns after the rename settles and its result is reflected in view state.
|
|
*/
|
|
async rename(title: string): Promise<void> {
|
|
if (title.trim() === this.state.getSnapshot().title || this.lifetime.signal.aborted) return
|
|
try {
|
|
valueOf(await this.remote.rename(this.sessionId, this.id, title))
|
|
if (this.stopped()) return
|
|
const current = this.state.getSnapshot().info
|
|
if (current !== undefined) this.inventory.update({ ...current, title: title.trim() })
|
|
this.patch({ ...(current === undefined ? {} : { info: { ...current, title: title.trim() } }), title: title.trim() })
|
|
} catch (error) { this.fail(error) }
|
|
}
|
|
|
|
/**
|
|
* Explicitly terminate this view's process independently of its DOM lifetime.
|
|
* @returns after Host process cleanup succeeds; failures remain retryable by the owner.
|
|
*/
|
|
close(): Promise<void> {
|
|
if (this.closing !== undefined) return this.closing
|
|
this.patch({ phase: 'closing', writable: false, error: undefined, issue: undefined })
|
|
this.detach()
|
|
this.closing = (async () => {
|
|
// Even a refused or lost creation response may leave an allocation to close.
|
|
await this.creation
|
|
valueOf(await this.remote.close(this.sessionId, this.id))
|
|
this.inventory.remove(this.id)
|
|
this.detach()
|
|
this.patch({ phase: 'closed', writable: false })
|
|
})().catch((error: unknown) => { this.closing = undefined; this.fail(error); throw error })
|
|
return this.closing
|
|
}
|
|
|
|
/**
|
|
* Stop Client work on plugin unload without closing Host terminals.
|
|
* @returns after active and previously detached stream iterators have closed.
|
|
*/
|
|
async dispose(): Promise<void> {
|
|
this.mounted = false
|
|
this.lifetime.abort()
|
|
this.detach()
|
|
await Promise.all(this.detaching)
|
|
}
|
|
|
|
private detach(): void {
|
|
const previous = this.stream
|
|
this.stream = undefined
|
|
this.attachment = undefined
|
|
this.pendingRender?.resolve()
|
|
this.pendingRender = undefined
|
|
if (previous !== undefined) {
|
|
const cleanup = previous.dispose().finally(() => { this.detaching.delete(cleanup) })
|
|
this.detaching.add(cleanup)
|
|
}
|
|
}
|
|
|
|
private async consume(stream: RemoteStream<TerminalFrame>): Promise<void> {
|
|
let generation = 0
|
|
let sequence = 0
|
|
try {
|
|
for await (const item of stream) {
|
|
if (this.stream !== stream) return
|
|
const frame = item.value
|
|
if (generation !== item.generation) {
|
|
if (frame.type !== 'snapshot') throw new TerminalViewError('invalidOutput', 'Terminal output generation is missing its screen snapshot')
|
|
generation = item.generation
|
|
sequence = frame.sequence
|
|
item.accept()
|
|
} else if (frame.type === 'output') {
|
|
if (frame.sequence !== sequence + 1) throw new TerminalViewError('invalidOutput', 'Terminal output sequence has a gap')
|
|
sequence = frame.sequence
|
|
} else if (frame.type === 'snapshot') throw new TerminalViewError('invalidOutput', 'Unexpected terminal screen snapshot')
|
|
if (frame.type === 'ack') {
|
|
const attachment = this.attachment
|
|
/* v8 ignore next -- the physical opener retains its handle until this consumer advances. */
|
|
if (attachment === undefined) throw new TerminalViewError('invalidOutput', 'Terminal acknowledgement has no attachment')
|
|
const pending = attachment.pending.get(frame.sequence)
|
|
if (frame.sequence !== attachment.acknowledged + 1 || pending === undefined) throw new TerminalViewError('invalidOutput', 'Terminal input acknowledgement is out of order')
|
|
attachment.acknowledged = frame.sequence
|
|
attachment.bytes -= pending.inputBytes
|
|
attachment.bufferedBytes -= pending.frameBytes
|
|
attachment.inFlightBytes -= pending.frameBytes
|
|
attachment.pending.delete(frame.sequence)
|
|
if (frame.refusal !== undefined) this.patch({ writable: false })
|
|
this.flushInput(attachment)
|
|
continue
|
|
}
|
|
if (frame.type !== 'output') {
|
|
this.inventory.update(frame.info)
|
|
this.patch({ info: frame.info, title: frame.info.title, phase: 'connected', writable: frame.info.state === 'running' && frame.writable })
|
|
}
|
|
if (frame.type !== 'state') {
|
|
const revision = ++this.revision
|
|
await new Promise<void>((resolve) => {
|
|
this.pendingRender = { revision, resolve }
|
|
const aborted = (): void => { this.acknowledge(revision) }
|
|
item.signal.addEventListener('abort', aborted, { once: true })
|
|
this.pendingRender.resolve = () => { item.signal.removeEventListener('abort', aborted); resolve() }
|
|
this.patch({ render: { revision, frame } })
|
|
if (item.signal.aborted) aborted()
|
|
})
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (this.stream === stream) {
|
|
if (this.state.getSnapshot().info?.state === 'exited') this.patch({ phase: 'closed', writable: false })
|
|
else this.fail(error)
|
|
}
|
|
}
|
|
}
|
|
|
|
private patch(patch: Partial<TerminalViewState>): void {
|
|
if (this.lifetime.signal.aborted) return
|
|
this.state.set({ ...this.state.getSnapshot(), ...patch })
|
|
}
|
|
|
|
private fail(error: unknown): void {
|
|
const failure = remoteErrorOf(error)
|
|
const issue = failure?.code === 'terminal/view' ? failure.details.issue : failure?.code === 'terminal/limit-reached' ? 'terminalLimit' : failure?.code === 'terminal/unavailable' ? 'missingTerminal' : undefined
|
|
if (!this.stopped() && issue === 'missingTerminal') this.inventory.remove(this.id)
|
|
this.patch({ phase: isRemoteStreamCarrierFailure(error) ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) })
|
|
}
|
|
}
|
|
|
|
function valueOf<T>(result: RemoteResult<T>): T {
|
|
if (!result.ok) throw result.error
|
|
return result.value
|
|
}
|