@h-rig/cli 0.0.6-alpha.84 → 0.0.6-alpha.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -158,19 +158,6 @@ function panelCellRect(layout, panel) {
158
158
  const dividerY = headerHeight ? Math.min(bottom - 1, top + headerHeight) : top;
159
159
  return { left, top, width, height, right, bottom, headerHeight, dividerY };
160
160
  }
161
- function panelPixelPlacement(layout, panel, size, minPixels = 8) {
162
- const cellW = size.width / layout.width;
163
- const cellH = size.height / layout.height;
164
- const leftCells = layout.centerLeft + (panel.left ?? 0);
165
- const topCells = layout.centerTop + panel.top;
166
- const widthCells = panel.width ?? layout.centerWidth;
167
- const heightCells = panel.height;
168
- const left = Math.round(leftCells * cellW);
169
- const top = Math.round(topCells * cellH);
170
- const width = Math.round(widthCells * cellW);
171
- const height = Math.round(heightCells * cellH);
172
- return width > minPixels && height > minPixels ? { left, top, width, height, leftCells, topCells, widthCells, heightCells } : null;
173
- }
174
161
 
175
162
  // packages/cli/src/app-opentui/render/constants.ts
176
163
  var LCG_MULTIPLIER = 1664525;
@@ -203,7 +190,6 @@ var RAIL_YS_LOOP = [0.18, 0.5, 0.82];
203
190
  var RAIL_YS_CARRIER = [0.24, 0.54, 0.82];
204
191
  var RAIL_YS_DISPATCH = [0.18, 0.58, 0.82];
205
192
  var GLOW_FALLOFF_EXP_ASCII = 2.2;
206
- var GLOW_FALLOFF_EXP_IMAGE = 2.4;
207
193
 
208
194
  // packages/cli/src/app-opentui/render/graphics.ts
209
195
  var BRAILLE_SAMPLES_X = 2;
@@ -741,971 +727,6 @@ function drawAmbientField(layer, layout, _tick, scene = "fleet", load = 0, activ
741
727
  layer.__rigAmbientKey = key;
742
728
  }
743
729
 
744
- // packages/cli/src/app-opentui/render/image-visual-layer.ts
745
- import { Worker } from "worker_threads";
746
- import { deflateSync } from "zlib";
747
- import { allocateImageId, deleteKittyImage } from "@earendil-works/pi-tui";
748
-
749
- // packages/cli/src/app-opentui/terminal-capabilities.ts
750
- import { getCapabilities } from "@earendil-works/pi-tui";
751
- function getRigTerminalCapabilities() {
752
- const imageProtocol = getCapabilities().images;
753
- const supportsKittyImages = imageProtocol === "kitty";
754
- return {
755
- imageProtocol,
756
- supportsKittyImages,
757
- visualMode: supportsKittyImages ? "kitty-images" : "framebuffer-fallback"
758
- };
759
- }
760
-
761
- // packages/cli/src/app-opentui/render/image-visual-layer.ts
762
- var PANEL_MASK_RADIUS_MIN = 14;
763
- var PANEL_MASK_RADIUS_MAX = 34;
764
- var PANEL_MASK_RADIUS_FACTOR = 0.035;
765
- var PANEL_BLUR_RADIUS_MIN = 8;
766
- var PANEL_BLUR_RADIUS_MAX = 28;
767
- var PANEL_BLUR_RADIUS_FACTOR = 0.018;
768
- var BG = [7, 8, 9, 255];
769
- var PANEL = [16, 17, 21, 184];
770
- var PANEL_HEADER = [16, 17, 21, 190];
771
- var PANEL_LINE2 = [255, 255, 255, 24];
772
- var LIME = [204, 255, 77, 255];
773
- var LIME_DIM = [169, 214, 63, 255];
774
- var CYAN = [86, 216, 255, 255];
775
- var MAGENTA = [255, 121, 176, 255];
776
- var INK_DIM = [108, 110, 121, 255];
777
- var PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
778
- var CRC_TABLE = makeCrcTable();
779
- var MAX_IMAGE_BYTES = 48 * 1024 * 1024;
780
- var KITTY_CHUNK_SIZE = 4096;
781
- var PANEL_BLUR_SCALE = 1;
782
- var PANEL_MASK_CACHE_LIMIT = 16;
783
- var ZLIB_LEVEL = 1;
784
- var DEFAULT_IMAGE_RESOLUTION_SCALE = 1;
785
- var LOAD_BUCKETS = 5;
786
- function loadBucket(load) {
787
- if (!Number.isFinite(load ?? NaN))
788
- return 0;
789
- return Math.max(0, Math.min(LOAD_BUCKETS, Math.round((load ?? 0) * LOAD_BUCKETS)));
790
- }
791
- var panelMaskCache = new Map;
792
- var BG_WORD = rgbaWord(BG);
793
- function imageTransport() {
794
- const forced = process.env.RIG_OPENTUI_IMAGE_TRANSPORT;
795
- if (forced === "rgba-zlib")
796
- return "rgba-zlib";
797
- return "png";
798
- }
799
- function imageResolutionScale() {
800
- const raw = Number.parseFloat(process.env.RIG_OPENTUI_IMAGE_SCALE ?? "");
801
- if (Number.isFinite(raw) && raw > 0)
802
- return Math.max(0.25, Math.min(1, raw));
803
- return DEFAULT_IMAGE_RESOLUTION_SCALE;
804
- }
805
- function rgbaWord(color) {
806
- return (color[3] << 24 | color[2] << 16 | color[1] << 8 | color[0]) >>> 0;
807
- }
808
- function fillRgba(data, color, word = rgbaWord(color)) {
809
- if (data.byteOffset % 4 === 0 && data.byteLength % 4 === 0) {
810
- new Uint32Array(data.buffer, data.byteOffset, data.byteLength / 4).fill(word);
811
- return;
812
- }
813
- for (let i = 0;i < data.length; i += 4) {
814
- data[i] = color[0];
815
- data[i + 1] = color[1];
816
- data[i + 2] = color[2];
817
- data[i + 3] = color[3];
818
- }
819
- }
820
- var ASCII_GLYPHS = {
821
- ".": ["00000", "00000", "00000", "00000", "00000", "00100", "00100"],
822
- "'": ["00100", "00100", "00000", "00000", "00000", "00000", "00000"],
823
- "-": ["00000", "00000", "00000", "11111", "00000", "00000", "00000"],
824
- _: ["00000", "00000", "00000", "00000", "00000", "00000", "11111"],
825
- "=": ["00000", "11111", "00000", "00000", "11111", "00000", "00000"],
826
- "|": ["00100", "00100", "00100", "00100", "00100", "00100", "00100"],
827
- "/": ["00001", "00010", "00010", "00100", "01000", "01000", "10000"],
828
- "\\": ["10000", "01000", "01000", "00100", "00010", "00010", "00001"],
829
- "(": ["00010", "00100", "01000", "01000", "01000", "00100", "00010"],
830
- ")": ["01000", "00100", "00010", "00010", "00010", "00100", "01000"],
831
- "!": ["00100", "00100", "00100", "00100", "00100", "00000", "00100"],
832
- "%": ["11001", "11010", "00100", "01000", "10110", "00110", "00000"],
833
- $: ["00100", "11110", "10100", "11110", "00101", "11110", "00100"],
834
- "@": ["01110", "10001", "10111", "10101", "10111", "10000", "01111"],
835
- o: ["00000", "01110", "10001", "10001", "10001", "01110", "00000"],
836
- "*": ["00100", "10101", "01110", "11111", "01110", "10101", "00100"]
837
- };
838
- function sceneStaticTick(scene) {
839
- let hash = 0;
840
- for (let index = 0;index < scene.length; index += 1)
841
- hash = hash * 33 + scene.charCodeAt(index) >>> 0;
842
- return 11 + hash % 97;
843
- }
844
- function charColor(char, row, totalRows) {
845
- if (char === "@" || char === "$" || char === "o")
846
- return LIME;
847
- if (char === "%" || char === "!" || char === "/" || char === "\\" || char === "|")
848
- return CYAN;
849
- if (char === "." || char === "'" || char === "_" || row < 3 || row > totalRows - 4)
850
- return INK_DIM;
851
- if (char === "-" || char === "=" || char === "(" || char === ")")
852
- return LIME_DIM;
853
- return MAGENTA;
854
- }
855
- function fillRectAlpha(data, width, height, left, top, rectWidth, rectHeight, color, alpha) {
856
- const x0 = Math.max(0, Math.floor(left));
857
- const y0 = Math.max(0, Math.floor(top));
858
- const x1 = Math.min(width, Math.ceil(left + rectWidth));
859
- const y1 = Math.min(height, Math.ceil(top + rectHeight));
860
- for (let y = y0;y < y1; y += 1) {
861
- for (let x = x0;x < x1; x += 1)
862
- blendOver(data, (y * width + x) * 4, color, alpha);
863
- }
864
- }
865
- function drawAsciiGlyph(data, width, height, x, y, cellWidth, cellHeight, char, color, alpha) {
866
- const pattern = ASCII_GLYPHS[char] ?? ASCII_GLYPHS["*"];
867
- const glyphWidth = Math.max(1, cellWidth * 0.56);
868
- const glyphHeight = Math.max(1, cellHeight * 0.7);
869
- const originX = x + (cellWidth - glyphWidth) * 0.5;
870
- const originY = y + (cellHeight - glyphHeight) * 0.5;
871
- const pixelWidth = Math.max(1, glyphWidth / pattern[0].length);
872
- const pixelHeight = Math.max(1, glyphHeight / pattern.length);
873
- for (let row = 0;row < pattern.length; row += 1) {
874
- const bits = pattern[row];
875
- for (let col = 0;col < bits.length; col += 1) {
876
- if (bits[col] !== "1")
877
- continue;
878
- fillRectAlpha(data, width, height, originX + col * pixelWidth, originY + row * pixelHeight, pixelWidth * 0.72, pixelHeight * 0.72, color, alpha);
879
- }
880
- }
881
- }
882
- function drawStaticAsciiFleetBackground(data, width, height, scene, layout, load, activeRuns) {
883
- const rows = fleetRows(sceneStaticTick(scene), { animate: true });
884
- const cellWidth = width / Math.max(1, layout.width);
885
- const cellHeight = height / Math.max(1, layout.height);
886
- const sideBySide = layout.width >= FLEET_GRID_WIDTH * 1.9;
887
- const leftCells = sideBySide ? Math.max(1, Math.floor(layout.width * 0.3 - FLEET_GRID_WIDTH / 2)) : Math.floor((layout.width - FLEET_GRID_WIDTH) / 2);
888
- const topCells = Math.floor((layout.height - FLEET_GRID_HEIGHT) / 2);
889
- const fleetLeft = leftCells * cellWidth;
890
- const fleetTop = topCells * cellHeight;
891
- drawGlow2(data, width, height, width * 0.5, height * 0.5, Math.min(width, height) * 0.4, LIME, 0.022 + load * 0.03);
892
- drawGlow2(data, width, height, width * 0.18, height * 0.22, Math.min(width, height) * 0.28, CYAN, 0.018 + load * 0.012);
893
- drawGlow2(data, width, height, width * 0.82, height * 0.78, Math.min(width, height) * 0.22, MAGENTA, 0.012 + load * 0.008);
894
- let droneTotal = 0;
895
- for (const line of rows)
896
- for (const char of line)
897
- if (char === "@" || char === "$" || char === "%")
898
- droneTotal += 1;
899
- const litTarget = Math.max(0, Math.min(droneTotal, activeRuns));
900
- let droneIndex = 0;
901
- for (let row = 0;row < rows.length; row += 1) {
902
- const line = rows[row];
903
- for (let col = 0;col < line.length; col += 1) {
904
- const char = line[col];
905
- if (char === " ")
906
- continue;
907
- const x = fleetLeft + col * cellWidth;
908
- const y = fleetTop + row * cellHeight;
909
- const color = charColor(char, row, rows.length);
910
- const isDrone = char === "@" || char === "$" || char === "%";
911
- const lit = isDrone && droneIndex < litTarget;
912
- drawAsciiGlyph(data, width, height, x + cellWidth * 0.07, y + cellHeight * 0.05, cellWidth, cellHeight, char, color, lit ? 0.72 : 0.46);
913
- if (isDrone) {
914
- droneIndex += 1;
915
- drawGlow2(data, width, height, x + cellWidth * 0.5, y + cellHeight * 0.5, Math.max(cellWidth, cellHeight) * 0.95, color, lit ? 0.044 : 0.014);
916
- }
917
- }
918
- }
919
- }
920
- function applyStaticAtmosphere(data, width, height, load) {
921
- const cx = width * 0.5;
922
- const cy = height * 0.42;
923
- const radius = Math.max(width, height) * 0.78;
924
- const minVignette = 0.1 - load * 0.02;
925
- for (let y = 0;y < height; y += 1) {
926
- for (let x = 0;x < width; x += 1) {
927
- const distance = Math.hypot(x - cx, y - cy) / radius;
928
- const alpha = Math.max(minVignette, Math.min(0.82, 0.12 + Math.pow(distance, 1.65) * 0.62));
929
- blendOver(data, (y * width + x) * 4, BG, alpha);
930
- }
931
- }
932
- drawGlow2(data, width, height, width * 0.82, height * 0.04, Math.min(width, height) * 0.2, LIME, 0.024 + load * 0.012);
933
- drawGlow2(data, width, height, width * 0.12, height * 0.18, Math.min(width, height) * 0.16, CYAN, 0.018 + load * 0.008);
934
- }
935
- function makeCrcTable() {
936
- const table = new Uint32Array(256);
937
- for (let n = 0;n < 256; n += 1) {
938
- let c = n;
939
- for (let k = 0;k < 8; k += 1)
940
- c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
941
- table[n] = c >>> 0;
942
- }
943
- return table;
944
- }
945
- function crc32(bytes) {
946
- let c = 4294967295;
947
- for (let i = 0;i < bytes.length; i += 1)
948
- c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ c >>> 8;
949
- return (c ^ 4294967295) >>> 0;
950
- }
951
- function chunk(type, data) {
952
- const out = new Uint8Array(12 + data.length);
953
- const view = new DataView(out.buffer);
954
- view.setUint32(0, data.length);
955
- out[4] = type.charCodeAt(0);
956
- out[5] = type.charCodeAt(1);
957
- out[6] = type.charCodeAt(2);
958
- out[7] = type.charCodeAt(3);
959
- out.set(data, 8);
960
- view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
961
- return out;
962
- }
963
- function encodePng(width, height, rgba) {
964
- const ihdr = new Uint8Array(13);
965
- const ihdrView = new DataView(ihdr.buffer);
966
- ihdrView.setUint32(0, width);
967
- ihdrView.setUint32(4, height);
968
- ihdr[8] = 8;
969
- ihdr[9] = 6;
970
- ihdr[10] = 0;
971
- ihdr[11] = 0;
972
- ihdr[12] = 0;
973
- const stride = width * 4;
974
- const raw = new Uint8Array((stride + 1) * height);
975
- for (let y = 0;y < height; y += 1) {
976
- const rawOffset = y * (stride + 1);
977
- raw[rawOffset] = 0;
978
- raw.set(rgba.subarray(y * stride, y * stride + stride), rawOffset + 1);
979
- }
980
- const compressed = deflateSync(raw, { level: ZLIB_LEVEL });
981
- return Buffer.concat([
982
- Buffer.from(PNG_SIGNATURE),
983
- Buffer.from(chunk("IHDR", ihdr)),
984
- Buffer.from(chunk("IDAT", compressed)),
985
- Buffer.from(chunk("IEND", new Uint8Array(0)))
986
- ]);
987
- }
988
- function kittyImageSequence(base64, options) {
989
- const params = [`a=T`, `f=${options.format}`, `q=2`, `C=1`, `c=${options.columns}`, `r=${options.rows}`, `i=${options.imageId}`, `z=${options.zIndex}`];
990
- if (options.format === 32) {
991
- params.push(`s=${options.pixelWidth ?? 1}`, `v=${options.pixelHeight ?? 1}`);
992
- if (options.compressed)
993
- params.push("o=z");
994
- }
995
- if (base64.length <= KITTY_CHUNK_SIZE)
996
- return `\x1B_G${params.join(",")};${base64}\x1B\\`;
997
- const chunks = [];
998
- for (let offset = 0;offset < base64.length; offset += KITTY_CHUNK_SIZE) {
999
- const part = base64.slice(offset, offset + KITTY_CHUNK_SIZE);
1000
- const last = offset + KITTY_CHUNK_SIZE >= base64.length;
1001
- chunks.push(`\x1B_G${offset === 0 ? `${params.join(",")},` : ""}m=${last ? 0 : 1};${part}\x1B\\`);
1002
- }
1003
- return chunks.join("");
1004
- }
1005
- function clampByte(value) {
1006
- return Math.max(0, Math.min(255, Math.round(value)));
1007
- }
1008
- function blendOver(data, index, color, alphaScale = 1) {
1009
- const alpha = color[3] / 255 * alphaScale;
1010
- const inv = 1 - alpha;
1011
- data[index] = clampByte(color[0] * alpha + data[index] * inv);
1012
- data[index + 1] = clampByte(color[1] * alpha + data[index + 1] * inv);
1013
- data[index + 2] = clampByte(color[2] * alpha + data[index + 2] * inv);
1014
- data[index + 3] = 255;
1015
- }
1016
- function drawDisc(data, width, height, cx, cy, radius, color, alpha = 1) {
1017
- const minX = Math.max(0, Math.floor(cx - radius));
1018
- const maxX = Math.min(width - 1, Math.ceil(cx + radius));
1019
- const minY = Math.max(0, Math.floor(cy - radius));
1020
- const maxY = Math.min(height - 1, Math.ceil(cy + radius));
1021
- for (let y = minY;y <= maxY; y += 1) {
1022
- for (let x = minX;x <= maxX; x += 1) {
1023
- const dx = x + 0.5 - cx;
1024
- const dy = y + 0.5 - cy;
1025
- const d = Math.sqrt(dx * dx + dy * dy);
1026
- if (d > radius)
1027
- continue;
1028
- const edge = Math.max(0, Math.min(1, radius - d));
1029
- blendOver(data, (y * width + x) * 4, color, alpha * Math.min(1, 0.35 + edge));
1030
- }
1031
- }
1032
- }
1033
- function drawGlow2(data, width, height, cx, cy, radius, color, alpha = 0.18) {
1034
- const minX = Math.max(0, Math.floor(cx - radius));
1035
- const maxX = Math.min(width - 1, Math.ceil(cx + radius));
1036
- const minY = Math.max(0, Math.floor(cy - radius));
1037
- const maxY = Math.min(height - 1, Math.ceil(cy + radius));
1038
- for (let y = minY;y <= maxY; y += 1) {
1039
- for (let x = minX;x <= maxX; x += 1) {
1040
- const dx = x + 0.5 - cx;
1041
- const dy = y + 0.5 - cy;
1042
- const d = Math.sqrt(dx * dx + dy * dy);
1043
- if (d > radius)
1044
- continue;
1045
- const falloff = Math.pow(1 - d / Math.max(1, radius), GLOW_FALLOFF_EXP_IMAGE);
1046
- blendOver(data, (y * width + x) * 4, color, alpha * falloff);
1047
- }
1048
- }
1049
- }
1050
- function drawLine2(data, width, height, x0, y0, x1, y1, color, alpha = 0.5, thickness = 1.4) {
1051
- const dx = x1 - x0;
1052
- const dy = y1 - y0;
1053
- const steps = Math.max(1, Math.ceil(Math.hypot(dx, dy) * 1.2));
1054
- for (let i = 0;i <= steps; i += 1) {
1055
- const t2 = i / steps;
1056
- drawDisc(data, width, height, x0 + dx * t2, y0 + dy * t2, thickness, color, alpha);
1057
- }
1058
- }
1059
- function roundRectAlpha(px, py, x, y, w, h, r) {
1060
- const rx = Math.max(x + r, Math.min(px, x + w - r));
1061
- const ry = Math.max(y + r, Math.min(py, y + h - r));
1062
- const dx = px - rx;
1063
- const dy = py - ry;
1064
- const dist = Math.sqrt(dx * dx + dy * dy);
1065
- return Math.max(0, Math.min(1, r + 0.75 - dist));
1066
- }
1067
- function panelRect(layout, panel, size) {
1068
- return panelPixelPlacement(layout, panel, size);
1069
- }
1070
- function downsampleRegion(data, canvasW, canvasH, rect, scale) {
1071
- const w = Math.max(1, Math.ceil(rect.width / scale));
1072
- const h = Math.max(1, Math.ceil(rect.height / scale));
1073
- const out = new Uint8ClampedArray(w * h * 3);
1074
- for (let y = 0;y < h; y += 1) {
1075
- for (let x = 0;x < w; x += 1) {
1076
- let r = 0, g = 0, b = 0, count = 0;
1077
- const sx0 = rect.left + x * scale;
1078
- const sy0 = rect.top + y * scale;
1079
- for (let yy = 0;yy < scale; yy += 1) {
1080
- const sy = sy0 + yy;
1081
- if (sy < 0 || sy >= canvasH)
1082
- continue;
1083
- for (let xx = 0;xx < scale; xx += 1) {
1084
- const sx = sx0 + xx;
1085
- if (sx < 0 || sx >= canvasW)
1086
- continue;
1087
- const i = (sy * canvasW + sx) * 4;
1088
- r += data[i];
1089
- g += data[i + 1];
1090
- b += data[i + 2];
1091
- count += 1;
1092
- }
1093
- }
1094
- const oi = (y * w + x) * 3;
1095
- out[oi] = count ? r / count : BG[0];
1096
- out[oi + 1] = count ? g / count : BG[1];
1097
- out[oi + 2] = count ? b / count : BG[2];
1098
- }
1099
- }
1100
- return { pixels: out, width: w, height: h };
1101
- }
1102
- function blurRgb(buffer, width, height, radius) {
1103
- const tmp = new Uint8ClampedArray(buffer.length);
1104
- const out = new Uint8ClampedArray(buffer.length);
1105
- const window = radius * 2 + 1;
1106
- for (let y = 0;y < height; y += 1) {
1107
- let r = 0, g = 0, b = 0;
1108
- for (let x = -radius;x <= radius; x += 1) {
1109
- const sx = Math.max(0, Math.min(width - 1, x));
1110
- const i = (y * width + sx) * 3;
1111
- r += buffer[i];
1112
- g += buffer[i + 1];
1113
- b += buffer[i + 2];
1114
- }
1115
- for (let x = 0;x < width; x += 1) {
1116
- const oi = (y * width + x) * 3;
1117
- tmp[oi] = r / window;
1118
- tmp[oi + 1] = g / window;
1119
- tmp[oi + 2] = b / window;
1120
- const removeX = Math.max(0, x - radius);
1121
- const addX = Math.min(width - 1, x + radius + 1);
1122
- const ri = (y * width + removeX) * 3;
1123
- const ai = (y * width + addX) * 3;
1124
- r += tmp.length ? buffer[ai] - buffer[ri] : 0;
1125
- g += tmp.length ? buffer[ai + 1] - buffer[ri + 1] : 0;
1126
- b += tmp.length ? buffer[ai + 2] - buffer[ri + 2] : 0;
1127
- }
1128
- }
1129
- for (let x = 0;x < width; x += 1) {
1130
- let r = 0, g = 0, b = 0;
1131
- for (let y = -radius;y <= radius; y += 1) {
1132
- const sy = Math.max(0, Math.min(height - 1, y));
1133
- const i = (sy * width + x) * 3;
1134
- r += tmp[i];
1135
- g += tmp[i + 1];
1136
- b += tmp[i + 2];
1137
- }
1138
- for (let y = 0;y < height; y += 1) {
1139
- const oi = (y * width + x) * 3;
1140
- out[oi] = r / window;
1141
- out[oi + 1] = g / window;
1142
- out[oi + 2] = b / window;
1143
- const removeY = Math.max(0, y - radius);
1144
- const addY = Math.min(height - 1, y + radius + 1);
1145
- const ri = (removeY * width + x) * 3;
1146
- const ai = (addY * width + x) * 3;
1147
- r += tmp[ai] - tmp[ri];
1148
- g += tmp[ai + 1] - tmp[ri + 1];
1149
- b += tmp[ai + 2] - tmp[ri + 2];
1150
- }
1151
- }
1152
- return out;
1153
- }
1154
- function panelMaskKey(width, height, rect, headerPx, blurScale) {
1155
- return `${width}x${height}:${rect.left},${rect.top},${rect.width},${rect.height}:${Math.round(headerPx * 100) / 100}:${blurScale}`;
1156
- }
1157
- function getPanelMask(width, height, rect, headerPx, blurScale) {
1158
- const key = panelMaskKey(width, height, rect, headerPx, blurScale);
1159
- const cached = panelMaskCache.get(key);
1160
- if (cached)
1161
- return cached;
1162
- const radius = Math.max(PANEL_MASK_RADIUS_MIN, Math.min(PANEL_MASK_RADIUS_MAX, Math.round(Math.min(rect.width, rect.height) * PANEL_MASK_RADIUS_FACTOR)));
1163
- const sampledWidth = Math.max(1, Math.ceil(rect.width / blurScale));
1164
- const sampledHeight = Math.max(1, Math.ceil(rect.height / blurScale));
1165
- const x0 = Math.max(0, rect.left);
1166
- const y0 = Math.max(0, rect.top);
1167
- const x1 = Math.min(width - 1, rect.left + rect.width - 1);
1168
- const y1 = Math.min(height - 1, rect.top + rect.height - 1);
1169
- const indices = [];
1170
- const sampleIndices = [];
1171
- const panelAlpha = [];
1172
- const edgeAlpha = [];
1173
- const headerFlags = [];
1174
- const dividerIndices = [];
1175
- for (let y = y0;y <= y1; y += 1) {
1176
- for (let x = x0;x <= x1; x += 1) {
1177
- const a = roundRectAlpha(x + 0.5, y + 0.5, rect.left, rect.top, rect.width, rect.height, radius);
1178
- if (a <= 0)
1179
- continue;
1180
- const edge = roundRectAlpha(x + 0.5, y + 0.5, rect.left + 1.2, rect.top + 1.2, rect.width - 2.4, rect.height - 2.4, Math.max(1, radius - 1.2));
1181
- const sx = Math.max(0, Math.min(sampledWidth - 1, Math.floor((x - rect.left) / blurScale)));
1182
- const sy = Math.max(0, Math.min(sampledHeight - 1, Math.floor((y - rect.top) / blurScale)));
1183
- indices.push((y * width + x) * 4);
1184
- sampleIndices.push((sy * sampledWidth + sx) * 3);
1185
- panelAlpha.push(a);
1186
- edgeAlpha.push(edge < 0.96 ? Math.min(1, (1 - edge) * 0.7) : 0);
1187
- headerFlags.push(y < rect.top + headerPx ? 1 : 0);
1188
- }
1189
- }
1190
- const dividerY = Math.round(rect.top + headerPx);
1191
- if (dividerY > y0 && dividerY < y1) {
1192
- for (let x = x0 + radius;x <= x1 - radius; x += 1) {
1193
- dividerIndices.push((dividerY * width + x) * 4);
1194
- }
1195
- }
1196
- const mask = {
1197
- key,
1198
- indices: Uint32Array.from(indices),
1199
- sampleIndices: Uint32Array.from(sampleIndices),
1200
- panelAlpha: Float32Array.from(panelAlpha),
1201
- edgeAlpha: Float32Array.from(edgeAlpha),
1202
- headerFlags: Uint8Array.from(headerFlags),
1203
- dividerIndices: Uint32Array.from(dividerIndices)
1204
- };
1205
- panelMaskCache.set(key, mask);
1206
- while (panelMaskCache.size > PANEL_MASK_CACHE_LIMIT) {
1207
- const oldest = panelMaskCache.keys().next().value;
1208
- if (!oldest)
1209
- break;
1210
- panelMaskCache.delete(oldest);
1211
- }
1212
- return mask;
1213
- }
1214
- function compositePanel(data, width, height, rect, headerPx) {
1215
- const blurScale = PANEL_BLUR_SCALE;
1216
- const sampled = downsampleRegion(data, width, height, rect, blurScale);
1217
- const blurRadius = Math.max(PANEL_BLUR_RADIUS_MIN, Math.min(PANEL_BLUR_RADIUS_MAX, Math.round(Math.min(rect.width, rect.height) * PANEL_BLUR_RADIUS_FACTOR)));
1218
- const blurred = blurRgb(sampled.pixels, sampled.width, sampled.height, blurRadius);
1219
- const mask = getPanelMask(width, height, rect, headerPx, blurScale);
1220
- for (let i = 0;i < mask.indices.length; i += 1) {
1221
- const idx = mask.indices[i];
1222
- const sampleIdx = mask.sampleIndices[i];
1223
- data[idx] = blurred[sampleIdx];
1224
- data[idx + 1] = blurred[sampleIdx + 1];
1225
- data[idx + 2] = blurred[sampleIdx + 2];
1226
- data[idx + 3] = 255;
1227
- blendOver(data, idx, mask.headerFlags[i] ? PANEL_HEADER : PANEL, mask.panelAlpha[i]);
1228
- const edge = mask.edgeAlpha[i];
1229
- if (edge > 0)
1230
- blendOver(data, idx, PANEL_LINE2, edge);
1231
- }
1232
- for (let i = 0;i < mask.dividerIndices.length; i += 1) {
1233
- blendOver(data, mask.dividerIndices[i], PANEL_LINE2, 0.28);
1234
- }
1235
- }
1236
- var RIG_GLYPH_STROKES = {
1237
- R: [[0, 0, 0, 1], [0, 0, 0.82, 0], [0.82, 0, 0.82, 0.5], [0, 0.5, 0.82, 0.5], [0.36, 0.5, 0.92, 1]],
1238
- I: [[0.5, 0, 0.5, 1], [0.18, 0, 0.82, 0], [0.18, 1, 0.82, 1]],
1239
- G: [[0.92, 0.08, 0.12, 0], [0.12, 0, 0.12, 1], [0.12, 1, 0.92, 1], [0.92, 0.5, 0.92, 1], [0.5, 0.5, 0.92, 0.5]]
1240
- };
1241
- function drawBigRigWordmark(data, width, height, layout, load) {
1242
- const sideBySide = layout.width >= FLEET_GRID_WIDTH * 1.9;
1243
- if (!sideBySide)
1244
- return;
1245
- const letters = "RIG";
1246
- const min = Math.min(width, height);
1247
- const glyphH = height * 0.42;
1248
- const glyphW = width * 0.13;
1249
- const gap = glyphW * 0.3;
1250
- const totalW = letters.length * glyphW + (letters.length - 1) * gap;
1251
- const centerX = width * 0.71;
1252
- const startX = centerX - totalW / 2;
1253
- const top = (height - glyphH) / 2;
1254
- const stroke = Math.max(2, min * 0.013);
1255
- drawGlow2(data, width, height, centerX, top + glyphH / 2, Math.max(glyphW, glyphH) * 0.9, LIME, 0.022 + load * 0.02);
1256
- const strokeAlpha = 0.1 + load * 0.06;
1257
- letters.split("").forEach((letter, index) => {
1258
- const segments = RIG_GLYPH_STROKES[letter];
1259
- if (!segments)
1260
- return;
1261
- const ox = startX + index * (glyphW + gap);
1262
- for (const [x0, y0, x1, y1] of segments) {
1263
- drawLine2(data, width, height, ox + x0 * glyphW, top + y0 * glyphH, ox + x1 * glyphW, top + y1 * glyphH, LIME_DIM, strokeAlpha, stroke);
1264
- }
1265
- });
1266
- }
1267
- function drawBackground(data, width, height, _tick, scene, layout, load, activeRuns) {
1268
- fillRgba(data, BG, BG_WORD);
1269
- drawStaticAsciiFleetBackground(data, width, height, scene, layout, load, activeRuns);
1270
- drawBigRigWordmark(data, width, height, layout, load);
1271
- applyStaticAtmosphere(data, width, height, load);
1272
- }
1273
- function imageVisualFrameKey(input) {
1274
- const width = Math.max(1, Math.floor(input.pixelSize.width));
1275
- const height = Math.max(1, Math.floor(input.pixelSize.height));
1276
- const layer = "layer" in input ? input.layer ?? "full" : "full";
1277
- const load = loadBucket(input.load);
1278
- return `${layer}:${width}x${height}:${input.layout.width}x${input.layout.height}:${input.scene}:${input.tick}:l${load}:${input.panels.map((panel) => `${panel.id}:${panel.top}:${panel.height}:${panel.width ?? ""}:${panel.left ?? ""}:${panel.headerHeight ?? ""}`).join("|")}`;
1279
- }
1280
- function encodeKittyFrame(width, height, data, input) {
1281
- if (input.transport === "png") {
1282
- const png = encodePng(width, height, data);
1283
- return kittyImageSequence(png.toString("base64"), { columns: input.layout.width, rows: input.layout.height, imageId: input.imageId, zIndex: input.zIndex, format: 100 });
1284
- }
1285
- const compressed = deflateSync(data, { level: ZLIB_LEVEL });
1286
- return kittyImageSequence(compressed.toString("base64"), {
1287
- columns: input.layout.width,
1288
- rows: input.layout.height,
1289
- imageId: input.imageId,
1290
- zIndex: input.zIndex,
1291
- format: 32,
1292
- pixelWidth: width,
1293
- pixelHeight: height,
1294
- compressed: true
1295
- });
1296
- }
1297
- function cropRgba(data, sourceWidth, rect) {
1298
- const out = new Uint8ClampedArray(rect.width * rect.height * 4);
1299
- for (let y = 0;y < rect.height; y += 1) {
1300
- const sourceStart = ((rect.top + y) * sourceWidth + rect.left) * 4;
1301
- out.set(data.subarray(sourceStart, sourceStart + rect.width * 4), y * rect.width * 4);
1302
- }
1303
- return out;
1304
- }
1305
- function encodePanelPatch(data, sourceWidth, placement, imageId, zIndex) {
1306
- const patch = cropRgba(data, sourceWidth, placement);
1307
- const png = encodePng(placement.width, placement.height, patch);
1308
- const sequence = kittyImageSequence(png.toString("base64"), {
1309
- columns: Math.max(1, Math.round(placement.widthCells)),
1310
- rows: Math.max(1, Math.round(placement.heightCells)),
1311
- imageId,
1312
- zIndex,
1313
- format: 100
1314
- });
1315
- return `\x1B[${Math.max(1, Math.round(placement.topCells) + 1)};${Math.max(1, Math.round(placement.leftCells) + 1)}H${sequence}`;
1316
- }
1317
- function renderImageVisualFrame(input) {
1318
- const width = Math.max(1, Math.floor(input.pixelSize.width));
1319
- const height = Math.max(1, Math.floor(input.pixelSize.height));
1320
- const byteCount = width * height * 4;
1321
- if (byteCount > MAX_IMAGE_BYTES)
1322
- return null;
1323
- const layer = input.layer ?? "full";
1324
- const data = new Uint8ClampedArray(byteCount);
1325
- const load = loadBucket(input.load) / LOAD_BUCKETS;
1326
- const activeRuns = Math.max(0, Math.floor(input.activeRuns ?? 0));
1327
- drawBackground(data, width, height, 0, input.scene, input.layout, load, activeRuns);
1328
- if (layer === "split") {
1329
- const sequences = [encodeKittyFrame(width, height, data, input)];
1330
- let panelIndex = 0;
1331
- for (const panel of input.panels) {
1332
- if (panel.chrome !== "ad-terminal")
1333
- continue;
1334
- const placement = panelPixelPlacement(input.layout, panel, { width, height });
1335
- if (!placement)
1336
- continue;
1337
- const cellH = height / input.layout.height;
1338
- const headerPx = Math.max(cellH * 3, (panel.headerHeight ?? 3) * cellH);
1339
- compositePanel(data, width, height, placement, headerPx);
1340
- const imageId = input.imageIds?.[panelIndex] ?? (input.imageId + 1000 + panelIndex >>> 0 || panelIndex + 1);
1341
- sequences.push(encodePanelPatch(data, width, placement, imageId, -12));
1342
- panelIndex += 1;
1343
- }
1344
- return { key: imageVisualFrameKey(input), sequence: sequences.join("") };
1345
- }
1346
- if (layer === "panel-chrome")
1347
- return { key: imageVisualFrameKey(input), sequence: "" };
1348
- if (layer === "background") {
1349
- return { key: imageVisualFrameKey(input), sequence: encodeKittyFrame(width, height, data, input) };
1350
- }
1351
- if (layer === "panel-patches") {
1352
- const sequences = [];
1353
- let panelIndex = 0;
1354
- for (const panel of input.panels) {
1355
- if (panel.chrome !== "ad-terminal")
1356
- continue;
1357
- const placement = panelPixelPlacement(input.layout, panel, { width, height });
1358
- if (!placement)
1359
- continue;
1360
- const cellH = height / input.layout.height;
1361
- const headerPx = Math.max(cellH * 3, (panel.headerHeight ?? 3) * cellH);
1362
- compositePanel(data, width, height, placement, headerPx);
1363
- const imageId = input.imageIds?.[panelIndex] ?? (input.imageId + 1000 + panelIndex >>> 0 || panelIndex + 1);
1364
- sequences.push(encodePanelPatch(data, width, placement, imageId, input.zIndex));
1365
- panelIndex += 1;
1366
- }
1367
- return { key: imageVisualFrameKey(input), sequence: sequences.join("") };
1368
- }
1369
- for (const panel of input.panels) {
1370
- if (panel.chrome !== "ad-terminal")
1371
- continue;
1372
- const rect = panelRect(input.layout, panel, { width, height });
1373
- if (!rect)
1374
- continue;
1375
- const cellH = height / input.layout.height;
1376
- const headerPx = Math.max(cellH * 3, (panel.headerHeight ?? 3) * cellH);
1377
- compositePanel(data, width, height, rect, headerPx);
1378
- }
1379
- return { key: imageVisualFrameKey(input), sequence: encodeKittyFrame(width, height, data, input) };
1380
- }
1381
- function shouldRenderImagesInline() {
1382
- return process.env.RIG_OPENTUI_IMAGE_WORKER === "0" || import.meta.url.includes("$bunfs");
1383
- }
1384
- function createImageWorker() {
1385
- if (shouldRenderImagesInline())
1386
- return null;
1387
- const isTypeScriptRuntime = import.meta.url.endsWith(".ts");
1388
- const workerUrl = new URL(isTypeScriptRuntime ? "./image-visual-layer-worker.ts" : "./image-visual-layer-worker.js", import.meta.url);
1389
- try {
1390
- return new Worker(workerUrl);
1391
- } catch {
1392
- if (typeof process.versions.bun === "string") {
1393
- try {
1394
- return new Worker("./src/app-opentui/render/image-visual-layer-worker.ts");
1395
- } catch {}
1396
- }
1397
- return null;
1398
- }
1399
- }
1400
- var RECENT_WRITTEN_LIMIT = 24;
1401
- var DEFAULT_IMAGE_OUTPUT_BACKLOG_BYTES = 256 * 1024;
1402
- var DEFAULT_IMAGE_OUTPUT_BYTES_PER_SECOND = 850 * 1024;
1403
- function imageOutputBacklogBytes() {
1404
- const raw = Number.parseInt(process.env.RIG_OPENTUI_IMAGE_BACKLOG_BYTES ?? "", 10);
1405
- if (Number.isFinite(raw) && raw > 0)
1406
- return Math.max(64 * 1024, Math.min(2 * 1024 * 1024, raw));
1407
- return DEFAULT_IMAGE_OUTPUT_BACKLOG_BYTES;
1408
- }
1409
- function imageOutputBytesPerSecond() {
1410
- const raw = Number.parseInt(process.env.RIG_OPENTUI_IMAGE_BYTES_PER_SECOND ?? "", 10);
1411
- if (Number.isFinite(raw) && raw > 0)
1412
- return Math.max(128 * 1024, Math.min(2 * 1024 * 1024, raw));
1413
- return DEFAULT_IMAGE_OUTPUT_BYTES_PER_SECOND;
1414
- }
1415
- function pendingLayerKey(key) {
1416
- return key.split(":", 1)[0] || "full";
1417
- }
1418
-
1419
- class ImageVisualLayer {
1420
- imageId = allocateImageId();
1421
- panelImageIds = Array.from({ length: 8 }, () => allocateImageId());
1422
- panelChromeImageIds = Array.from({ length: 8 }, () => allocateImageId());
1423
- stdout;
1424
- onFrameReady;
1425
- protocol;
1426
- transport = imageTransport();
1427
- maxOutputBacklogBytes = imageOutputBacklogBytes();
1428
- outputBytesPerSecond = imageOutputBytesPerSecond();
1429
- outputBudgetBytes = imageOutputBytesPerSecond();
1430
- lastBudgetAtMs = Date.now();
1431
- motionSlot = this.createSlot();
1432
- workersStarted = false;
1433
- pendingFrames = new Map;
1434
- recentWrittenKeys = [];
1435
- imagesVisible = false;
1436
- flushPaused = false;
1437
- requestId = 0;
1438
- lastBackgroundKey = "";
1439
- fatalWorkerError = null;
1440
- destroyed = false;
1441
- constructor(stdout = process.stdout, onFrameReady) {
1442
- this.stdout = stdout;
1443
- this.onFrameReady = onFrameReady;
1444
- this.protocol = getRigTerminalCapabilities().imageProtocol;
1445
- }
1446
- get enabled() {
1447
- return this.protocol === "kitty";
1448
- }
1449
- clear() {
1450
- if (this.enabled) {
1451
- if (this.imagesVisible)
1452
- this.stdout.write([this.imageId, ...this.panelImageIds, ...this.panelChromeImageIds].map((id) => deleteKittyImage(id)).join("") + "\x1B[?25h");
1453
- this.imagesVisible = false;
1454
- this.pendingFrames.clear();
1455
- this.recentWrittenKeys.length = 0;
1456
- this.resetSlot(this.motionSlot);
1457
- this.lastBackgroundKey = "";
1458
- this.outputBudgetBytes = this.outputBytesPerSecond;
1459
- this.lastBudgetAtMs = Date.now();
1460
- this.motionSlot.clearedThroughRequestId = this.requestId;
1461
- }
1462
- }
1463
- destroy() {
1464
- if (this.destroyed)
1465
- return;
1466
- this.clear();
1467
- this.destroyed = true;
1468
- const workers = [this.motionSlot.worker];
1469
- this.motionSlot.worker = null;
1470
- for (const worker of workers)
1471
- if (worker)
1472
- worker.terminate().catch(() => {
1473
- return;
1474
- });
1475
- }
1476
- setFlushPaused(paused) {
1477
- this.flushPaused = paused;
1478
- }
1479
- isReady(input) {
1480
- if (!this.enabled || this.destroyed)
1481
- return true;
1482
- this.throwIfFatal();
1483
- const splitKey = imageVisualFrameKey({ ...input, tick: 0, layer: "split" });
1484
- return this.recentWrittenKeys.includes(splitKey) || Array.from(this.pendingFrames.values()).some((frame) => frame.key === splitKey);
1485
- }
1486
- render(input) {
1487
- if (!this.enabled || this.destroyed)
1488
- return;
1489
- this.throwIfFatal();
1490
- if (this.transport !== "png")
1491
- this.failWorker("renderer", new Error("OpenTUI image visuals require PNG transport for static-background rendering."));
1492
- this.ensureWorkersStarted();
1493
- const width = Math.max(1, Math.floor(input.pixelSize.width));
1494
- const height = Math.max(1, Math.floor(input.pixelSize.height));
1495
- if (width * height * 4 > MAX_IMAGE_BYTES)
1496
- return;
1497
- if (this.isOutputBackedUp())
1498
- return;
1499
- this.refillOutputBudget();
1500
- const splitInput = { ...input, tick: 0, layer: "split" };
1501
- const splitKey = imageVisualFrameKey(splitInput);
1502
- if (input.force || splitKey !== this.lastBackgroundKey) {
1503
- this.scheduleRender(this.motionSlot, splitInput, this.imageId, -30, input.force, this.panelImageIds);
1504
- this.lastBackgroundKey = splitKey;
1505
- }
1506
- }
1507
- flush() {
1508
- this.throwIfFatal();
1509
- if (this.flushPaused)
1510
- return false;
1511
- if (this.pendingFrames.size === 0)
1512
- return false;
1513
- this.refillOutputBudget();
1514
- if (this.isOutputBackedUp()) {
1515
- const retainedSplit = this.pendingFrames.get("split");
1516
- this.pendingFrames.clear();
1517
- if (retainedSplit)
1518
- this.pendingFrames.set("split", retainedSplit);
1519
- return false;
1520
- }
1521
- const framePriority = (frame) => {
1522
- const layer = pendingLayerKey(frame.key);
1523
- if (layer === "split")
1524
- return 1;
1525
- return 4;
1526
- };
1527
- const frames = Array.from(this.pendingFrames.values()).sort((a, b) => framePriority(a) - framePriority(b));
1528
- const prefix = "\x1B[?25l\x1B7\x1B[s\x1B[H";
1529
- const suffix = "\x1B[u\x1B8";
1530
- const selected = [];
1531
- const retained = new Map;
1532
- let sequence = "";
1533
- let byteLength = Buffer.byteLength(prefix + suffix);
1534
- for (const frame of frames) {
1535
- const candidate = sequence + frame.sequence;
1536
- const candidateBytes = Buffer.byteLength(prefix + candidate + suffix);
1537
- const layer = pendingLayerKey(frame.key);
1538
- const allowOneStaticFrame = selected.length === 0 && layer === "split";
1539
- if (candidateBytes <= this.outputBudgetBytes || allowOneStaticFrame) {
1540
- selected.push(frame);
1541
- sequence = candidate;
1542
- byteLength = candidateBytes;
1543
- } else if (layer === "split") {
1544
- retained.set(layer, frame);
1545
- }
1546
- }
1547
- this.pendingFrames.clear();
1548
- for (const [layer, frame] of retained)
1549
- this.pendingFrames.set(layer, frame);
1550
- if (!sequence || selected.length === 0)
1551
- return false;
1552
- const payload = `${prefix}${sequence}${suffix}`;
1553
- for (const frame of selected)
1554
- this.markWritten(frame.key);
1555
- this.outputBudgetBytes -= byteLength;
1556
- this.stdout.cork?.();
1557
- const accepted = this.stdout.write(payload);
1558
- this.stdout.uncork?.();
1559
- this.imagesVisible = true;
1560
- return accepted;
1561
- }
1562
- createSlot() {
1563
- return { worker: null, busy: false, queuedRequest: null, inFlightKey: "", queuedKey: "", clearedThroughRequestId: 0, latestRequestId: 0 };
1564
- }
1565
- resetSlot(slot) {
1566
- slot.busy = false;
1567
- slot.queuedRequest = null;
1568
- slot.inFlightKey = "";
1569
- slot.queuedKey = "";
1570
- }
1571
- markWritten(key) {
1572
- this.recentWrittenKeys.push(key);
1573
- while (this.recentWrittenKeys.length > RECENT_WRITTEN_LIMIT)
1574
- this.recentWrittenKeys.shift();
1575
- }
1576
- refillOutputBudget() {
1577
- const now = Date.now();
1578
- const elapsedMs = Math.max(0, now - this.lastBudgetAtMs);
1579
- this.lastBudgetAtMs = now;
1580
- this.outputBudgetBytes = Math.min(this.outputBytesPerSecond, this.outputBudgetBytes + elapsedMs / 1000 * this.outputBytesPerSecond);
1581
- }
1582
- isOutputBackedUp() {
1583
- return Boolean(this.stdout.writableNeedDrain) || this.stdout.writableLength > this.maxOutputBacklogBytes;
1584
- }
1585
- stageFrame(frame) {
1586
- this.pendingFrames.set(pendingLayerKey(frame.key), frame);
1587
- }
1588
- isKnownKey(slot, key) {
1589
- return this.recentWrittenKeys.includes(key) || Array.from(this.pendingFrames.values()).some((frame) => frame.key === key) || key === slot.inFlightKey || key === slot.queuedKey;
1590
- }
1591
- ensureWorkersStarted() {
1592
- if (this.workersStarted)
1593
- return;
1594
- this.workersStarted = true;
1595
- this.startWorker(this.motionSlot, "static-visuals");
1596
- }
1597
- failWorker(name, error) {
1598
- const detail = error instanceof Error ? error.message : String(error);
1599
- this.fatalWorkerError ??= new Error(`OpenTUI image worker ${name} failed: ${detail}`);
1600
- throw this.fatalWorkerError;
1601
- }
1602
- throwIfFatal() {
1603
- if (this.fatalWorkerError)
1604
- throw this.fatalWorkerError;
1605
- }
1606
- scheduleRender(slot, input, imageId, zIndex, force, imageIds) {
1607
- this.throwIfFatal();
1608
- const key = imageVisualFrameKey(input);
1609
- if (!force && this.isKnownKey(slot, key))
1610
- return;
1611
- const request = {
1612
- ...input,
1613
- imageId,
1614
- ...imageIds ? { imageIds } : {},
1615
- zIndex,
1616
- transport: this.transport,
1617
- requestId: ++this.requestId,
1618
- key
1619
- };
1620
- slot.latestRequestId = request.requestId;
1621
- if (!slot.worker) {
1622
- this.renderInline(slot, request);
1623
- return;
1624
- }
1625
- this.enqueueWorkerRender(slot, request);
1626
- }
1627
- startWorker(slot, name) {
1628
- const worker = createImageWorker();
1629
- if (!worker)
1630
- return;
1631
- slot.worker = worker;
1632
- worker.on("message", (message) => this.handleWorkerMessage(slot, message));
1633
- worker.once("error", (error) => {
1634
- if (!this.destroyed)
1635
- this.fatalWorkerError ??= new Error(`OpenTUI image worker ${name} failed: ${error instanceof Error ? error.message : String(error)}`);
1636
- });
1637
- worker.once("exit", (code) => {
1638
- if (!this.destroyed)
1639
- this.fatalWorkerError ??= new Error(`OpenTUI image worker ${name} exited unexpectedly with code ${code}.`);
1640
- });
1641
- }
1642
- renderInline(slot, request) {
1643
- try {
1644
- const result = renderImageVisualFrame(request);
1645
- if (result?.sequence && !this.isKnownKey(slot, result.key) && (!this.isOutputBackedUp() || pendingLayerKey(result.key) === "split")) {
1646
- this.stageFrame({ key: result.key, sequence: result.sequence });
1647
- this.onFrameReady?.();
1648
- }
1649
- } catch (error) {
1650
- this.failWorker(String(request.layer ?? "visual"), error);
1651
- }
1652
- }
1653
- enqueueWorkerRender(slot, request) {
1654
- this.throwIfFatal();
1655
- if (slot.busy) {
1656
- slot.queuedRequest = request;
1657
- slot.queuedKey = request.key;
1658
- return;
1659
- }
1660
- this.dispatchWorkerRender(slot, request);
1661
- }
1662
- dispatchWorkerRender(slot, request) {
1663
- this.throwIfFatal();
1664
- if (!slot.worker)
1665
- this.failWorker(String(request.layer ?? "visual"), new Error("worker is unavailable"));
1666
- slot.busy = true;
1667
- slot.inFlightKey = request.key;
1668
- try {
1669
- slot.worker.postMessage(request);
1670
- } catch (error) {
1671
- this.failWorker(String(request.layer ?? "visual"), error);
1672
- }
1673
- }
1674
- handleWorkerMessage(slot, message) {
1675
- if (this.destroyed || !message || typeof message !== "object")
1676
- return;
1677
- const response = message;
1678
- slot.busy = false;
1679
- slot.inFlightKey = "";
1680
- const isStale = response.requestId <= slot.clearedThroughRequestId || response.requestId < slot.latestRequestId;
1681
- if (!isStale) {
1682
- if (response.error)
1683
- this.failWorker(pendingLayerKey(response.key), new Error(response.error));
1684
- if (response.sequence && !this.isKnownKey(slot, response.key) && (!this.isOutputBackedUp() || pendingLayerKey(response.key) === "split")) {
1685
- this.stageFrame({ key: response.key, sequence: response.sequence });
1686
- this.onFrameReady?.();
1687
- }
1688
- }
1689
- const next = slot.queuedRequest;
1690
- slot.queuedRequest = null;
1691
- slot.queuedKey = "";
1692
- if (next && !this.isKnownKey(slot, next.key))
1693
- this.dispatchWorkerRender(slot, next);
1694
- }
1695
- }
1696
- function pixelSizeForRenderer(renderer) {
1697
- const resolution = renderer.resolution;
1698
- const base = resolution?.width && resolution?.height ? resolution : { width: renderer.width * 12, height: renderer.height * 24 };
1699
- const scale = imageResolutionScale();
1700
- return {
1701
- width: Math.max(renderer.width, Math.floor(base.width * scale)),
1702
- height: Math.max(renderer.height, Math.floor(base.height * scale))
1703
- };
1704
- }
1705
- function forceModernImageVisuals() {
1706
- return getRigTerminalCapabilities().supportsKittyImages;
1707
- }
1708
-
1709
730
  // packages/cli/src/app-opentui/fleet-stats.ts
1710
731
  var ACTIVE_STATUSES = new Set([
1711
732
  "running",
@@ -1763,68 +784,42 @@ function isTerminalScene(scene) {
1763
784
  }
1764
785
  function Backdrop(props) {
1765
786
  const renderer = useRenderer();
1766
- const imageRef = useRef(null);
1767
787
  const graphicsRef = useRef(null);
1768
788
  useEffect(() => {
1769
- const imageVisuals = forceModernImageVisuals() ? new ImageVisualLayer(process.stdout, () => renderer.requestRender?.()) : null;
1770
- if (imageVisuals?.enabled) {
1771
- imageRef.current = imageVisuals;
1772
- } else {
1773
- const layout = computeStageLayout(renderer.width, renderer.height);
1774
- const graphics = createGraphicsLayer(renderer, layout);
1775
- renderer.root.add(graphics);
1776
- graphicsRef.current = graphics;
1777
- }
789
+ const layout = computeStageLayout(renderer.width, renderer.height);
790
+ const graphics = createGraphicsLayer(renderer, layout);
791
+ renderer.root.add(graphics);
792
+ graphicsRef.current = graphics;
1778
793
  return () => {
1779
- imageRef.current?.destroy();
1780
- const graphics = graphicsRef.current;
1781
- if (graphics) {
794
+ const g = graphicsRef.current;
795
+ if (g) {
1782
796
  try {
1783
- renderer.root.remove(graphics.id);
797
+ renderer.root.remove(g.id);
1784
798
  } catch {}
1785
799
  }
1786
- imageRef.current = null;
1787
800
  graphicsRef.current = null;
1788
801
  };
1789
802
  }, [renderer]);
1790
803
  useEffect(() => {
1791
- const layout = computeStageLayout(renderer.width, renderer.height);
1792
- const image = imageRef.current;
1793
804
  const graphics = graphicsRef.current;
805
+ if (!graphics)
806
+ return;
807
+ const layout = computeStageLayout(renderer.width, renderer.height);
1794
808
  if (layout.tooSmall) {
1795
- image?.clear();
1796
- if (graphics)
1797
- clearGraphicsLayer(graphics);
809
+ clearGraphicsLayer(graphics);
1798
810
  return;
1799
811
  }
1800
812
  const stats = fleetStatsFromState(props.state);
1801
- const tick = props.state.tick;
1802
- const animationTick = Math.floor(tick / ANIMATION_SLOWDOWN);
813
+ const animationTick = Math.floor(props.state.tick / ANIMATION_SLOWDOWN);
1803
814
  const panels = (props.frame.panels ?? []).map((panel) => ({ ...panel }));
1804
815
  const terminalActive = props.frame.terminalActive ?? isTerminalScene(props.state.scene);
1805
816
  const fullScreen = Boolean(props.frame.fullScreen);
1806
- if (image) {
1807
- if (terminalActive || fullScreen) {
1808
- image.clear();
1809
- } else {
1810
- image.render({
1811
- layout,
1812
- pixelSize: pixelSizeForRenderer(renderer),
1813
- panels,
1814
- scene: props.state.scene,
1815
- tick,
1816
- load: stats.load,
1817
- activeRuns: stats.active
1818
- });
1819
- }
1820
- } else if (graphics) {
1821
- resizeGraphicsLayer(graphics, layout);
1822
- if (terminalActive || fullScreen) {
1823
- clearGraphicsLayer(graphics);
1824
- } else {
1825
- drawAmbientField(graphics, layout, animationTick, props.state.scene, stats.load, stats.active);
1826
- drawPanelChrome(graphics, layout, panels);
1827
- }
817
+ resizeGraphicsLayer(graphics, layout);
818
+ if (terminalActive || fullScreen) {
819
+ clearGraphicsLayer(graphics);
820
+ } else {
821
+ drawAmbientField(graphics, layout, animationTick, props.state.scene, stats.load, stats.active);
822
+ drawPanelChrome(graphics, layout, panels);
1828
823
  }
1829
824
  });
1830
825
  return null;