const std = @import("std"); const builtin = @import("builtin"); const ansi = @import("ansi.zig"); const handles = @import("context-handles.zig"); const feed = @import("native-span-feed.zig"); const renderer = @import("renderer.zig"); const terminal = @import("terminal.zig"); const scene = @import("scene.zig"); const buffer = @import("buffer.zig"); const input_parser = @import("input-parser.zig"); const stdout_writer = @import("stdout-writer.zig"); const utf8 = @import("utf8.zig"); const Context = @import("context.zig").Context; const api = @import("context_abi_c"); test { _ = @import("tests/session-split_test.zig"); } test "Session console output rejects an incomplete scalar when its queue cannot accept more bytes" { const Writer = struct { calls: u32 = 0, pub fn write(self: *@This(), bytes: []const u8) !usize { try std.testing.expectEqualStrings("😀", bytes); self.calls += 1; return bytes.len; } }; for ([_]u32{ 2, 4 }) |capacity| { const owner = try Context.init(std.testing.allocator, std.Io.failing, .{}); defer owner.deinit() catch unreachable; const id = try owner.createSession(.{ .chunk_size = 1, .chunk_count = capacity, .span_capacity = capacity }); defer owner.cancelSession(id) catch unreachable; const value = try owner.raw().getSession(id); var writer: Writer = .{}; try owner.writeSession(id, "\xf0\x9f"); if (capacity == 2) { try std.testing.expectError(error.IncompatibleOutput, value.drainConsoleOutput(&writer, 4)); try std.testing.expectEqual(@as(u64, 0), value.completed_bytes); var copy: [1]u8 = undefined; const ticket = (try owner.readOutput(id, ©)).?; try std.testing.expectEqual(@as(u8, 0xf0), copy[0]); try owner.completeOutput(id, ticket, .written); } else { try std.testing.expectEqual(@as(u32, 0), try value.drainConsoleOutput(&writer, 4)); try owner.writeSession(id, "\x98\x80"); try std.testing.expectEqual(@as(u32, 4), try value.drainConsoleOutput(&writer, 4)); try std.testing.expectEqual(@as(u32, 1), writer.calls); try std.testing.expect(value.isDrained()); } } } test "Session console output retains an incomplete scalar that cannot complete" { const Writer = struct { pub fn write(_: @This(), _: []const u8) error{WriteFailed}!usize { return error.WriteFailed; } }; const cases = [_]struct { writes: []const []const u8, setup: bool = false }{ // Terminal setup stops raw admission before the scalar completes. .{ .writes = &.{"\xf0\x9f"}, .setup = true }, // A byte that cannot continue the scalar, in its span or the next one. .{ .writes = &.{ "\xf0\x9f", "\x1b[0m" } }, .{ .writes = &.{ "\xf0\x41", "\x80\x80" } }, }; for (cases) |case| { const owner = try Context.init(std.testing.allocator, std.testing.io, .{}); defer owner.deinit() catch unreachable; const id = try owner.createSession(.{ .chunk_size = 4096, .chunk_count = 4, .span_capacity = 4, .control_capacity = 4096 }); defer owner.cancelSession(id) catch unreachable; try owner.attachSessionRenderer(id, 2, 1, .{ .forwarded_env = &.{} }); for (case.writes) |bytes| try owner.writeSession(id, bytes); if (case.setup) { try owner.setupSessionTerminal(id, .{}); try std.testing.expectError(error.Busy, owner.writeSession(id, "\x98\x80")); } const value = try owner.raw().getSession(id); try std.testing.expectError(error.IncompatibleOutput, value.drainConsoleOutput(Writer{}, 4)); try std.testing.expectEqual(@as(u64, 0), value.completed_bytes); if (case.setup) continue; var out: [16]u8 = undefined; var len: usize = 0; while (try owner.readOutput(id, out[len..])) |ticket| { len += ticket.len; try owner.completeOutput(id, ticket, .written); } try std.testing.expectEqualStrings(case.writes[0], out[0..case.writes[0].len]); try std.testing.expectEqualStrings(case.writes[1], out[case.writes[0].len..len]); } } pub const Error = feed.StreamError || error{ SessionClosed, SessionFailed, SessionCancelled, WrongContext, WrongSession, StaleHandle, StaleRequest, InvalidTicket, RequestLimit, RendererAlreadyAttached, RendererNotAttached, PresentationPending, PresentationFailed, IncompatibleOutput, UnsupportedResource, SplitRenderPending, InvalidOptions, InvalidTerminalState, TerminalInactive, InvalidClock, InvalidBudget, ControlPacketTooLarge, FrameBusy, StaleFrame, SceneNotAttached, }; pub const Options = struct { /// Fixed chunk storage and retained-payload limit: chunk_size * chunk_count. /// Atomic writes use a whole chunk for each span, even for short writes. chunk_size: u32 = 64 * 1024, chunk_count: u32 = 2, span_capacity: u32 = 2, /// Control bytes held inside chunk storage, rounded up to whole chunks. /// Zero disables reservation; leave at least one ordinary chunk and span slot. control_capacity: u32 = 0, }; pub const RendererOptions = struct { remote_mode: terminal.RemoteMode = .local, /// Borrowed until Session destruction. An empty map excludes the host environment. env_map: ?*const std.process.Environ.Map = null, /// Copied during attachment. Mutually exclusive with the authoritative env_map. forwarded_env: ?[]const EnvironmentEntry = null, }; pub const EnvironmentEntry = struct { key: []const u8, value: []const u8 }; // Initialization budgets include the two u32 lengths encoded for each entry. pub const environment_entries_max: u32 = api.OT_SESSION_ENV_ENTRIES_MAX; pub const environment_bytes_max: u32 = api.OT_SESSION_ENV_BYTES_MAX; pub const TerminalOptions = struct { use_alternate_screen: bool = true, mouse: bool = true, mouse_movement: bool = true, kitty_keyboard_flags: u8 = (terminal.Options{}).kitty_keyboard_flags, /// Applies to both suspension and close, as in renderer restoration, once /// setup or resume has claimed the main-screen surface. clear_on_close: bool = true, /// End the startup query batch with DA1 instead of sending DA1 mid-batch. reply_sentinel: bool = false, synchronized_output: terminal.SynchronizedOutput = .auto, host_multiplexer: bool = false, }; pub const TerminalPhase = enum(u8) { uninitialized, setting_up, active, suspending, suspended, resuming, closing, restored, failed, cancelled, }; pub const TerminalState = struct { phase: TerminalPhase, deadline_ns: ?u64, }; pub const MouseMode = enum(u8) { disabled, drag, motion }; pub const CursorOptions = struct { position: ?struct { x: i32, y: i32, visible: bool } = null, style: ?terminal.CursorStyle = null, blinking: ?bool = null, color: ?ansi.RGBA = null, cursor: ?terminal.MousePointerStyle = null, }; pub const ProgramState = enum(u8) { idle = 1, working, done, blocked, @"error", clear }; pub const ProgramKind = enum(u8) { permission = 1, question, auth }; /// One OSC 7501 Program Status Protocol report. Empty strings omit their key; /// an empty id addresses the root record. Title and message are UTF-8 text. pub const ProgramStatus = struct { state: ProgramState, id: []const u8 = "", kind: ?ProgramKind = null, progress: ?u8 = null, app: []const u8 = "", title: []const u8 = "", message: []const u8 = "", }; /// Complete read-only OSC palette queries, optionally wrapped for tmux. pub const PaletteQuery = struct { bytes: []const u8, /// Appends DA1 after the validated queries, in the same packet. sentinel: bool = false, }; /// Byte slices are borrowed for this call only. Replies must contain complete /// 7-bit ASCII CSI, DCS, OSC, or APC capability responses, not input-stream chunks. pub const Control = union(enum) { capability_response: []const u8, /// UTF-8 without C0, DEL, or C1 controls; at most title_bytes_max bytes. title: []const u8, mouse: MouseMode, /// Zero disables Kitty keyboard; other flags apply when support is detected. kitty_keyboard_flags: u8, restore_modes, /// True appends DA1, the sentinel that ends this query batch. query_pixel_resolution: bool, /// The host stopped waiting for DA1 after a miss, so later pushes send no Kitty keyboard query. end_reply_sentinel, /// True appends DA1, the sentinel that ends this query batch. query_theme_colors: bool, palette_query: PaletteQuery, reset_background, /// Desired cursor state only; the frame encoder owns output admission. cursor: CursorOptions, /// Validated against the protocol limits below; never multiplexer-wrapped. program_status: ProgramStatus, }; pub const InputFeed = struct { consumed: u32, discarded: u32, deadline_ns: ?u64, }; pub const PumpStatus = enum(u8) { idle, again, output_pending, wait_until, closed }; pub const PumpResult = struct { status: PumpStatus, deadline_ns: ?u64 = null, }; pub const control_packet_bytes_max: u32 = 4096; pub const capability_response_bytes_max: u32 = control_packet_bytes_max; pub const title_bytes_max: u32 = control_packet_bytes_max - "\x1b]0;\x07".len; pub const program_status_id_bytes_max: u32 = 128; pub const program_status_id_segment_bytes_max: u32 = 32; pub const program_status_id_segments_max: u32 = 8; pub const program_status_app_bytes_max: u32 = 32; pub const program_status_title_bytes_max: u32 = 192; pub const program_status_message_bytes_max: u32 = 2048; /// A valid report with every key at its longest value. pub const program_status_bytes_max: u32 = "\x1b]7501;state=blocked:id=:kind=permission:progress=100:app=:title=:msg=\x1b\\".len + program_status_id_bytes_max + program_status_app_bytes_max + std.base64.standard.Encoder.calcSize(program_status_title_bytes_max) + std.base64.standard.Encoder.calcSize(program_status_message_bytes_max); pub const cursor_settle_ns: u64 = 10 * std.time.ns_per_ms; pub const split_snapshots_max: u32 = api.OT_SPLIT_SNAPSHOTS_MAX; pub const SplitControl = union(enum) { reset: struct { seed_rows: u32, pinned_render_offset: u32 }, sync: u32, output_offset: u32, render_offset: u32, transition: renderer.SplitFooterTransition, clear_transition, }; /// Declaration order is step order; Lifecycle.assertValid relies on it. const Step = enum { idle, query, setup_screen, reserve_rows, enable, activate, delete_images, reset_input, restore_rows, reset_output, settle_first, show_cursor, settle_second, }; const Lifecycle = struct { phase: TerminalPhase = .uninitialized, step: Step = .idle, mouse: bool = false, mouse_movement: bool = true, rows_remaining: u32 = 0, /// Main-screen rows that enable moves back up. Fixed when setup or resume is /// accepted, because split controls and snapshots can change renderOffset later. rows_return: u32 = 0, /// Enable has published, so restoration may clear the rendered main-screen /// area. Before that, the visible screen still holds shell output. screen_claimed: bool = false, /// A late close dropped output, which may have cut a frame inside its synchronized update. dropped: bool = false, image_index: usize = 0, deadline_ns: ?u64 = null, fn assertValid(self: Lifecycle, state: State) void { const step = @backingInt(self.step); std.debug.assert(switch (self.phase) { .uninitialized, .active, .suspended, .restored, .failed, .cancelled => self.step == .idle, .setting_up => step >= @backingInt(Step.query) and step <= @backingInt(Step.activate), .resuming => step >= @backingInt(Step.setup_screen) and step <= @backingInt(Step.activate), .suspending, .closing => step >= @backingInt(Step.delete_images), }); std.debug.assert((state == .failed) == (self.phase == .failed)); std.debug.assert((state == .cancelled) == (self.phase == .cancelled)); if (self.phase == .closing) std.debug.assert(state == .closing); } }; pub const State = enum { open, closing, closed, failed, cancelled }; pub const RenderStatus = enum { /// This frame has completed presentation. presented, /// One accepted frame still awaits output completion; no second frame is accepted. pending, /// Output pressure rejected and cleared the drawn frame without publishing bytes. skipped, /// The frame cannot be published: it is larger than the empty queue, or /// encoding or allocation failed. No bytes were published; transport stays open. failed, }; pub const OutputTicket = struct { session: handles.Handle, request_id: u64, len: u32, }; /// Written acknowledges the entire copy. The host handles partial I/O itself. pub const OutputResult = enum { written, failed }; /// A stdout writer collect or post: bytes completed by this call, and whether a copy is still /// being written when it returns. pub const PostResult = struct { written: u32 = 0, in_flight: bool = false }; /// Context-owned, address-stable transport and optional renderer. Use Context's /// checked methods. Session owns output, presentation, terminal lifecycle, and /// destruction. Legacy renderer setup must remain disabled. pub const Session = struct { handle: handles.Handle, output: *feed.Stream, renderer: ?*renderer.CliRenderer = null, scene: ?*scene.Scene = null, state: State = .open, span: ?feed.SpanInfo = null, span_offset: u32 = 0, pending: ?OutputTicket = null, /// `pending` belongs to the stdout writer: no host ticket can complete it. pending_post: bool = false, /// The stdout writer, created by the first post. stdout_post: ?stdout_writer.Abandon = null, last_request_id: u64 = 0, /// Successful ticket bytes, not retained span charges or discarded output. completed_bytes: u64 = 0, /// The screen and Kitty keyboard as the terminal has them while a packet that may switch them is queued, up /// to `end`. The model counts a switch once it is queued, so a late close that drops it restores these. wire: struct { alt_screen: bool = false, use_alternate: bool = false, kitty_keyboard: bool = false, end: u64 = 0 } = .{}, frame_end_offset: ?u64 = null, lifecycle: Lifecycle = .{}, // Pump and Kitty polling share one accepted host clock. last_pump_ns: ?u64 = null, // Cancel revokes authority, but outstanding scopes still pin renderer storage. frame_lease_count: u32 = 0, input: input_parser.InputParser = .{}, /// Host expectations; feeds add the terminal's Kitty keyboard state. input_expect: input_parser.Expectations = .{}, // Input feeds keep their own monotonic host clock, separate from pump time. last_input_ns: ?u64 = null, pub fn deinit(self: *Session) error{Busy}!void { if (!self.canDestroy()) return error.Busy; std.debug.assert(self.span == null and self.pending == null); self.abandonStdout(); if (self.renderer) |value| value.destroyStorage(); if (self.scene) |value| value.deinit(); self.output.destroy(); } /// Copies a complete write or rejects it without publishing any bytes. pub fn write(self: *Session, bytes: []const u8) Error!void { try self.checkWriting(); try self.output.writeAtomic(bytes); } fn checkWriting(self: *const Session) Error!void { try self.checkOpen(); switch (self.lifecycle.phase) { .uninitialized, .active, .suspended => {}, else => return error.Busy, } } pub fn checkOpen(self: *const Session) Error!void { switch (self.state) { .open => {}, .closing, .closed => return error.SessionClosed, .failed => return error.SessionFailed, .cancelled => return error.SessionCancelled, } } /// Accepts at most one deferred frame. Even a no-byte frame waits for earlier /// raw output; later raw writes do not delay that frame's presentation. pub fn render(self: *Session, force: bool) Error!RenderStatus { try self.checkRendering(); try self.checkFrameIdle(); if (self.scene) |owned| { if (owned.cancelled_paint) return error.StaleFrame; } if (self.renderer) |attached| attached.leaveRetained(); return self.renderReady(force, null, null, null); } /// Every returned status consumes the draft, including skipped and failed. /// Admission errors preserve it for retry after the caller resolves the error. pub fn commitSceneFrame(self: *Session, frame: scene.FrameRequest, force: bool) Error!RenderStatus { try self.checkRendering(); const owned = self.scene orelse return error.SceneNotAttached; const painted = try owned.checkPainted(frame); if (self.frame_lease_count != 0) return error.FrameBusy; const attached = self.renderer orelse return error.RendererNotAttached; if (!painted.destination.matches(attached.getNextBuffer())) return error.StaleFrame; if (self.frame_end_offset != null) return error.PresentationPending; const status = try self.renderReady(force, null, painted.work, painted.damage); owned.painted = null; // A failed encoder may leave scratch cells intact, but cannot authorize their replay. owned.cancelled_paint = status == .failed; return status; } pub fn copySceneFrame(self: *Session, frame: scene.FrameRequest, target: *buffer.OptimizedBuffer) !void { try self.checkRendering(); if (self.frame_lease_count != 0) return error.FrameBusy; if (self.frame_end_offset != null) return error.PresentationPending; const owned = self.scene orelse return error.SceneNotAttached; const painted = try owned.checkPainted(frame); const source = (self.renderer orelse return error.RendererNotAttached).getNextBuffer(); if (!painted.destination.matches(source)) return error.StaleFrame; if (target.owner_context_id != self.handle.context_id) return error.WrongContext; try target.copyFrom(source); } /// Snapshot serialization may materialize image fallbacks. Private, bounded /// copies keep both rejected admission and in-flight output from changing sources. pub fn renderSplit(self: *Session, frame: ?scene.FrameRequest, snapshots: []const renderer.SplitSnapshot, pinned_render_offset: u32, force: bool) !RenderStatus { const suspended_snapshots = frame == null and self.lifecycle.phase == .suspended; if (suspended_snapshots) { try self.checkOpen(); } else { try self.checkRendering(); } const attached = self.renderer orelse return error.RendererNotAttached; if (frame == null and self.frame_end_offset != null) return .pending; if (snapshots.len > split_snapshots_max or pinned_render_offset > std.math.maxInt(u16)) return error.InvalidOptions; var work: ?renderer.FrameWork = null; var damage: ?*const std.DynamicBitSetUnmanaged = null; if (frame) |request| { const owned = self.scene orelse return error.SceneNotAttached; const painted = try owned.checkPainted(request); work = painted.work; damage = painted.damage; if (self.frame_lease_count != 0) return error.FrameBusy; if (!painted.destination.matches(attached.getNextBuffer())) return error.StaleFrame; if (self.frame_end_offset != null) return error.PresentationPending; } else try self.checkFrameIdle(); var copies: [split_snapshots_max]renderer.SplitSnapshot = undefined; var count: usize = 0; defer for (copies[0..count]) |copy| copy.snapshot.deinit(); var remaining = self.output.options.max_bytes; for (snapshots) |commit| { const source = commit.snapshot; const cells = @as(u64, source.width) * source.height; const bytes = std.math.mul(u64, cells, 24) catch return error.InvalidOptions; if (bytes > remaining or commit.row_columns > source.width) return error.InvalidOptions; remaining -= bytes; const copy = try buffer.OptimizedBuffer.init(attached.allocator, source.width, source.height, .{ .pool = source.pool, .link_pool = source.link_pool, .width_method = source.width_method, .logger = source.logger, }); copies[count] = commit; copies[count].snapshot = copy; count += 1; copy.owner_context_id = source.owner_context_id; try Context.drawContextBuffer(copy, source, 0, 0, .{}); } const status = try self.renderReady(force, .{ .snapshots = copies[0..count], .pinned_render_offset = pinned_render_offset, .paint_footer = frame != null, .suspended = suspended_snapshots, }, work, damage); if (frame != null) { self.scene.?.painted = null; self.scene.?.cancelled_paint = status == .failed; } return status; } /// work is the committed scene draft's counts; it is published only if this frame presents. fn renderReady(self: *Session, force: bool, split: ?renderer.SplitRender, work: ?renderer.FrameWork, damage: ?*const std.DynamicBitSetUnmanaged) Error!RenderStatus { const value = self.renderer orelse return error.RendererNotAttached; value.scene_work = work; value.scene_damage = damage; defer value.scene_work = null; defer value.scene_damage = null; if (self.frame_end_offset != null) return .pending; const lifecycle_active = self.lifecycle.phase == .active; const previous_reservation = self.output.control_sequence; if (lifecycle_active) { const count = @max(value.currentImages.items.len, value.nextRenderBuffer.image_placements.items.len); try self.reserveControlSequence(try cleanupPackets(count)); // A frame publishes no control spans, so restoring the reservation cannot fail. std.debug.assert(self.output.control_spans == 0); } var accepted = false; defer if (lifecycle_active and !accepted) { self.output.setControlSequenceReservation(previous_reservation) catch unreachable; }; const result = if (split) |options| try value.renderSplitDeferred(options, force) else try value.renderDeferred(force); // The Session endpoint and the renderer's pending presentation are one state. std.debug.assert((result == .rendered) == (value.pendingPresentation != null)); switch (result) { .skipped => return .skipped, .failed => return .failed, .rendered => {}, } accepted = true; self.frame_end_offset = self.output.getStats().bytes_written; std.debug.assert(self.completed_bytes <= self.frame_end_offset.?); if (self.completed_bytes == self.frame_end_offset.?) { self.finishPresentation(.presented); return .presented; } return .pending; } pub fn checkRendering(self: *const Session) Error!void { try self.checkOpen(); switch (self.lifecycle.phase) { .uninitialized, .active => {}, else => return error.TerminalInactive, } } pub fn checkResizing(self: *const Session) Error!void { if (self.lifecycle.phase == .suspended) return self.checkOpen(); try self.checkRendering(); } pub fn splitControl(self: *Session, command: SplitControl) Error!u32 { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (command == .output_offset) return value.getSplitOutputOffset(command.output_offset); try self.checkFrameIdle(); if (self.frame_end_offset != null) return error.PresentationPending; switch (command) { .reset => |options| { if (options.seed_rows > std.math.maxInt(u16) or options.pinned_render_offset > std.math.maxInt(u16)) return error.InvalidOptions; return value.resetSplitScrollback(options.seed_rows, options.pinned_render_offset); }, .sync => |offset| { if (offset > std.math.maxInt(u16)) return error.InvalidOptions; return value.syncSplitScrollback(offset); }, .render_offset => |offset| { if (offset > std.math.maxInt(u16)) return error.InvalidOptions; value.renderOffset = offset; }, .transition => |transition| { if (@as(u64, transition.source_top_line) + transition.source_height > std.math.maxInt(u16) or @as(u64, transition.target_top_line) + transition.target_height > std.math.maxInt(u16) or transition.scroll_lines > std.math.maxInt(u16)) return error.InvalidOptions; value.pendingSplitFooterTransition = transition; }, .clear_transition => value.clearPendingSplitFooterTransition(), .output_offset => unreachable, } return value.renderOffset; } pub fn setScreen(self: *Session, alternate: bool, width: u32, height: u32, trailing_output: []const u8) !void { try self.checkOpen(); try self.checkFrameIdle(); if (self.frame_end_offset != null) return error.PresentationPending; const value = self.renderer orelse return error.RendererNotAttached; var candidate = value.terminal; var bytes: [control_packet_bytes_max]u8 = undefined; var writer: std.Io.Writer = .fixed(&bytes); switch (self.lifecycle.phase) { .uninitialized, .suspended => {}, .active => { if (value.useAlternateScreen != alternate) { const keyboard_flags = candidate.state.kitty_keyboard_flags; const keyboard_enabled = candidate.state.kitty_keyboard; try candidate.setKittyKeyboard(&writer, false, 0); if (alternate) try candidate.enterAltScreen(&writer) else try candidate.exitAltScreen(&writer); if (keyboard_enabled) try candidate.setKittyKeyboard(&writer, true, keyboard_flags); } }, else => return error.TerminalInactive, } if (trailing_output.len > bytes.len - writer.buffered().len) return error.InvalidOptions; try writer.writeAll(trailing_output); try value.resizeWithOutput(width, height, writer.buffered()); self.queueSwitch(value); candidate.state.cursor = value.terminal.state.cursor; value.terminal.state = candidate.state; value.useAlternateScreen = alternate; value.imageScreenInvalidated = true; value.invalidateTerminalState(); } pub fn syncDetached(self: *Session, parent: *Session) Error!void { try self.checkOpen(); try parent.checkOpen(); try self.checkFrameIdle(); if (self.handle.context_id != parent.handle.context_id) return error.WrongContext; if (self == parent or self.lifecycle.phase != .uninitialized or self.frame_end_offset != null) return error.InvalidOptions; const value = self.renderer orelse return error.RendererNotAttached; const source = parent.renderer orelse return error.RendererNotAttached; value.terminal.caps = source.terminal.caps; value.terminal.image_protocol = source.terminal.image_protocol; value.image_resolution = source.image_resolution; self.syncWidthMethod(value); } /// When the terminal's width method changes, the text the scene shows follows it. fn syncWidthMethod(self: *Session, value: *renderer.CliRenderer) void { const before = value.getNextBuffer().width_method; value.syncWidthMethod(); const after = value.getNextBuffer().width_method; if (after != before) if (self.scene) |owned| Context.followWidthMethod(owned, after); } pub fn checkFrameIdle(self: *const Session) Error!void { if (self.frame_lease_count != 0) return error.FrameBusy; if (self.scene) |owned| { if (owned.attempt != null or owned.painted != null) return error.FrameBusy; } } pub fn checkLayoutIdle(self: *const Session) Error!void { if (self.scene) |owned| { if (owned.attempt != null) return error.FrameBusy; } } pub fn cancelSceneFrame(self: *Session) void { if (self.scene) |owned| { if (owned.painted != null) { if (self.renderer) |attached| { attached.getNextBuffer().clearScissorRects(); attached.getNextBuffer().clearOpacity(); // A cancelled draft is never presented, painted or skipped. attached.taint(renderer.FrameWork.full_path_unretained); } } owned.cancelFrame(); } } /// Initial managed setup must precede accepted frames: switching screens would /// strand their image state. Earlier raw output may still be queued or copied. /// This accepts a request; pump emits its packets after that output completes. pub fn setupTerminal(self: *Session, options: TerminalOptions) Error!void { try self.checkOpen(); try self.checkLayoutIdle(); const value = self.renderer orelse return error.RendererNotAttached; if (self.lifecycle.phase != .uninitialized) return error.InvalidTerminalState; if (self.frame_end_offset != null or value.renderStats.frameCount != 0) return error.InvalidTerminalState; try self.checkTerminalStart(options.kitty_keyboard_flags); const rows = if (options.use_alternate_screen) 0 else value.height - 1; const packets = try setupPackets(try cleanupPackets(0), rows, true); try self.reserveControlSequence(packets); value.useAlternateScreen = options.use_alternate_screen; value.clearOnShutdown = options.clear_on_close; value.terminal.reply_sentinel = options.reply_sentinel; value.terminal.explicit_width_probed = options.use_alternate_screen and value.height >= 3; value.terminal.synchronized_output = options.synchronized_output; value.terminal.multiplexer_on_host = options.host_multiplexer; value.terminal.opts.kitty_keyboard_flags = options.kitty_keyboard_flags; self.lifecycle = .{ .phase = .setting_up, .step = .query, .mouse = options.mouse, .mouse_movement = options.mouse_movement, .rows_remaining = rows, .rows_return = if (value.renderOffset == 0) rows else 0, }; } pub fn suspendTerminal(self: *Session) Error!void { try self.checkOpen(); try self.checkLayoutIdle(); switch (self.lifecycle.phase) { .suspending, .suspended => return, .active => {}, else => return error.InvalidTerminalState, } const value = self.renderer.?; value.terminalSuspended = true; value.cancelKittyImageTransport(false); self.lifecycle.phase = .suspending; self.lifecycle.step = .delete_images; self.lifecycle.image_index = 0; } pub fn resumeTerminal(self: *Session) Error!void { try self.checkOpen(); if (self.lifecycle.phase != .suspended) return error.InvalidTerminalState; const value = self.renderer.?; try self.checkTerminalStart(value.terminal.opts.kitty_keyboard_flags); const rows = if (!value.useAlternateScreen and value.renderOffset == 0) value.height - 1 else 0; const packets = try setupPackets(try cleanupPackets(value.currentImages.items.len), rows, false); try self.reserveControlSequence(packets); value.terminal.setCursorPosition(1, 1, false); value.terminalSuspended = false; self.lifecycle.phase = .resuming; self.lifecycle.step = .setup_screen; self.lifecycle.rows_remaining = rows; self.lifecycle.rows_return = rows; } pub fn getTerminalState(self: *const Session) TerminalState { return .{ .phase = self.lifecycle.phase, .deadline_ns = self.lifecycle.deadline_ns }; } /// Emitting controls use ordinary capacity, never restoration storage or headroom. /// Also accepts capability replies during setup after query publication and during resume. /// Cursor intent and the sentinel end are synchronous in any open phase; other controls require active. /// Queued and copied output stays ahead. /// Rejection preserves state and output. No allocation or host I/O occurs. pub fn control(self: *Session, command: Control) Error!void { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (command == .cursor) { const options = command.cursor; if (options.position) |position| { // Terminal restoration also stores zero-based rows and columns as u16. const position_max = @as(i32, std.math.maxInt(u16)) + 1; if (position.x > position_max or position.y > position_max) return error.InvalidOptions; value.terminal.setCursorPosition(@intCast(@max(1, position.x)), @intCast(@max(1, position.y)), position.visible); if (self.scene) |owned| owned.editor_cursor_owned = false; } const current = value.terminal.getCursorStyle(); value.terminal.setCursorStyle(options.style orelse current.style, options.blinking orelse current.blinking); if (options.color) |color| value.terminal.setCursorColor(color); if (options.cursor) |cursor| value.terminal.setMousePointerStyle(cursor); return; } if (command == .end_reply_sentinel) { value.terminal.reply_sentinel = false; return; } // Malformed input is rejected in every phase, before lifecycle admission. switch (command) { .title => |title| try validateText(title, title_bytes_max), .kitty_keyboard_flags => |flags| { if (flags & ~@as(u8, api.OT_KITTY_KEYBOARD_ALL) != 0) return error.InvalidOptions; }, .palette_query => |query| try validatePaletteQuery(query.bytes), .program_status => |status| try validateProgramStatus(status), else => {}, } switch (self.lifecycle.phase) { .active => {}, .setting_up, .resuming => { if (command != .capability_response or self.lifecycle.step == .query) { return error.TerminalInactive; } }, else => return error.TerminalInactive, } self.assertTerminalOutput(); try self.publishTerminalPacket(command); } /// UTF-8 without C0, DEL, or C1 controls. fn validateText(text: []const u8, bytes_max: u32) Error!void { if (text.len > bytes_max or !std.unicode.utf8ValidateSlice(text) or utf8.containsControl(text)) return error.InvalidOptions; } /// Rejects every report a terminal would discard or partly ignore, so each /// accepted report means exactly what its fields say. fn validateProgramStatus(status: ProgramStatus) Error!void { if (status.kind != null and status.state != .blocked) return error.InvalidOptions; if (status.progress) |progress| { if (progress > 100) return error.InvalidOptions; if (status.state != .working and status.state != .blocked) return error.InvalidOptions; } if (status.state == .clear and (status.app.len != 0 or status.title.len != 0 or status.message.len != 0)) { return error.InvalidOptions; } if (status.id.len > program_status_id_bytes_max) return error.InvalidOptions; if (std.mem.countScalar(u8, status.id, '/') >= program_status_id_segments_max) return error.InvalidOptions; if (status.id.len != 0) { var segments = std.mem.splitScalar(u8, status.id, '/'); while (segments.next()) |segment| try validateProgramStatusName(segment, program_status_id_segment_bytes_max); } if (status.app.len != 0) try validateProgramStatusName(status.app, program_status_app_bytes_max); try validateText(status.title, program_status_title_bytes_max); try validateText(status.message, program_status_message_bytes_max); } fn validateProgramStatusName(name: []const u8, bytes_max: u32) Error!void { if (name.len == 0 or name.len > bytes_max) return error.InvalidOptions; for (name) |byte| { if (!std.ascii.isAlphanumeric(byte) and std.mem.findScalar(u8, "_.+-", byte) == null) { return error.InvalidOptions; } } } pub fn setPaletteState(self: *Session, palette: []const ansi.RGBA, default_fg: ansi.RGBA, default_bg: ansi.RGBA, epoch: u32) Error!void { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (self.lifecycle.phase != .active) return error.TerminalInactive; if (palette.len > 256) return error.InvalidOptions; value.setPaletteState(palette, default_fg, default_bg, epoch); } /// Reuses terminal protocol selection and encoding; rejected output cannot consume an ID. pub fn triggerNotification(self: *Session, message: []const u8, title: ?[]const u8) Error!bool { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (self.lifecycle.phase != .active) return error.TerminalInactive; self.assertTerminalOutput(); const title_len = if (title) |text| text.len else 0; if (message.len > control_packet_bytes_max or title_len > control_packet_bytes_max - message.len) return false; var candidate = value.terminal; var bytes: [control_packet_bytes_max]u8 = undefined; var writer: std.Io.Writer = .fixed(&bytes); if (!(candidate.writeNotification(value.allocator, &writer, message, title) catch return false)) return false; self.output.writeAtomic(writer.buffered()) catch return false; value.terminal.notification_id_counter = candidate.notification_id_counter; return true; } pub fn setKittyImageTransport(self: *Session, mode: u32) Error!void { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (!value.setKittyImageTransport(mode)) return error.InvalidOptions; if (self.lifecycle.phase == .active) self.startKittyProbe(value); } /// A probe that output dropped never reaches the terminal; a later start retries it. fn startKittyProbe(self: *Session, value: *renderer.CliRenderer) void { const idle = value.kittyTransport.file_state == .disabled; const published = self.output.getStats().bytes_written; value.startKittyFileProbeFromSession(); const dropped = self.output.getStats().bytes_written == published; if (idle and dropped and value.kittyTransport.file_state == .probing) value.kittyTransport.cancel(.disabled); } pub fn kittyImageTransportStatus(self: *Session) Error![6]u32 { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; return value.kittyImageTransportStatus(); } pub fn pollKittyImageTransport(self: *Session, now_ns: u64) Error!bool { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; try self.checkClock(now_ns); self.last_pump_ns = now_ns; value.kittyTransport.expire(now_ns); return value.pollKittyImageTransport(); } pub fn cancelKittyImageTransport(self: *Session, failed: bool) Error!void { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; value.cancelKittyImageTransport(failed); } pub fn processKittyImageReply(self: *Session, response: []const u8) Error!u32 { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; return value.processKittyImageReply(response); } pub fn startKittyFileProbe(self: *Session) Error!void { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (self.lifecycle.phase == .active) self.startKittyProbe(value); } fn validatePaletteQuery(bytes: []const u8) Error!void { if (bytes.len == 0 or bytes.len > control_packet_bytes_max) return error.InvalidOptions; const wrapped = std.mem.startsWith(u8, bytes, ansi.ANSI.tmuxDcsStart); var rest = bytes; if (wrapped) { if (!std.mem.endsWith(u8, rest, ansi.ANSI.tmuxDcsEnd)) return error.InvalidOptions; rest = rest[ansi.ANSI.tmuxDcsStart.len .. rest.len - ansi.ANSI.tmuxDcsEnd.len]; if (rest.len == 0) return error.InvalidOptions; } const prefix = if (wrapped) "\x1b\x1b]4;" else "\x1b]"; while (rest.len != 0) { if (!std.mem.startsWith(u8, rest, prefix)) return error.InvalidOptions; rest = rest[prefix.len..]; const end = std.mem.findScalar(u8, rest, ';') orelse return error.InvalidOptions; if (end == 0 or end > 3) return error.InvalidOptions; const number = std.fmt.parseInt(u16, rest[0..end], 10) catch return error.InvalidOptions; rest = rest[end + 1 ..]; if (!wrapped and number == 4) { const index_end = std.mem.findScalar(u8, rest, ';') orelse return error.InvalidOptions; if (index_end == 0 or index_end > 3) return error.InvalidOptions; _ = std.fmt.parseInt(u8, rest[0..index_end], 10) catch return error.InvalidOptions; rest = rest[index_end + 1 ..]; } else if (wrapped) { if (number > 255) return error.InvalidOptions; } else if (!(number >= 10 and number <= 17) and number != 19) return error.InvalidOptions; if (!std.mem.startsWith(u8, rest, "?\x07")) return error.InvalidOptions; rest = rest[2..]; } } /// Copies a complete OSC 52 sequence or returns false on unsupported capability, /// payload limits, allocation failure, or output pressure. No host I/O occurs. pub fn writeClipboard(self: *Session, target: terminal.ClipboardTarget, bytes: []const u8) Error!bool { try self.checkOpen(); const value = self.renderer orelse return error.RendererNotAttached; if (self.lifecycle.phase != .active) return error.TerminalInactive; self.assertTerminalOutput(); // Only this call stages bytes, and it clears them before returning. std.debug.assert(self.output.staged_bytes == 0); const output_len = value.terminal.clipboardSequenceSize(bytes.len) catch return false; // Charge ordinary capacity before allocating or encoding large payloads. // Clipboard writes cannot borrow restoration storage or counter headroom. self.output.setStagedBytes(output_len) catch return false; defer self.output.setStagedBytes(0) catch unreachable; const output_bytes = value.allocator.alloc(u8, output_len) catch return false; defer value.allocator.free(output_bytes); var writer: std.Io.Writer = .fixed(output_bytes); value.terminal.writeClipboard(&writer, target, bytes) catch return false; std.debug.assert(writer.buffered().len == output_len); self.output.setStagedBytes(0) catch unreachable; self.output.writeAtomic(writer.buffered()) catch return false; return true; } /// One work unit visits one image entry (including non-Kitty entries), emits /// at most 4096 control bytes, or advances one state. Budget must be nonzero. /// now_ns shares a monotone host clock with Kitty polling. Cursor delays begin /// when a pump observes completed output. The first wait requires room for both /// waits; a cursor retry requires room for the final wait. Also visits at most /// eight file leases, even under output pressure. No clock reads or sleeps. pub fn pump(self: *Session, now_ns: u64, work_budget: u32) Error!PumpResult { if (work_budget == 0) return error.InvalidBudget; try self.checkClock(now_ns); switch (self.state) { .open, .closing => {}, .closed => return .{ .status = .closed }, .failed => return error.SessionFailed, .cancelled => return error.SessionCancelled, } const previous_now = self.last_pump_ns; self.last_pump_ns = now_ns; errdefer self.last_pump_ns = previous_now; const result = try self.pumpWork(now_ns, work_budget); if (self.renderer) |value| value.kittyTransport.expire(now_ns); return result; } /// Parses terminal input into caller-owned records in every open lifecycle /// phase. Feeds share one monotonic clock; rejection leaves the parser unchanged. pub fn feedInput(self: *Session, bytes: []const u8, now_ns: u64, sink: *input_parser.Sink) Error!InputFeed { try self.checkOpen(); if (self.last_input_ns) |previous| { if (now_ns < previous) return error.InvalidClock; } self.last_input_ns = now_ns; var expect = self.input_expect; // The host only requests Kitty keyboard; setup pushes its flags once the terminal reports support, // and the reply to the push's own query confirms them. if (self.renderer) |value| { expect.kitty_keyboard = value.terminal.state.kitty_keyboard; expect.escape_prefix = value.terminal.state.kitty_confirmed; expect.kitty_query = value.terminal.kittyQueryOutstanding(); } self.input.setExpectations(expect); const consumed = self.input.feed(bytes, now_ns, sink); return .{ .consumed = consumed, .discarded = self.input.discarded_count, .deadline_ns = self.input.deadlineNs() }; } /// Emits nothing; the next feed resolves a unit that may no longer wait. pub fn setInputExpectations(self: *Session, expect: input_parser.Expectations) Error!void { try self.checkOpen(); self.input_expect = expect; } /// With `keep_reply`, a pending reply prefix survives while the host expects replies. pub fn resetInput(self: *Session, keep_reply: bool) Error!void { try self.checkOpen(); self.input.reset(keep_reply and self.input_expect.replies); } fn checkClock(self: *const Session, now_ns: u64) Error!void { if (self.last_pump_ns) |previous| { if (now_ns < previous) return error.InvalidClock; } } /// Process-exit fallback only: stop admission and visit one restoration unit /// without cursor-settle waits. Output still requires successful completion; /// pending tickets and failed transports are never replayed or bypassed. pub fn pumpExit(self: *Session) Error!PumpStatus { try self.beginClose(); if (self.state == .closed) return .closed; return (try self.pumpWork(null, 1)).status; } fn pumpWork(self: *Session, now_ns: ?u64, work_budget: u32) Error!PumpResult { defer self.lifecycle.assertValid(self.state); var remaining = work_budget; while (remaining > 0) : (remaining -= 1) { if (!self.isDrained()) return .{ .status = .output_pending }; switch (self.lifecycle.step) { .idle => return .{ .status = .idle }, .activate => { const value = self.renderer.?; try self.reserveControlSequence(try cleanupPackets(value.currentImages.items.len)); value.invalidateTerminalState(); self.lifecycle.phase = .active; self.lifecycle.step = .idle; return .{ .status = .idle }; }, .settle_first, .settle_second => { if (now_ns) |now| { if (self.lifecycle.deadline_ns == null) { const waits: u64 = if (self.lifecycle.step == .settle_first) 2 else 1; _ = std.math.add(u64, now, waits * cursor_settle_ns) catch return error.InvalidClock; self.lifecycle.deadline_ns = now + cursor_settle_ns; } const deadline = self.lifecycle.deadline_ns.?; if (now < deadline) return .{ .status = .wait_until, .deadline_ns = deadline }; } if (self.lifecycle.step == .settle_first) { if (now_ns) |now| { _ = std.math.add(u64, now, cursor_settle_ns) catch return error.InvalidClock; } self.lifecycle.step = .show_cursor; self.lifecycle.deadline_ns = null; } else { // A drained queue holds no control spans, staged, or reserved bytes. self.output.setControlSequenceReservation(.{}) catch unreachable; const value = self.renderer.?; value.currentImages.clearRetainingCapacity(); value.invalidateTerminalState(); self.lifecycle.deadline_ns = null; self.lifecycle.step = .idle; self.lifecycle.screen_claimed = false; self.lifecycle.phase = if (self.state == .closing) .restored else .suspended; if (self.state == .closing) { self.output.close() catch unreachable; self.state = .closed; return .{ .status = .closed }; } return .{ .status = .idle }; } }, else => { if (self.lifecycle.step == .show_cursor) { if (now_ns) |now| { _ = std.math.add(u64, now, cursor_settle_ns) catch return error.InvalidClock; } } try self.publishTerminalPacket(null); }, } } return .{ .status = if (self.isDrained()) .again else .output_pending }; } /// Session renderers own their feed. fn assertTerminalOutput(self: *const Session) void { const value = self.renderer.?; std.debug.assert(value.backend.feed == self.output); std.debug.assert(!value.backend.frameActive); std.debug.assert(self.output.callback == null and !self.output.in_callback); } fn checkTerminalStart(self: *Session, kitty_keyboard_flags: u8) Error!void { self.assertTerminalOutput(); const value = self.renderer.?; // Attachment, resize, and screen changes reject zero rows; reset_output adds one row. std.debug.assert(value.height > 0 and value.renderOffset < std.math.maxInt(u32)); // Reserved rows follow the current footer geometry, which a transition replaces. if (value.pendingSplitFooterTransition.mode != .none) return error.SplitRenderPending; if (kitty_keyboard_flags & ~@as(u8, api.OT_KITTY_KEYBOARD_ALL) != 0) return error.InvalidOptions; if (@as(u64, self.output.control_chunks) * self.output.options.chunk_size < control_packet_bytes_max) { return error.NoSpace; } } fn cleanupPackets(images: usize) Error!u64 { // Reserve the full Windows cursor-row range: a capability reply may still // update the saved row after setup. This is counter headroom, not storage. const rows: u64 = if (builtin.os.tag == .windows) std.math.maxInt(u16) else 0; const row_packets = std.math.divCeil(u64, rows, control_packet_bytes_max / ansi.ANSI.reverseIndex.len) catch unreachable; return std.math.add(u64, images, 4 + row_packets) catch error.NoSpace; } fn setupPackets(cleanup_packets: u64, rows: u32, query: bool) Error!u64 { const row_packets = std.math.divCeil(u64, rows, control_packet_bytes_max) catch unreachable; return std.math.add(u64, cleanup_packets, row_packets + 2 + @intFromBool(query)) catch error.NoSpace; } fn reserveControlSequence(self: *Session, packets: u64) Error!void { const bytes = std.math.mul(u64, packets, control_packet_bytes_max) catch return error.NoSpace; const spans_per_packet = std.math.divCeil(u64, control_packet_bytes_max, self.output.options.chunk_size) catch unreachable; const spans = std.math.mul(u64, packets, spans_per_packet) catch return error.NoSpace; // Tickets copy at least one byte, so byte headroom also covers their request IDs. try self.output.setControlSequenceReservation(.{ .bytes = bytes, .spans = spans }); } fn publishTerminalPacket(self: *Session, command: ?Control) Error!void { const value = self.renderer.?; var candidate = value.terminal; var progress = self.lifecycle; const owned_environment = if (value.terminal.host_env_map) |*map| value.terminal.opts.env_map == map else false; // Environment policy distinguishes a forwarded, self-owned map by address. // The draft borrows its storage; only its self-relative pointer is rebased. if (owned_environment) candidate.opts.env_map = &candidate.host_env_map.?; var bytes: [control_packet_bytes_max]u8 = undefined; var writer: std.Io.Writer = .fixed(&bytes); if (command) |input| { writeControlPacket(input, &candidate, &progress, &writer) catch |err| return switch (err) { error.InvalidOptions => error.InvalidOptions, else => error.ControlPacketTooLarge, }; try self.output.writeAtomic(writer.buffered()); } else { self.writeTerminalPacket(&candidate, &progress, &writer) catch return error.ControlPacketTooLarge; try self.output.writeReservedControlAtomic(writer.buffered()); } if (owned_environment) candidate.opts.env_map = &value.terminal.host_env_map.?; // A reply that changes no capability, such as a Kitty keyboard confirmation, needs no repaint. const repaint = !std.meta.eql(candidate.caps, value.terminal.caps) or candidate.multiplexer != value.terminal.multiplexer; self.queueSwitch(value); value.terminal = candidate; // Releases are not reported while mouse reporting is off (issue 426). if (progress.mouse != self.lifecycle.mouse) self.input.buttons_held = 0; self.lifecycle = progress; self.syncWidthMethod(value); if (command != null and command.? == .capability_response and repaint) value.invalidateTerminalState(); } /// A packet that may switch the screen or Kitty keyboard was queued; the model has not taken it yet. fn queueSwitch(self: *Session, value: *const renderer.CliRenderer) void { if (self.completed_bytes >= self.wire.end) { const state = value.terminal.state; self.wire = .{ .alt_screen = state.alt_screen, .use_alternate = value.useAlternateScreen, .kitty_keyboard = state.kitty_keyboard }; } self.wire.end = self.output.getStats().bytes_written; } fn writeControlPacket(command: Control, candidate: *terminal.Terminal, progress: *Lifecycle, writer: *std.Io.Writer) !void { switch (command) { .capability_response => |response| { try applyCapabilityResponses(candidate, response); // Setup enables modes after screen selection. Kitty's keyboard // stack belongs to that screen, not the previous one. if (progress.phase == .active or progress.step == .activate) { try candidate.enableDetectedFeatures(writer, candidate.opts.kitty_keyboard_flags != 0); } else { candidate.checkEnvironmentOverrides(); } }, .title => |title| try ansi.ANSI.setTerminalTitleOutput(writer, title), .mouse => |mode| { const enabled = mode != .disabled; const movement = if (enabled) mode == .motion else progress.mouse_movement; try candidate.setMouseMode(writer, enabled, movement); progress.mouse = enabled; progress.mouse_movement = movement; }, .kitty_keyboard_flags => |flags| { if (candidate.state.kitty_keyboard and candidate.state.kitty_keyboard_flags != flags) { try candidate.setKittyKeyboard(writer, false, 0); } candidate.setKittyKeyboardFlags(flags); try candidate.enableDetectedFeatures(writer, flags != 0); }, .restore_modes => try candidate.restoreTerminalModes(writer), .query_pixel_resolution => |sentinel| { try writer.writeAll(ansi.ANSI.queryPixelSize); if (sentinel) try writer.writeAll(ansi.ANSI.primaryDeviceAttrs); }, .query_theme_colors => |sentinel| { try candidate.queryThemeColors(writer); if (sentinel) try writer.writeAll(ansi.ANSI.primaryDeviceAttrs); }, .palette_query => |query| { try writer.writeAll(query.bytes); if (query.sentinel) try writer.writeAll(ansi.ANSI.primaryDeviceAttrs); }, .reset_background => try writer.writeAll(ansi.ANSI.resetTerminalBgColor), .cursor, .end_reply_sentinel => unreachable, .program_status => |status| writeProgramStatus(writer, status), } } /// Validation bounds the report, and the bound fits the empty packet, so writing cannot fail. fn writeProgramStatus(writer: *std.Io.Writer, status: ProgramStatus) void { comptime std.debug.assert(program_status_bytes_max <= control_packet_bytes_max); var report: std.ArrayList(u8) = .initBuffer(writer.unusedCapacitySlice()[0..program_status_bytes_max]); report.printAssumeCapacity("\x1b]7501;state={t}", .{status.state}); if (status.id.len != 0) report.printAssumeCapacity(":id={s}", .{status.id}); if (status.kind) |kind| report.printAssumeCapacity(":kind={t}", .{kind}); if (status.progress) |progress| report.printAssumeCapacity(":progress={d}", .{progress}); if (status.app.len != 0) report.printAssumeCapacity(":app={s}", .{status.app}); if (status.title.len != 0) report.printAssumeCapacity(":title={b64}", .{status.title}); if (status.message.len != 0) report.printAssumeCapacity(":msg={b64}", .{status.message}); report.appendSliceAssumeCapacity("\x1b\\"); writer.advance(report.items.len); } fn writeTerminalPacket(self: *Session, candidate: *terminal.Terminal, progress: *Lifecycle, writer: *std.Io.Writer) !void { const value = self.renderer.?; switch (progress.step) { .query => { // Initialize before replies can supply the startup cursor position. candidate.setCursorPosition(1, 1, false); try candidate.queryTerminalSend(writer); progress.step = .setup_screen; }, .setup_screen => { try writer.writeAll(ansi.ANSI.saveCursorState); if (value.useAlternateScreen) try candidate.enterAltScreen(writer); if (progress.phase == .setting_up and candidate.explicit_width_probed) try candidate.queryExplicitWidth(writer); progress.step = if (progress.rows_remaining == 0) .enable else .reserve_rows; }, .reserve_rows => { const count = @min(progress.rows_remaining, control_packet_bytes_max); try writer.splatByteAll('\n', count); progress.rows_remaining -= count; if (progress.rows_remaining == 0) progress.step = .enable; }, .enable => { if (progress.rows_return != 0) try writer.print("\x1b[{d}A", .{progress.rows_return}); try writer.writeAll(ansi.ANSI.hideCursor); try candidate.enableDetectedFeatures(writer, candidate.opts.kitty_keyboard_flags != 0); try candidate.setMouseMode(writer, progress.mouse, progress.mouse_movement); // Terminals answer in order: the DA1 reply follows every other reply of the setup. if (progress.phase == .setting_up and candidate.reply_sentinel) try writer.writeAll(ansi.ANSI.primaryDeviceAttrs); progress.screen_claimed = true; progress.step = .activate; }, .delete_images => { if (progress.image_index < value.currentImages.items.len) { try value.writeShutdownImage(writer, progress.image_index); progress.image_index += 1; } if (progress.image_index == value.currentImages.items.len) progress.step = .reset_input; }, .reset_input => { if (progress.dropped) try writer.writeAll(ansi.ANSI.syncReset); try candidate.resetInputModes(writer); progress.step = .reset_output; if (candidate.state.alt_screen) { try candidate.exitAltScreen(writer); } else if (builtin.os.tag == .windows and candidate.opts.remote_mode != .remote and progress.screen_claimed and !value.useAlternateScreen and value.clearOnShutdown and value.renderOffset == 0) { try writer.writeByte('\r'); progress.rows_remaining = candidate.state.cursor.row; progress.step = .restore_rows; } }, .restore_rows => { if (progress.rows_remaining != 0) { const count = @min(progress.rows_remaining, control_packet_bytes_max / ansi.ANSI.reverseIndex.len); try writer.splatBytesAll(ansi.ANSI.reverseIndex, count); progress.rows_remaining -= count; } else { try writer.writeAll(ansi.ANSI.eraseBelowCursor); progress.step = .reset_output; } }, .reset_output => { try candidate.resetOutputModes(writer); if (progress.screen_claimed and !value.useAlternateScreen and value.clearOnShutdown) { if (value.renderOffset == 0) { try writer.writeAll("\x1b[H\x1b[J"); } else { try writer.writeAll("\x1b[r"); try ansi.ANSI.moveToOutput(writer, 1, value.renderOffset + 1); try writer.writeAll(ansi.ANSI.eraseBelowCursor); try ansi.ANSI.moveToOutput(writer, 1, value.renderOffset + 1); } } try writer.writeAll(ansi.ANSI.resetCursorColorFallback ++ ansi.ANSI.resetCursorColor ++ ansi.ANSI.defaultCursorStyle ++ ansi.ANSI.showCursor); progress.step = .settle_first; }, .show_cursor => { try writer.writeAll(ansi.ANSI.showCursor); progress.step = .settle_second; }, .idle, .activate, .settle_first, .settle_second => unreachable, } } /// Copies only the next span's unacknowledged prefix into host-owned storage. /// Only out[0..ticket.len] is written. Empty reads consume no bytes or IDs. /// One copy may await completion; the whole span stays charged until completed. pub fn readOutput(self: *Session, out: []u8) Error!?OutputTicket { if (!try self.checkOutput()) return null; if (out.len == 0) return null; if (self.pending != null) return error.Busy; if (self.span == null and !self.output.hasPendingSpans()) return null; const request_id = std.math.add(u64, self.last_request_id, 1) catch return error.RequestLimit; const bytes = self.nextOutput().?; const len: u32 = @intCast(@min(out.len, bytes.len)); @memcpy(out[0..len], bytes[0..len]); const ticket: OutputTicket = .{ .session = self.handle, .request_id = request_id, .len = len }; self.pending = ticket; self.last_request_id = request_id; return ticket; } /// Borrows the next span for one writer.write call, capped by max_bytes. /// The writer returns a delivered prefix length; zero or WouldBlock retains /// the suffix for retry. Other errors permanently stop output without replay. /// The writer must not retain the slice or acknowledge buffered-but-unwritten bytes. pub fn drainOutput(self: *Session, writer: anytype, max_bytes: u32) Error!u32 { if (max_bytes == 0) return error.InvalidBudget; if (!try self.checkOutput()) return 0; if (self.pending != null) return error.Busy; const bytes = self.nextOutput() orelse return 0; const offered = bytes[0..@min(bytes.len, max_bytes)]; const count = try self.deliverOutput(writer, offered); if (count != 0) self.completeOutputBytes(count); return count; } fn deliverOutput(self: *Session, writer: anytype, offered: []const u8) Error!u32 { const count = writer.write(offered) catch |err| switch (@as(anyerror, err)) { error.WouldBlock => return 0, else => { self.failOutput(); return error.SessionFailed; }, }; if (count > offered.len) { self.failOutput(); return error.SessionFailed; } return @intCast(count); } pub fn drainStdout(self: *Session, io: std.Io, max_bytes: u32) Error!u32 { if (max_bytes < 4) return error.InvalidBudget; if (!try self.checkOutput()) return 0; if (self.pending != null) return error.Busy; var stdout = renderer.StdoutOutput.initWithIo(io); if (!stdout.supportsDirectWrite()) return error.UnsupportedResource; const Writer = struct { output: *renderer.StdoutOutput, pub fn write(writer: @This(), bytes: []const u8) !usize { return writer.output.writeSome(bytes); } }; const writer: Writer = .{ .output = &stdout }; if (builtin.os.tag != .windows or !stdout.windowsConsole) { return self.drainOutput(writer, max_bytes); } return self.drainConsoleOutput(writer, max_bytes); } fn drainConsoleOutput(self: *Session, writer: anytype, max_bytes: u32) Error!u32 { std.debug.assert(max_bytes >= 4); if (!try self.checkOutput()) return 0; if (self.pending != null) return error.Busy; const bytes = self.nextOutput() orelse return 0; const sequence_len = std.unicode.utf8ByteSequenceLength(bytes[0]) catch 1; if (bytes.len >= sequence_len) return self.drainOutput(writer, max_bytes); // A UTF-8 scalar can straddle up to four one-byte queue chunks. Keep its // bytes charged until WriteConsoleW succeeds; no decoder owns a hidden tail. var scalar: [4]u8 = undefined; @memcpy(scalar[0..bytes.len], bytes); const copied = self.output.copyQueuedPrefix(scalar[bytes.len..sequence_len]); // Bytes that cannot continue the scalar belong to later output; never join them. for (scalar[1 .. bytes.len + copied]) |byte| { if (byte & 0xc0 != 0x80) return error.IncompatibleOutput; } if (copied != sequence_len - bytes.len) { self.checkWriting() catch return error.IncompatibleOutput; if (!self.output.hasAtomicCapacity()) return error.IncompatibleOutput; return 0; } const written = try self.deliverOutput(writer, scalar[0..sequence_len]); var remaining = written; while (remaining != 0) { const count: u32 = @intCast(@min(remaining, self.nextOutput().?.len)); self.completeOutputBytes(count); remaining -= count; } return written; } fn checkOutput(self: *const Session) Error!bool { switch (self.state) { .open, .closing => return true, .closed => return false, .failed => return error.SessionFailed, .cancelled => return error.SessionCancelled, } } fn nextOutput(self: *Session) ?[]const u8 { std.debug.assert(self.pending == null); // A fully completed span is released at once, so a held span has bytes left. std.debug.assert(self.span == null or self.span_offset < self.span.?.len); if (self.span == null and !self.output.hasPendingSpans()) return null; if (self.span == null) { var spans: [1]feed.SpanInfo = undefined; const count = self.output.drainSpans(&spans); std.debug.assert(count == 1 and self.span_offset == 0); self.span = spans[0]; } return self.span.?.slice()[self.span_offset..]; } /// An invalid ticket changes nothing. A valid failed result consumes the /// request, not the bytes, and permanently stops transport without replay. pub fn completeOutput(self: *Session, ticket: OutputTicket, result: OutputResult) Error!void { if (ticket.session.context_id != self.handle.context_id) return error.WrongContext; if (ticket.session.slot != self.handle.slot) return error.WrongSession; if (ticket.session.generation != self.handle.generation) return error.StaleHandle; if (self.pending_post) return error.StaleRequest; const pending = self.pending orelse return error.StaleRequest; if (ticket.request_id != pending.request_id) return error.StaleRequest; if (ticket.len != pending.len) return error.InvalidTicket; std.debug.assert(self.state == .open or self.state == .closing); self.pending = null; if (result == .failed) { self.failOutput(); return; } self.completeOutputBytes(ticket.len); } fn failOutput(self: *Session) void { self.cancelSceneFrame(); self.state = .failed; self.lifecycle.phase = .failed; self.lifecycle.step = .idle; self.lifecycle.deadline_ns = null; self.finishPresentation(.failed); } fn completeOutputBytes(self: *Session, count: u32) void { std.debug.assert(self.pending == null); const span = self.span.?; std.debug.assert(count > 0 and count <= span.len - self.span_offset); const published_bytes = self.output.getStats().bytes_written; std.debug.assert(self.completed_bytes <= published_bytes); std.debug.assert(count <= published_bytes - self.completed_bytes); self.completed_bytes += count; self.span_offset += count; if (self.span_offset == span.len) { self.output.releaseSpan(span.slot_index, span.release_id) catch unreachable; self.span = null; self.span_offset = 0; } if (self.frame_end_offset) |end_offset| { if (self.completed_bytes >= end_offset) self.finishPresentation(.presented); } if (self.state == .closing and self.output.closed and self.isDrained()) self.state = .closed; } /// Rejects further writes without waiting for the host to complete output. pub fn beginClose(self: *Session) Error!void { switch (self.state) { .open => {}, .closing, .closed => return, .failed => return error.SessionFailed, .cancelled => return error.SessionCancelled, } defer self.lifecycle.assertValid(self.state); self.cancelSceneFrame(); switch (self.lifecycle.phase) { .uninitialized, .suspended => { try self.output.close(); self.state = if (self.isDrained()) .closed else .closing; if (self.lifecycle.phase == .suspended) self.lifecycle.phase = .restored; }, .active, .setting_up, .resuming, .suspending => { if (self.lifecycle.phase != .suspending) { self.lifecycle.step = .delete_images; self.lifecycle.image_index = 0; } self.lifecycle.phase = .closing; self.state = .closing; }, .restored, .closing, .failed, .cancelled => unreachable, } } /// Writes stdout from a native thread (`W` is `stdout_writer.Writer(Sink, Runner)`). /// Collects a finished copy, then, unless `wait` or `max_bytes == 0`, hands over the next /// one. `wait` (process exit) never starts a copy: it waits for the running one, and a copy /// the thread never picked up is taken back unwritten for the synchronous drain. /// `create` makes the writer on the first hand-over, or fails with UnsupportedResource /// before any output is consumed. pub fn postStdout(self: *Session, comptime W: type, create: anytype, max_bytes: u32, wait: bool) Error!PostResult { if (!try self.checkOutput()) return .{}; var result: PostResult = .{}; if (self.pending_post) { const writer: *W = @ptrCast(@alignCast(self.stdout_post.?.ptr)); switch (if (wait) writer.waitCollect(reclaim_grace_ns) else writer.collect()) { .busy => return .{ .in_flight = true }, .written => { const ticket = self.pending.?; self.pending_post = false; try self.completeOutput(ticket, .written); result.written = ticket.len; }, .failed => { self.pending_post = false; try self.completeOutput(self.pending.?, .failed); return error.SessionFailed; }, .reclaimed => { self.pending = null; self.pending_post = false; self.stdout_post = null; writer.release(); return .{}; }, } } else if (self.pending != null) return error.Busy; if (wait or max_bytes == 0) return result; if (self.span == null and !self.output.hasPendingSpans()) return result; const writer: *W = if (self.stdout_post) |held| @ptrCast(@alignCast(held.ptr)) else blk: { const created: *W = try create.create(); self.stdout_post = created.handle(); break :blk created; }; const ticket = (try self.readOutput(writer.buffer[0..@min(max_bytes, writer.buffer.len)])).?; self.pending_post = true; writer.start(ticket.len); result.in_flight = true; return result; } /// How long process exit waits for the thread to pick up a posted copy before taking it back. const reclaim_grace_ns = 100 * std.time.ns_per_ms; fn abandonStdout(self: *Session) void { const held = self.stdout_post orelse return; self.stdout_post = null; self.pending_post = false; held.abandon(held.ptr); } /// A close past its deadline: begins close, then discards the output queued before it, except the copy that /// the host holds, so only that copy and the restoration remain. pub fn dropOutput(self: *Session) Error!void { try self.beginClose(); // Restoration packets enter only a drained queue. Once the first is queued, the queue holds nothing else. const step = self.lifecycle.step; if (step != .idle and (step != .delete_images or self.lifecycle.image_index != 0)) return; self.finishPresentation(.failed); const kept: u32 = if (self.pending) |ticket| ticket.len else 0; if (self.releaseQueued(kept)) { // Dropped packets may have changed the terminal model without reaching the terminal: take the screen // and Kitty keyboard back to what the terminal has, and reset the other input modes. self.lifecycle.dropped = true; if (self.renderer) |value| { const state = &value.terminal.state; if (self.completed_bytes + kept < self.wire.end) { state.alt_screen = self.wire.alt_screen; state.kitty_keyboard = self.wire.kitty_keyboard; value.useAlternateScreen = self.wire.use_alternate; } state.modify_other_keys = true; state.bracketed_paste = true; state.focus_tracking = true; state.unicode = true; } } if (self.output.closed and self.isDrained()) self.state = .closed; } /// Releases every queued span. The held span keeps `kept` bytes from its offset for a copy in flight. /// Returns whether any bytes were released. fn releaseQueued(self: *Session, kept: u32) bool { var released = false; if (self.span) |*span| { released = span.len > self.span_offset + kept; if (kept == 0) { self.output.releaseSpan(span.slot_index, span.release_id) catch unreachable; self.span = null; self.span_offset = 0; } else span.len = self.span_offset + kept; } var spans: [1]feed.SpanInfo = undefined; while (self.output.drainSpans(&spans) != 0) { self.output.releaseSpan(spans[0].slot_index, spans[0].release_id) catch unreachable; released = true; } return released; } /// Explicitly discards disconnected output. Copies belong to the host, so /// cancellation leaves no native borrow and never retries accepted bytes. pub fn cancel(self: *Session) void { self.abandonStdout(); self.cancelSceneFrame(); self.finishPresentation(.failed); _ = self.releaseQueued(0); self.output.close() catch unreachable; self.pending = null; self.state = .cancelled; self.lifecycle.phase = .cancelled; self.lifecycle.step = .idle; self.lifecycle.deadline_ns = null; std.debug.assert(self.isDrained()); } pub fn canDestroy(self: *Session) bool { if (self.frame_lease_count != 0) return false; if (!self.isDrained()) return false; return switch (self.lifecycle.phase) { .uninitialized, .suspended, .restored, .cancelled => true, else => false, }; } pub fn isDrained(self: *Session) bool { return self.frame_end_offset == null and self.output.getStats().outstanding_spans == 0; } pub fn getStats(self: *Session) feed.Stats { return self.output.getStats(); } fn finishPresentation(self: *Session, outcome: renderer.PresentationOutcome) void { if (self.frame_end_offset == null) return; self.renderer.?.completePresentation(outcome) catch unreachable; self.frame_end_offset = null; } }; fn applyCapabilityResponses(candidate: *terminal.Terminal, response: []const u8) Error!void { if (response.len == 0 or response.len > capability_response_bytes_max) return error.InvalidOptions; var offset: usize = 0; while (offset < response.len) { const bytes = response[offset..]; if (bytes.len < 3 or bytes[0] != '\x1b') return error.InvalidOptions; var end: usize = 2; switch (bytes[1]) { '[' => { while (end < bytes.len and bytes[end] >= 0x30 and bytes[end] <= 0x3f) : (end += 1) {} while (end < bytes.len and bytes[end] >= 0x20 and bytes[end] <= 0x2f) : (end += 1) {} if (end == bytes.len) return error.InvalidOptions; end += 1; try validateCapabilityCsi(bytes[2..end]); }, 'P', ']', '_' => { // These reply payloads are printable ASCII. Only OSC accepts BEL; // all other string replies require ST, without nested escapes. while (end < bytes.len and bytes[end] >= 0x20 and bytes[end] <= 0x7e) : (end += 1) {} const payload = bytes[2..end]; if (bytes[1] == ']' and end < bytes.len and bytes[end] == '\x07') { end += 1; } else if (std.mem.startsWith(u8, bytes[end..], "\x1b\\")) { end += 2; } else return error.InvalidOptions; try validateCapabilityString(bytes[1], payload); }, else => return error.InvalidOptions, } // The legacy parser searches within one reply; batching must retain wire order. candidate.processCapabilityResponse(bytes[0..end]); offset += end; } } fn validateCapabilityString(kind: u8, payload: []const u8) Error!void { switch (kind) { 'P' => { if (std.mem.startsWith(u8, payload, ">|")) { if (payload.len == 2) return error.InvalidOptions; return; } if (std.mem.eql(u8, payload, "0+r")) return; if (!std.mem.startsWith(u8, payload, "0+r") and !std.mem.startsWith(u8, payload, "1+r")) { return error.InvalidOptions; } var fields = std.mem.splitScalar(u8, payload[3..], '='); var count: u8 = 0; while (fields.next()) |field| { if (count == 2 or field.len % 2 != 0 or (count == 0 and field.len == 0)) { return error.InvalidOptions; } for (field) |byte| { if (!std.ascii.isHex(byte)) return error.InvalidOptions; } count += 1; } }, ']' => { if (!std.mem.startsWith(u8, payload, "99;") and !std.mem.startsWith(u8, payload, "1337;Capabilities=") and !std.mem.startsWith(u8, payload, "7501;")) return error.InvalidOptions; }, '_' => { if (!std.mem.startsWith(u8, payload, "G")) return error.InvalidOptions; const separator = std.mem.findScalar(u8, payload, ';') orelse return error.InvalidOptions; if (separator == 1 or separator + 1 == payload.len) return error.InvalidOptions; var fields = std.mem.splitScalar(u8, payload[1..separator], ','); while (fields.next()) |field| { if (field.len < 3 or !std.ascii.isAlphabetic(field[0]) or field[1] != '=') { return error.InvalidOptions; } for (field[2..]) |byte| { if (!std.ascii.isDigit(byte)) return error.InvalidOptions; } _ = std.fmt.parseInt(u32, field[2..], 10) catch return error.InvalidOptions; } }, else => unreachable, } } fn validateCapabilityCsi(payload: []const u8) Error!void { const final = payload[payload.len - 1]; var parameters = payload[0 .. payload.len - 1]; switch (final) { 'y', 'u', 'c' => { if (!std.mem.startsWith(u8, parameters, "?")) return error.InvalidOptions; parameters = parameters[1..]; }, 'R' => {}, else => return error.InvalidOptions, } if (final == 'y') { if (!std.mem.endsWith(u8, parameters, "$")) return error.InvalidOptions; parameters = parameters[0 .. parameters.len - 1]; } var values: [2]u16 = .{ 0, 0 }; var count: usize = 0; var parts = std.mem.splitScalar(u8, parameters, ';'); while (parts.next()) |part| { for (part) |byte| { if (!std.ascii.isDigit(byte)) return error.InvalidOptions; } const value = if (part.len == 0 and final == 'c') 0 else std.fmt.parseInt(u16, part, 10) catch return error.InvalidOptions; if (count < values.len) values[count] = value; count += 1; } switch (final) { 'y' => { if (count != 2 or values[1] > 4) return error.InvalidOptions; switch (values[0]) { 1004, 1016, 2004, 2026, 2027, 2031 => {}, else => return error.InvalidOptions, } }, 'u' => if (count != 1 or values[0] > 31) return error.InvalidOptions, 'R' => if (count != 2 or values[0] == 0 or values[1] == 0) return error.InvalidOptions, 'c' => {}, else => unreachable, } }