From 9d99d70da8c3b950f5d14daad64052c45ad213c2 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 21:59:57 -0500 Subject: [PATCH 1/5] Add interactive per-layer routing floorplanner canvas across host, GPUI, and Web UI --- i18n/en.msg | 21 + i18n/es.msg | 21 + i18n/ja.msg | 21 + .../src/main/java/dev/backplane/mobile/Msg.kt | 123 +- mobile/ios/Shared/TrCatalog.swift | 21 + native/gpui/src/screens/mgmt.rs | 4 +- native/gpui/src/screens/mgmt_plan.rs | 273 ++- native/gpui/src/screens/mgmt_plan_canvas.rs | 1947 +++++++++++++++++ native/gpui/src/screens/mod.rs | 1 + native/host/src/data/ext.rs | 4 +- native/host/src/data/webpolicy.rs | 2 + native/host/src/kicad/board.rs | 2 +- native/host/src/plan/geom.rs | 923 ++++++++ native/host/src/plan/mod.rs | 373 +++- native/host/src/plan/panel.rs | 150 +- web/dist/assets/app.js | 36 +- web/dist/assets/pair.js | 2 +- web/dist/assets/style.css | 218 ++ web/dist/manifest.json | 50 +- web/src/mgmt-model.ts | 395 +++- web/src/mgmt.ts | 497 ++++- web/src/plan-canvas.ts | 951 ++++++++ web/src/shell.css | 218 ++ web/test/mgmt.test.ts | 69 + 24 files changed, 6251 insertions(+), 71 deletions(-) create mode 100644 native/gpui/src/screens/mgmt_plan_canvas.rs create mode 100644 native/host/src/plan/geom.rs create mode 100644 web/src/plan-canvas.ts diff --git a/i18n/en.msg b/i18n/en.msg index 14367cb662..57c777926b 100644 --- a/i18n/en.msg +++ b/i18n/en.msg @@ -4978,3 +4978,24 @@ gpui.keys.mgmt.plan = Plan panel beside the design: open or close web.plan.awaiting = {n} awaiting approval web.plan.net.one = 1 net web.plan.nets = {n} nets +gpui.mgmt.plan.view.canvas = Canvas +gpui.mgmt.plan.view.split = Split +gpui.mgmt.plan.view.list = List +gpui.mgmt.plan.grid.all = All layers +gpui.mgmt.plan.grid.pair = Side by side +gpui.mgmt.plan.grid.single = Single +gpui.mgmt.plan.expand = Expand +gpui.mgmt.plan.compact = Compact +gpui.mgmt.plan.sync = Link zoom +gpui.mgmt.plan.fit = Fit +gpui.mgmt.plan.lock = Lock +gpui.mgmt.plan.unlock = Unlock +gpui.mgmt.plan.layer.move = Move to layer +gpui.mgmt.plan.width = Width +gpui.mgmt.plan.addnote = Add note +gpui.mgmt.plan.note.placeholder = Steering note for router… +gpui.mgmt.plan.hint = Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove +gpui.mgmt.plan.rejectlayer = Reject layer +gpui.mgmt.plan.edited = Edited +gpui.mgmt.plan.locked = Locked +gpui.mgmt.plan.noitems = No corridors or planes on this layer diff --git a/i18n/es.msg b/i18n/es.msg index 57bdc53082..ca271f3fa8 100644 --- a/i18n/es.msg +++ b/i18n/es.msg @@ -4978,3 +4978,24 @@ gpui.keys.mgmt.plan = Panel de plan junto al diseño: abrir o cerrar web.plan.awaiting = {n} esperando aprobación web.plan.net.one = 1 red web.plan.nets = {n} redes +gpui.mgmt.plan.view.canvas = Lienzo +gpui.mgmt.plan.view.split = Dividido +gpui.mgmt.plan.view.list = Lista +gpui.mgmt.plan.grid.all = Todas las capas +gpui.mgmt.plan.grid.pair = Lado a lado +gpui.mgmt.plan.grid.single = Única +gpui.mgmt.plan.expand = Expandir +gpui.mgmt.plan.compact = Compacto +gpui.mgmt.plan.sync = Vincular zoom +gpui.mgmt.plan.fit = Ajustar +gpui.mgmt.plan.lock = Bloquear +gpui.mgmt.plan.unlock = Desbloquear +gpui.mgmt.plan.layer.move = Mover a capa +gpui.mgmt.plan.width = Ancho +gpui.mgmt.plan.addnote = Añadir nota +gpui.mgmt.plan.note.placeholder = Nota de guiado para el router… +gpui.mgmt.plan.hint = Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar +gpui.mgmt.plan.rejectlayer = Rechazar capa +gpui.mgmt.plan.edited = Editado +gpui.mgmt.plan.locked = Bloqueado +gpui.mgmt.plan.noitems = Sin corredores ni planos en esta capa diff --git a/i18n/ja.msg b/i18n/ja.msg index 2e0b8281c6..7a08046bcf 100644 --- a/i18n/ja.msg +++ b/i18n/ja.msg @@ -5001,3 +5001,24 @@ gpui.keys.mgmt.plan = 設計横の計画パネル: 開くまたは閉じる web.plan.awaiting = {n} 件が承認待ち web.plan.net.one = 1 ネット web.plan.nets = {n} ネット +gpui.mgmt.plan.view.canvas = キャンバス +gpui.mgmt.plan.view.split = 分割 +gpui.mgmt.plan.view.list = リスト +gpui.mgmt.plan.grid.all = 全レイヤー +gpui.mgmt.plan.grid.pair = 並べて表示 +gpui.mgmt.plan.grid.single = 単一 +gpui.mgmt.plan.expand = 拡大 +gpui.mgmt.plan.compact = 標準 +gpui.mgmt.plan.sync = ズーム連動 +gpui.mgmt.plan.fit = 全体表示 +gpui.mgmt.plan.lock = ロック +gpui.mgmt.plan.unlock = ロック解除 +gpui.mgmt.plan.layer.move = レイヤー移動 +gpui.mgmt.plan.width = 幅 +gpui.mgmt.plan.addnote = メモを追加 +gpui.mgmt.plan.note.placeholder = ルーターへの指示メモ… +gpui.mgmt.plan.hint = 頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除 +gpui.mgmt.plan.rejectlayer = レイヤーを却下 +gpui.mgmt.plan.edited = 編集済み +gpui.mgmt.plan.locked = ロック中 +gpui.mgmt.plan.noitems = このレイヤーにコリドーまたはプレーンがありません diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt index c207d0d970..bc6f1f41ce 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt @@ -4877,6 +4877,27 @@ object Msg { "web.plan.awaiting", "web.plan.net.one", "web.plan.nets", + "gpui.mgmt.plan.view.canvas", + "gpui.mgmt.plan.view.split", + "gpui.mgmt.plan.view.list", + "gpui.mgmt.plan.grid.all", + "gpui.mgmt.plan.grid.pair", + "gpui.mgmt.plan.grid.single", + "gpui.mgmt.plan.expand", + "gpui.mgmt.plan.compact", + "gpui.mgmt.plan.sync", + "gpui.mgmt.plan.fit", + "gpui.mgmt.plan.lock", + "gpui.mgmt.plan.unlock", + "gpui.mgmt.plan.layer.move", + "gpui.mgmt.plan.width", + "gpui.mgmt.plan.addnote", + "gpui.mgmt.plan.note.placeholder", + "gpui.mgmt.plan.hint", + "gpui.mgmt.plan.rejectlayer", + "gpui.mgmt.plan.edited", + "gpui.mgmt.plan.locked", + "gpui.mgmt.plan.noitems", ) internal val keys: Array by lazy { arrayOf(*keys0(), *keys1(), *keys2(), *keys3(), *keys4(), *keys5(), *keys6(), *keys7(), *keys8(), *keys9(), *keys10(), *keys11(), *keys12(), *keys13(), *keys14(), *keys15(), *keys16(), *keys17(), *keys18(), *keys19()) } private fun en0(): Array = arrayOf( @@ -9753,6 +9774,27 @@ object Msg { "{n} awaiting approval", "1 net", "{n} nets", + "Canvas", + "Split", + "List", + "All layers", + "Side by side", + "Single", + "Expand", + "Compact", + "Link zoom", + "Fit", + "Lock", + "Unlock", + "Move to layer", + "Width", + "Add note", + "Steering note for router…", + "Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove", + "Reject layer", + "Edited", + "Locked", + "No corridors or planes on this layer", ) internal val en: Array by lazy { arrayOf(*en0(), *en1(), *en2(), *en3(), *en4(), *en5(), *en6(), *en7(), *en8(), *en9(), *en10(), *en11(), *en12(), *en13(), *en14(), *en15(), *en16(), *en17(), *en18(), *en19()) } private fun ja0(): Array = arrayOf( @@ -14629,6 +14671,27 @@ object Msg { "{n} 件が承認待ち", "1 ネット", "{n} ネット", + "キャンバス", + "分割", + "リスト", + "全レイヤー", + "並べて表示", + "単一", + "拡大", + "標準", + "ズーム連動", + "全体表示", + "ロック", + "ロック解除", + "レイヤー移動", + "幅", + "メモを追加", + "ルーターへの指示メモ…", + "頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除", + "レイヤーを却下", + "編集済み", + "ロック中", + "このレイヤーにコリドーまたはプレーンがありません", ) internal val ja: Array by lazy { arrayOf(*ja0(), *ja1(), *ja2(), *ja3(), *ja4(), *ja5(), *ja6(), *ja7(), *ja8(), *ja9(), *ja10(), *ja11(), *ja12(), *ja13(), *ja14(), *ja15(), *ja16(), *ja17(), *ja18(), *ja19()) } private fun es0(): Array = arrayOf( @@ -19505,6 +19568,27 @@ object Msg { "{n} esperando aprobación", "1 red", "{n} redes", + "Lienzo", + "Dividido", + "Lista", + "Todas las capas", + "Lado a lado", + "Única", + "Expandir", + "Compacto", + "Vincular zoom", + "Ajustar", + "Bloquear", + "Desbloquear", + "Mover a capa", + "Ancho", + "Añadir nota", + "Nota de guiado para el router…", + "Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar", + "Rechazar capa", + "Editado", + "Bloqueado", + "Sin corredores ni planos en esta capa", ) internal val es: Array by lazy { arrayOf(*es0(), *es1(), *es2(), *es3(), *es4(), *es5(), *es6(), *es7(), *es8(), *es9(), *es10(), *es11(), *es12(), *es13(), *es14(), *es15(), *es16(), *es17(), *es18(), *es19()) } private fun exactText0(): Array = arrayOf( @@ -22861,9 +22945,25 @@ object Msg { "Toggle Plan mode (off · 1 turn · always)", "Plan panel beside the design: open or close", "1 net", + "Canvas", + "List", + "All layers", + "Side by side", + "Single", + "Link zoom", + "Lock", + "Unlock", + "Move to layer", + "Width", + "Steering note for router…", + "Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove", + "Reject layer", + "Edited", + "Locked", + "No corridors or planes on this layer", ) internal val exactText: Array by lazy { arrayOf(*exactText0(), *exactText1(), *exactText2(), *exactText3(), *exactText4(), *exactText5(), *exactText6(), *exactText7(), *exactText8(), *exactText9(), *exactText10(), *exactText11(), *exactText12(), *exactText13()) } - internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3123, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3691, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3730, 87, 88, 98, 99, 3052, 3729, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3172, 165, 166, 3174, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3133, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2939, 237, 238, 239, 240, 3690, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3144, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3738, 336, 3737, 3740, 340, 3750, 342, 343, 344, 345, 354, 3121, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2942, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2934, 2935, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3151, 457, 458, 459, 460, 461, 2924, 463, 464, 465, 3054, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3159, 3160, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3803, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3735, 734, 735, 736, 737, 3158, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3718, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3154, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3728, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3805, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3124, 964, 965, 966, 967, 968, 969, 3753, 971, 2979, 3036, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3756, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2931, 3005, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3770, 1094, 1095, 1098, 1099, 1100, 3153, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3755, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2933, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1355, 1356, 3009, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 2936, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 3053, 3546, 1407, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 3548, 1444, 1445, 1446, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1464, 1465, 3693, 1467, 1468, 1469, 3705, 3711, 1472, 1473, 1474, 1475, 1476, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1494, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1539, 1540, 1541, 1542, 1544, 1545, 1546, 1547, 1548, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 3012, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 3422, 1636, 1637, 1638, 1639, 3423, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 2945, 1658, 1660, 1662, 1664, 1668, 1672, 1678, 1680, 1681, 1682, 1684, 1685, 1686, 1687, 1688, 1689, 1691, 1693, 1694, 1695, 1696, 1697, 1699, 1700, 3717, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1792, 1793, 2988, 1802, 1804, 1808, 2970, 1810, 1811, 2971, 1813, 1814, 1818, 3035, 1820, 1821, 1822, 1823, 1824, 1825, 1826, 1827, 1828, 1830, 1835, 1837, 1838, 1839, 1840, 1841, 1842, 3050, 1844, 1845, 1848, 1849, 1859, 1860, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1908, 1909, 1911, 1912, 1922, 1924, 1925, 1928, 1929, 1932, 1933, 1934, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1954, 1960, 1961, 1962, 1963, 1967, 3111, 1973, 1974, 1976, 1977, 1978, 1979, 3763, 3764, 1988, 1990, 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2012, 2013, 3096, 3097, 3098, 2021, 3324, 2023, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2040, 2041, 2042, 2043, 2044, 2045, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2078, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 3038, 2096, 2097, 2098, 2100, 2102, 2103, 2104, 2105, 2961, 3086, 3087, 3088, 3089, 3090, 2112, 2113, 2114, 2116, 2963, 2964, 2954, 2953, 2122, 2955, 2124, 2959, 2126, 3322, 2131, 2135, 2137, 2138, 2139, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2989, 2151, 2152, 2153, 2154, 3022, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2167, 3335, 2169, 2170, 2171, 2172, 3004, 2174, 2175, 2176, 2177, 2952, 2179, 3067, 2182, 2186, 2187, 3612, 2189, 2190, 3699, 3700, 2194, 3149, 2197, 3688, 2200, 2201, 2202, 2203, 2204, 3748, 2206, 3119, 2208, 3118, 2210, 2212, 2214, 2215, 2216, 2220, 2223, 2225, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2239, 2240, 2241, 3706, 2243, 2244, 2246, 2996, 2994, 2998, 2252, 2254, 2255, 2261, 2262, 2263, 2264, 3034, 2269, 2270, 2272, 2277, 2278, 2978, 3547, 2941, 2940, 2943, 3063, 3066, 2291, 2292, 2294, 2295, 2297, 2298, 2299, 2300, 2301, 2302, 2303, 2304, 2305, 3767, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2328, 2330, 2331, 2332, 2336, 2337, 2340, 2341, 2348, 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2362, 2363, 2364, 2365, 2366, 2367, 2389, 2390, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2409, 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2423, 2424, 2425, 2426, 2428, 2429, 2430, 2432, 2435, 2436, 2437, 2440, 2441, 2442, 2443, 2444, 2445, 2446, 2447, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2477, 2478, 2479, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2500, 2501, 2502, 2503, 3100, 2505, 2507, 2508, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2519, 2520, 2521, 2522, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2541, 2542, 2543, 2544, 2547, 2548, 2549, 2550, 2551, 2552, 2553, 2554, 2555, 2557, 2558, 2559, 2560, 2561, 2562, 2563, 2564, 2565, 2568, 2570, 2571, 2574, 2575, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2584, 2585, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2599, 2601, 2604, 2606, 3696, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2621, 2622, 2624, 2625, 2626, 2627, 2628, 2629, 2630, 2632, 2633, 2634, 2639, 2640, 2641, 2643, 2644, 2645, 2646, 2648, 2649, 2650, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2660, 3669, 2662, 2663, 2665, 3666, 2667, 2668, 3670, 3667, 2680, 2684, 3677, 3173, 3678, 2688, 3679, 2690, 2692, 3681, 2694, 3682, 2696, 2698, 3686, 3664, 3657, 3665, 2717, 2718, 2720, 2721, 2731, 2732, 2734, 2735, 2736, 2737, 2738, 2739, 2740, 2741, 2742, 2746, 2749, 2752, 2754, 2756, 2762, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 3344, 2776, 2777, 2778, 2779, 2780, 2782, 2784, 2785, 3376, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2804, 2805, 2806, 2807, 2810, 2811, 2813, 2814, 2815, 2816, 2968, 2818, 2820, 2821, 2823, 2824, 2825, 2826, 2827, 2829, 2830, 2834, 2837, 2838, 2839, 2841, 2842, 2843, 2845, 2846, 2847, 2848, 2850, 2851, 2854, 2857, 2858, 2859, 2860, 2861, 2863, 2865, 2866, 2868, 2869, 2870, 2871, 2872, 2873, 2874, 2875, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2891, 2892, 2893, 2894, 2895, 2896, 2902, 2903, 2904, 2906, 2907, 2908, 2912, 2913, 2914, 2915, 2916, 2920, 2921, 2925, 2926, 2927, 2928, 2929, 2930, 2932, 2937, 2938, 2944, 2949, 2951, 2956, 2957, 2958, 2960, 2962, 2965, 2966, 2967, 2969, 2973, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2990, 2991, 2992, 2993, 2997, 2999, 3000, 3001, 3002, 3006, 3007, 3011, 3013, 3014, 3015, 3017, 3018, 3019, 3020, 3021, 3024, 3025, 3026, 3027, 3028, 3029, 3030, 3031, 3032, 3039, 3040, 3041, 3042, 3047, 3048, 3049, 3051, 3055, 3056, 3057, 3058, 3059, 3062, 3064, 3065, 3068, 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3078, 3080, 3081, 3082, 3083, 3084, 3085, 3091, 3092, 3093, 3094, 3095, 3099, 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3109, 3110, 3113, 3115, 3116, 3117, 3120, 3125, 3126, 3127, 3129, 3132, 3134, 3135, 3137, 3138, 3139, 3141, 3142, 3143, 3145, 3146, 3147, 3148, 3152, 3157, 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3170, 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3182, 3183, 3184, 3185, 3186, 3187, 3190, 3191, 3194, 3195, 3196, 3197, 3198, 3199, 3200, 3201, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3217, 3218, 3220, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3231, 3232, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3244, 3245, 3246, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3288, 3289, 3290, 3291, 3292, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3318, 3319, 3323, 3325, 3326, 3327, 3329, 3330, 3331, 3334, 3336, 3337, 3338, 3339, 3340, 3343, 3345, 3348, 3350, 3351, 3356, 3357, 3358, 3359, 3362, 3369, 3370, 3371, 3372, 3373, 3374, 3377, 3378, 3379, 3380, 3383, 3384, 3385, 3386, 3387, 3388, 3389, 3390, 3391, 3392, 3394, 3395, 3396, 3397, 3398, 3399, 3401, 3402, 3404, 3405, 3406, 3407, 3408, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3424, 3427, 3430, 3431, 3432, 3433, 3434, 3435, 3436, 3437, 3438, 3439, 3440, 3441, 3442, 3443, 3444, 3445, 3446, 3447, 3448, 3450, 3451, 3452, 3453, 3454, 3455, 3456, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3467, 3468, 3472, 3478, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3497, 3498, 3499, 3500, 3501, 3505, 3506, 3510, 3511, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3524, 3525, 3527, 3528, 3529, 3530, 3533, 3534, 3535, 3536, 3537, 3549, 3550, 3551, 3552, 3553, 3554, 3555, 3556, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3566, 3568, 3569, 3570, 3574, 3575, 3576, 3577, 3583, 3584, 3585, 3586, 3590, 3592, 3593, 3594, 3596, 3599, 3600, 3604, 3611, 3613, 3616, 3618, 3619, 3620, 3621, 3622, 3623, 3625, 3626, 3627, 3628, 3629, 3630, 3631, 3632, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, 3646, 3647, 3648, 3649, 3650, 3651, 3652, 3653, 3654, 3655, 3656, 3674, 3689, 3692, 3694, 3695, 3697, 3701, 3703, 3707, 3716, 3719, 3720, 3721, 3722, 3723, 3724, 3726, 3732, 3733, 3736, 3739, 3741, 3742, 3743, 3744, 3745, 3746, 3749, 3752, 3754, 3758, 3759, 3760, 3761, 3762, 3765, 3766, 3768, 3769, 3771, 3772, 3773, 3774, 3775, 3776, 3777, 3778, 3780, 3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3800, 3802, 3804, 3813, 3814, 3816, 3817, 3826, 3832, 3838, 3847, 3849, 3850, 3851, 3852, 3855, 3856, 3858, 3864, 3868, 3872, 3877, 3878, 3880, 3881, 3882, 3884, 3885, 3886, 3891, 3892, 3893, 3894, 3895, 3896, 3897, 3898, 3899, 3902, 3903, 3904, 3949, 3950, 3955, 3957, 3958, 3960, 3966, 3969, 3984, 3985, 3986, 3987, 3988, 3989, 3991, 3992, 3994, 3995, 3997, 3999, 4000, 4013, 4016, 4017, 4019, 4020, 4024, 4029, 4032, 4033, 4035, 4036, 4042, 4044, 4045, 4048, 4050, 4055, 4056, 4057, 4062, 4073, 4096, 4112, 4120, 4129, 4130, 4134, 4139, 4155, 4156, 4157, 4158, 4160, 4162, 4163, 4165, 4168, 4172, 4175, 4178, 4179, 4180, 4181, 4185, 4186, 4187, 4188, 4191, 4192, 4193, 4194, 4195, 4196, 4197, 4198, 4199, 4200, 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, 4212, 4213, 4214, 4222, 4225, 4226, 4232, 4237, 4238, 4239, 4240, 4244, 4248, 4250, 4251, 4252, 4253, 4254, 4255, 4256, 4257, 4259, 4260, 4261, 4262, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4280, 4292, 4293, 4295, 4296, 4297, 4298, 4302, 4303, 4304, 4305, 4306, 4307, 4309, 4310, 4311, 4317, 4318, 4319, 4320, 4321, 4322, 4326, 4330, 4331, 4333, 4334, 4335, 4336, 4337, 4339, 4349, 4351, 4356, 4357, 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365, 4366, 4367, 4368, 4369, 4370, 4371, 4373, 4374, 4375, 4376, 4377, 4378, 4379, 4384, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4401, 4402, 4403, 4404, 4405, 4406, 4407, 4409, 4410, 4411, 4413, 4414, 4415, 4416, 4419, 4420, 4421, 4423, 4424, 4425, 4427, 4428, 4429, 4430, 4431, 4432, 4434, 4436, 4439, 4440, 4441, 4442, 4444, 4445, 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453, 4454, 4458, 4460, 4461, 4462, 4463, 4464, 4468, 4469, 4473, 4474, 4475, 4477, 4479, 4480, 4481, 4482, 4483, 4484, 4485, 4487, 4488, 4489, 4490, 4491, 4492, 4493, 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4517, 4518, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4539, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4547, 4552, 4553, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4565, 4566, 4567, 4568, 4569, 4571, 4572, 4573, 4574, 4583, 4584, 4585, 4586, 4587, 4588, 4590, 4593, 4594, 4595, 4597, 4598, 4599, 4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4703, 4704, 4705, 4711, 4724, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4745, 4746, 4747, 4748, 4749, 4751, 4752, 4753, 4754, 4755, 4756, 4757, 4760, 4761, 4763, 4764, 4765, 4768, 4769, 4770, 4771, 4772, 4773, 4774, 4775, 4776, 4777, 4778, 4779, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4789, 4790, 4791, 4792, 4793, 4794, 4796, 4797, 4798, 4799, 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4824, 4825, 4826, 4827, 4829, 4830, 4831, 4833) } + internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3123, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3691, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3730, 87, 88, 98, 99, 3052, 3729, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3172, 165, 166, 3174, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3133, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2939, 237, 238, 239, 240, 3690, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3144, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3738, 336, 3737, 3740, 340, 3750, 342, 343, 344, 345, 354, 3121, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2942, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2934, 2935, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3151, 457, 458, 459, 460, 461, 2924, 463, 464, 465, 3054, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3159, 3160, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3803, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3735, 734, 735, 736, 737, 3158, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3718, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3154, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3728, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3805, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3124, 964, 965, 966, 967, 968, 969, 3753, 971, 2979, 3036, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3756, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2931, 3005, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3770, 1094, 1095, 1098, 1099, 1100, 3153, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3755, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2933, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1355, 1356, 3009, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 2936, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 3053, 3546, 1407, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 3548, 1444, 1445, 1446, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1464, 1465, 3693, 1467, 1468, 1469, 3705, 3711, 1472, 1473, 1474, 1475, 1476, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1494, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1539, 1540, 1541, 1542, 1544, 1545, 1546, 1547, 1548, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 3012, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 3422, 1636, 1637, 1638, 1639, 3423, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 2945, 1658, 1660, 1662, 1664, 1668, 1672, 1678, 1680, 1681, 1682, 1684, 1685, 1686, 1687, 1688, 1689, 1691, 1693, 1694, 1695, 1696, 1697, 1699, 1700, 3717, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1792, 1793, 2988, 1802, 1804, 1808, 2970, 1810, 1811, 2971, 1813, 1814, 1818, 3035, 1820, 1821, 1822, 1823, 1824, 1825, 1826, 1827, 1828, 1830, 1835, 1837, 1838, 1839, 1840, 1841, 1842, 3050, 1844, 1845, 1848, 1849, 1859, 1860, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1908, 1909, 1911, 1912, 1922, 1924, 1925, 1928, 1929, 1932, 1933, 1934, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1954, 1960, 1961, 1962, 1963, 1967, 3111, 1973, 1974, 1976, 1977, 1978, 1979, 3763, 3764, 1988, 1990, 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2012, 2013, 3096, 3097, 3098, 2021, 3324, 2023, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2040, 2041, 2042, 2043, 2044, 2045, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2078, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 3038, 2096, 2097, 2098, 2100, 2102, 2103, 2104, 2105, 2961, 3086, 3087, 3088, 3089, 3090, 2112, 2113, 2114, 2116, 2963, 2964, 2954, 2953, 2122, 2955, 2124, 2959, 2126, 3322, 2131, 2135, 2137, 2138, 2139, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2989, 2151, 2152, 2153, 2154, 3022, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2167, 3335, 2169, 2170, 2171, 2172, 3004, 2174, 2175, 2176, 2177, 2952, 2179, 3067, 2182, 2186, 2187, 3612, 2189, 2190, 3699, 3700, 2194, 3149, 2197, 3688, 2200, 2201, 2202, 2203, 2204, 3748, 2206, 3119, 2208, 3118, 2210, 2212, 2214, 2215, 2216, 2220, 2223, 2225, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2239, 2240, 2241, 3706, 2243, 2244, 2246, 2996, 2994, 2998, 2252, 2254, 2255, 2261, 2262, 2263, 2264, 3034, 2269, 2270, 2272, 2277, 2278, 2978, 3547, 2941, 2940, 2943, 3063, 3066, 2291, 2292, 2294, 2295, 2297, 2298, 2299, 2300, 2301, 2302, 2303, 2304, 2305, 3767, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2328, 2330, 2331, 2332, 2336, 2337, 2340, 2341, 2348, 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2362, 2363, 2364, 2365, 2366, 2367, 2389, 2390, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2409, 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2423, 2424, 2425, 2426, 2428, 2429, 2430, 2432, 2435, 2436, 2437, 2440, 2441, 2442, 2443, 2444, 2445, 2446, 2447, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2477, 2478, 2479, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2500, 2501, 2502, 2503, 3100, 2505, 2507, 2508, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2519, 2520, 2521, 2522, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2541, 2542, 2543, 2544, 2547, 2548, 2549, 2550, 2551, 2552, 2553, 2554, 2555, 2557, 2558, 2559, 2560, 2561, 2562, 2563, 2564, 2565, 2568, 2570, 2571, 2574, 2575, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2584, 2585, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2599, 2601, 2604, 2606, 3696, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2621, 2622, 2624, 2625, 2626, 2627, 2628, 2629, 2630, 2632, 2633, 2634, 2639, 2640, 2641, 2643, 2644, 2645, 2646, 2648, 2649, 2650, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2660, 3669, 2662, 2663, 2665, 3666, 2667, 2668, 3670, 3667, 2680, 2684, 3677, 3173, 3678, 2688, 3679, 2690, 2692, 3681, 2694, 3682, 2696, 2698, 3686, 3664, 3657, 3665, 2717, 2718, 2720, 2721, 2731, 2732, 2734, 2735, 2736, 2737, 2738, 2739, 2740, 2741, 2742, 2746, 2749, 2752, 2754, 2756, 2762, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 3344, 2776, 2777, 2778, 2779, 2780, 2782, 2784, 2785, 3376, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2804, 2805, 2806, 2807, 2810, 2811, 2813, 2814, 2815, 2816, 2968, 2818, 2820, 2821, 2823, 2824, 2825, 2826, 2827, 2829, 2830, 2834, 2837, 2838, 2839, 2841, 2842, 2843, 2845, 2846, 2847, 2848, 2850, 2851, 2854, 2857, 2858, 2859, 2860, 2861, 2863, 2865, 2866, 2868, 2869, 2870, 2871, 2872, 2873, 2874, 2875, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2891, 2892, 2893, 2894, 2895, 2896, 2902, 2903, 2904, 2906, 2907, 2908, 2912, 2913, 2914, 2915, 2916, 2920, 2921, 2925, 2926, 2927, 2928, 2929, 2930, 2932, 2937, 2938, 2944, 2949, 2951, 2956, 2957, 2958, 2960, 2962, 2965, 2966, 2967, 2969, 2973, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2990, 2991, 2992, 2993, 2997, 2999, 3000, 3001, 3002, 3006, 3007, 3011, 3013, 3014, 3015, 3017, 3018, 3019, 3020, 3021, 3024, 3025, 3026, 3027, 3028, 3029, 3030, 3031, 3032, 3039, 3040, 3041, 3042, 3047, 3048, 3049, 3051, 3055, 3056, 3057, 3058, 3059, 3062, 3064, 3065, 3068, 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3078, 3080, 3081, 3082, 3083, 3084, 3085, 3091, 3092, 3093, 3094, 3095, 3099, 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3109, 3110, 3113, 3115, 3116, 3117, 3120, 3125, 3126, 3127, 3129, 3132, 3134, 3135, 3137, 3138, 3139, 3141, 3142, 3143, 3145, 3146, 3147, 3148, 3152, 3157, 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3170, 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3182, 3183, 3184, 3185, 3186, 3187, 3190, 3191, 3194, 3195, 3196, 3197, 3198, 3199, 3200, 3201, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3217, 3218, 3220, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3231, 3232, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3244, 3245, 3246, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3288, 3289, 3290, 3291, 3292, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3318, 3319, 3323, 3325, 3326, 3327, 3329, 3330, 3331, 3334, 3336, 3337, 3338, 3339, 3340, 3343, 3345, 3348, 3350, 3351, 3356, 3357, 3358, 3359, 3362, 3369, 3370, 3371, 3372, 3373, 3374, 3377, 3378, 3379, 3380, 3383, 3384, 3385, 3386, 3387, 3388, 3389, 3390, 3391, 3392, 3394, 3395, 3396, 3397, 3398, 3399, 3401, 3402, 3404, 3405, 3406, 3407, 3408, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3424, 3427, 3430, 3431, 3432, 3433, 3434, 3435, 3436, 3437, 3438, 3439, 3440, 3441, 3442, 3443, 3444, 3445, 3446, 3447, 3448, 3450, 3451, 3452, 3453, 3454, 3455, 3456, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3467, 3468, 3472, 3478, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3497, 3498, 3499, 3500, 3501, 3505, 3506, 3510, 3511, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3524, 3525, 3527, 3528, 3529, 3530, 3533, 3534, 3535, 3536, 3537, 3549, 3550, 3551, 3552, 3553, 3554, 3555, 3556, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3566, 3568, 3569, 3570, 3574, 3575, 3576, 3577, 3583, 3584, 3585, 3586, 3590, 3592, 3593, 3594, 3596, 3599, 3600, 3604, 3611, 3613, 3616, 3618, 3619, 3620, 3621, 3622, 3623, 3625, 3626, 3627, 3628, 3629, 3630, 3631, 3632, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, 3646, 3647, 3648, 3649, 3650, 3651, 3652, 3653, 3654, 3655, 3656, 3674, 3689, 3692, 3694, 3695, 3697, 3701, 3703, 3707, 3716, 3719, 3720, 3721, 3722, 3723, 3724, 3726, 3732, 3733, 3736, 3739, 3741, 3742, 3743, 3744, 3745, 3746, 3749, 3752, 3754, 3758, 3759, 3760, 3761, 3762, 3765, 3766, 3768, 3769, 3771, 3772, 3773, 3774, 3775, 3776, 3777, 3778, 3780, 3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3800, 3802, 3804, 3813, 3814, 3816, 3817, 3826, 3832, 3838, 3847, 3849, 3850, 3851, 3852, 3855, 3856, 3858, 3864, 3868, 3872, 3877, 3878, 3880, 3881, 3882, 3884, 3885, 3886, 3891, 3892, 3893, 3894, 3895, 3896, 3897, 3898, 3899, 3902, 3903, 3904, 3949, 3950, 3955, 3957, 3958, 3960, 3966, 3969, 3984, 3985, 3986, 3987, 3988, 3989, 3991, 3992, 3994, 3995, 3997, 3999, 4000, 4013, 4016, 4017, 4019, 4020, 4024, 4029, 4032, 4033, 4035, 4036, 4042, 4044, 4045, 4048, 4050, 4055, 4056, 4057, 4062, 4073, 4096, 4112, 4120, 4129, 4130, 4134, 4139, 4155, 4156, 4157, 4158, 4160, 4162, 4163, 4165, 4168, 4172, 4175, 4178, 4179, 4180, 4181, 4185, 4186, 4187, 4188, 4191, 4192, 4193, 4194, 4195, 4196, 4197, 4198, 4199, 4200, 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, 4212, 4213, 4214, 4222, 4225, 4226, 4232, 4237, 4238, 4239, 4240, 4244, 4248, 4250, 4251, 4252, 4253, 4254, 4255, 4256, 4257, 4259, 4260, 4261, 4262, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4280, 4292, 4293, 4295, 4296, 4297, 4298, 4302, 4303, 4304, 4305, 4306, 4307, 4309, 4310, 4311, 4317, 4318, 4319, 4320, 4321, 4322, 4326, 4330, 4331, 4333, 4334, 4335, 4336, 4337, 4339, 4349, 4351, 4356, 4357, 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365, 4366, 4367, 4368, 4369, 4370, 4371, 4373, 4374, 4375, 4376, 4377, 4378, 4379, 4384, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4401, 4402, 4403, 4404, 4405, 4406, 4407, 4409, 4410, 4411, 4413, 4414, 4415, 4416, 4419, 4420, 4421, 4423, 4424, 4425, 4427, 4428, 4429, 4430, 4431, 4432, 4434, 4436, 4439, 4440, 4441, 4442, 4444, 4445, 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453, 4454, 4458, 4460, 4461, 4462, 4463, 4464, 4468, 4469, 4473, 4474, 4475, 4477, 4479, 4480, 4481, 4482, 4483, 4484, 4485, 4487, 4488, 4489, 4490, 4491, 4492, 4493, 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4517, 4518, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4539, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4547, 4552, 4553, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4565, 4566, 4567, 4568, 4569, 4571, 4572, 4573, 4574, 4583, 4584, 4585, 4586, 4587, 4588, 4590, 4593, 4594, 4595, 4597, 4598, 4599, 4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4703, 4704, 4705, 4711, 4724, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4745, 4746, 4747, 4748, 4749, 4751, 4752, 4753, 4754, 4755, 4756, 4757, 4760, 4761, 4763, 4764, 4765, 4768, 4769, 4770, 4771, 4772, 4773, 4774, 4775, 4776, 4777, 4778, 4779, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4789, 4790, 4791, 4792, 4793, 4794, 4796, 4797, 4798, 4799, 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4824, 4825, 4826, 4827, 4829, 4830, 4831, 4833, 4835, 4837, 4838, 4839, 4840, 4843, 4845, 4846, 4847, 4848, 4850, 4851, 4852, 4853, 4854, 4855) } internal val templates: IntArray by lazy { intArrayOf(2329, 2808, 2620, 2619, 2618, 2840, 2862, 3342, 2583, 418, 2753, 2751, 2647, 2338, 2344, 2755, 2852, 2567, 2566, 285, 2296, 2757, 2864, 3192, 4144, 2506, 2556, 2016, 2334, 3676, 2081, 2683, 2339, 3193, 1336, 4164, 4184, 3675, 2524, 2681, 1833, 4159, 2092, 2130, 2136, 4513, 283, 2082, 4455, 3354, 3375, 2039, 2307, 3672, 452, 2715, 2747, 2748, 3355, 3671, 2716, 3603, 609, 1677, 3680, 1834, 2691, 3683, 2697, 3346, 616, 617, 2733, 3044, 3658, 1625, 2750, 3602, 303, 614, 69, 711, 621, 2306, 4182, 1121, 2448, 3425, 3798, 1242, 2165, 2535, 3347, 2128, 3687, 714, 1729, 1930, 2703, 2712, 2923, 4189, 3349, 3361, 136, 594, 596, 2523, 2678, 1831, 4177, 2995, 610, 2249, 2546, 3835, 1302, 4176, 3471, 3608, 3609, 158, 2046, 2048, 2083, 2803, 4312, 2134, 2333, 2476, 3597, 214, 284, 1276, 1980, 4744, 3466, 3475, 3476, 67, 83, 218, 619, 4549, 3495, 4271, 3320, 3685, 726, 1023, 2347, 2439, 2701, 4314, 89, 2346, 2361, 2876, 624, 1623, 1920, 2790, 4443, 3368, 1543, 2067, 2253, 2537, 4495, 3363, 3429, 3479, 650, 1854, 3890, 3128, 3470, 3516, 3580, 3799, 1317, 1832, 2011, 2385, 2672, 3818, 4514, 3382, 3428, 1807, 1829, 3317, 593, 1292, 1346, 1919, 3457, 3659, 221, 1667, 2704, 2901, 3046, 3114, 3403, 258, 591, 1026, 1931, 1955, 4097, 3400, 3526, 655, 1342, 1683, 2017, 3122, 3321, 3582, 3601, 710, 1283, 1353, 1624, 1698, 1861, 2335, 2438, 2536, 3905, 4183, 4380, 3381, 3449, 3595, 649, 699, 1044, 2572, 3140, 3259, 3662, 108, 184, 606, 721, 1081, 1935, 2015, 2077, 2132, 2371, 2452, 2708, 2744, 2788, 3910, 4426, 4767, 3341, 3412, 3573, 160, 623, 701, 1332, 1333, 1345, 1491, 1626, 2129, 2133, 2226, 2370, 2598, 4152, 4456, 3077, 3169, 3216, 3294, 3508, 3663, 3673, 703, 1183, 1538, 1863, 2221, 2224, 2451, 2709, 2729, 2730, 2898, 2899, 3920, 3940, 4173, 4417, 4750, 4766, 3581, 3598, 3704, 1463, 1550, 1669, 1921, 2391, 2403, 2728, 4116, 4174, 4457, 4548, 3043, 3045, 3060, 3578, 3591, 3757, 723, 1024, 1798, 2101, 2166, 2381, 2724, 2725, 3925, 4171, 4247, 4258, 3247, 3367, 91, 93, 595, 715, 1027, 1350, 1986, 2293, 2386, 2671, 2723, 2727, 3887, 4496, 4828, 2974, 2975, 3477, 3541, 3684, 94, 1251, 1259, 1490, 1549, 1846, 2149, 2181, 2431, 2449, 2699, 3827, 3828, 4170, 4323, 4386, 4832, 3293, 3332, 3333, 3411, 3567, 299, 599, 618, 700, 1109, 1117, 1175, 1489, 1592, 1914, 2093, 2099, 2117, 2184, 2401, 2406, 2408, 2631, 2664, 2722, 2900, 2917, 2918, 4141, 4167, 4284, 2976, 3130, 3507, 3540, 3709, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1441, 1495, 1671, 1852, 1872, 1892, 1927, 1957, 2038, 2276, 2384, 2450, 2905, 3854, 3906, 4124, 4497, 4515, 4516, 4715, 3037, 3393, 3588, 3589, 92, 96, 269, 603, 648, 712, 980, 1331, 1673, 1853, 1910, 2080, 2379, 2405, 2407, 2410, 2499, 2637, 2673, 2855, 2867, 4215, 4499, 4727, 2950, 3215, 3248, 3328, 3426, 3545, 3579, 208, 277, 316, 329, 330, 1287, 1492, 1493, 1915, 1985, 2010, 2079, 2183, 2211, 2259, 2373, 2388, 2400, 2674, 2677, 2758, 2759, 3825, 4512, 4710, 2972, 3360, 3364, 3413, 3469, 3624, 3661, 3714, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1674, 1675, 1850, 1923, 1926, 1984, 1987, 2115, 2150, 2198, 2372, 2380, 2600, 2706, 2745, 2822, 3822, 3823, 3883, 4140, 4713, 4725, 4726, 3410, 3532, 3539, 3544, 3606, 3614, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1488, 1676, 1794, 1855, 1975, 2185, 2191, 2343, 2369, 2375, 2402, 2534, 2635, 3888, 4113, 4166, 4229, 4315, 4385, 4596, 4714, 3023, 3108, 3473, 3474, 3572, 3605, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1679, 1709, 1795, 1800, 1815, 1851, 2014, 2047, 2238, 2256, 2265, 2368, 2422, 2434, 2726, 4151, 3003, 3353, 3538, 3607, 3615, 3660, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1408, 1856, 1971, 1981, 2374, 2383, 2427, 2705, 2743, 2897, 2911, 3860, 4758, 4759, 4762, 2977, 3008, 3061, 3131, 3189, 3202, 3203, 3366, 3514, 3515, 3587, 3610, 3617, 3668, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1712, 1796, 1797, 1805, 1916, 1917, 1918, 2007, 2217, 2219, 2245, 2257, 2258, 2280, 2342, 2376, 2377, 2433, 2539, 2540, 2623, 2638, 2670, 2675, 2676, 2713, 2760, 2761, 3806, 3824, 3870, 3924, 4169, 4263, 4281, 4313, 4383, 4418, 4470, 4494, 4555, 4795, 3010, 3112, 3136, 3150, 3171, 3352, 3365, 3509, 3513, 3543, 3571, 3702, 3712, 3713, 3725, 3727, 3734, 5, 8, 82, 185, 188, 192, 257, 276, 325, 326, 348, 351, 356, 598, 620, 658, 696, 705, 856, 985, 1048, 1122, 1148, 1149, 1168, 1179, 1239, 1354, 1462, 1615, 1659, 1670, 1816, 1847, 1913, 1959, 1972, 1993, 2213, 2218, 2268, 2274, 2275, 2282, 2387, 2573, 2609, 2783, 3871, 3879, 3909, 3926, 4093, 4128, 4142, 4190, 4230, 4282, 4308, 4471, 4498, 3033, 3079, 3155, 3156, 3161, 3219, 3503, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1352, 1559, 1799, 1891, 1953, 1956, 2266, 2279, 2345, 2392, 2538, 2586, 2828, 3829, 3876, 3942, 4109, 4467, 4554, 3409, 3502, 3504, 3512, 3531, 3542, 3710, 3731, 3751, 95, 196, 203, 204, 205, 242, 243, 346, 581, 586, 601, 615, 622, 626, 627, 691, 716, 725, 983, 986, 1085, 1089, 1161, 1174, 1204, 1349, 1442, 1477, 1654, 1655, 1657, 1692, 1817, 1857, 2196, 2271, 2281, 2382, 2404, 2412, 2919, 4095, 4125, 4126, 4216, 4241, 4279, 4381, 4437, 4478, 4834) } internal val argNames: Map> by lazy { mapOf(5 to arrayOf("n"), 6 to arrayOf("n"), 7 to arrayOf("who"), 8 to arrayOf("title"), 65 to arrayOf("state"), 67 to arrayOf("listen"), 69 to arrayOf("listen"), 82 to arrayOf("version"), 83 to arrayOf("count", "plural"), 89 to arrayOf("size", "limit"), 90 to arrayOf("name"), 91 to arrayOf("dir"), 92 to arrayOf("dir"), 93 to arrayOf("name"), 94 to arrayOf("name"), 95 to arrayOf("path"), 96 to arrayOf("path"), 97 to arrayOf("name"), 108 to arrayOf("first"), 110 to arrayOf("n"), 136 to arrayOf("count", "plural"), 154 to arrayOf("tool"), 158 to arrayOf("n"), 160 to arrayOf("name"), 184 to arrayOf("pid", "cmd"), 185 to arrayOf("title", "ago"), 186 to arrayOf("name", "who", "n"), 188 to arrayOf("line"), 190 to arrayOf("n"), 191 to arrayOf("n"), 192 to arrayOf("n"), 196 to arrayOf("name"), 203 to arrayOf("when"), 204 to arrayOf("text", "when"), 205 to arrayOf("when"), 207 to arrayOf("count", "plural"), 208 to arrayOf("count", "plural"), 210 to arrayOf("took", "ago"), 211 to arrayOf("ago"), 212 to arrayOf("kind"), 214 to arrayOf("kind", "code", "why"), 218 to arrayOf("clock"), 221 to arrayOf("build"), 242 to arrayOf("step"), 243 to arrayOf("turn"), 244 to arrayOf("branch"), 257 to arrayOf("step", "total"), 258 to arrayOf("step", "total"), 259 to arrayOf("when"), 261 to arrayOf("tool"), 268 to arrayOf("count", "plural"), 269 to arrayOf("count", "total"), 274 to arrayOf("old", "new"), 276 to arrayOf("version"), 277 to arrayOf("count"), 278 to arrayOf("tag"), 283 to arrayOf("version"), 284 to arrayOf("old", "version"), 285 to arrayOf("version"), 288 to arrayOf("version"), 299 to arrayOf("project", "location"), 303 to arrayOf("account"), 304 to arrayOf("account"), 316 to arrayOf("n"), 318 to arrayOf("n"), 320 to arrayOf("minute"), 321 to arrayOf("time"), 322 to arrayOf("time"), 323 to arrayOf("clock"), 324 to arrayOf("clock", "took"), 325 to arrayOf("clock"), 326 to arrayOf("clock", "took"), 327 to arrayOf("clock"), 328 to arrayOf("clock", "took"), 329 to arrayOf("clock"), 330 to arrayOf("clock", "took"), 331 to arrayOf("clock"), 346 to arrayOf("target"), 347 to arrayOf("target"), 348 to arrayOf("target"), 349 to arrayOf("target"), 350 to arrayOf("target"), 351 to arrayOf("target"), 352 to arrayOf("target"), 353 to arrayOf("target"), 356 to arrayOf("name"), 375 to arrayOf("t"), 418 to arrayOf("minutes", "plural"), 452 to arrayOf("path"), 579 to arrayOf("count"), 580 to arrayOf("count"), 581 to arrayOf("title"), 582 to arrayOf("path"), 583 to arrayOf("path", "error"), 584 to arrayOf("first", "last", "count"), 585 to arrayOf("task", "step"), 586 to arrayOf("count"), 587 to arrayOf("path"), 588 to arrayOf("count", "plural"), 589 to arrayOf("label"), 590 to arrayOf("provider"), 591 to arrayOf("version"), 593 to arrayOf("key"), 594 to arrayOf("device"), 595 to arrayOf("kind", "device"), 596 to arrayOf("status"), 597 to arrayOf("kind", "title"), 598 to arrayOf("layer"), 599 to arrayOf("error"), 600 to arrayOf("page"), 601 to arrayOf("page", "kind", "total"), 602 to arrayOf("reason"), 603 to arrayOf("tag"), 604 to arrayOf("tag"), 605 to arrayOf("title"), 606 to arrayOf("title"), 607 to arrayOf("text", "time"), 608 to arrayOf("kind", "device"), 609 to arrayOf("device"), 610 to arrayOf("device"), 611 to arrayOf("word"), 612 to arrayOf("word", "kind", "count"), 613 to arrayOf("error"), 614 to arrayOf("count"), 615 to arrayOf("time", "relative", "rel", "zoned", "zone"), 616 to arrayOf("zone"), 617 to arrayOf("zone"), 618 to arrayOf("id", "state", "count", "age"), 619 to arrayOf("id"), 620 to arrayOf("name"), 621 to arrayOf("name"), 622 to arrayOf("clock", "count", "plural"), 623 to arrayOf("name"), 624 to arrayOf("name"), 625 to arrayOf("name"), 626 to arrayOf("count"), 627 to arrayOf("count"), 631 to arrayOf("name", "state"), 632 to arrayOf("author", "place", "state"), 633 to arrayOf("title", "state"), 648 to arrayOf("error"), 649 to arrayOf("error"), 650 to arrayOf("host"), 655 to arrayOf("email"), 658 to arrayOf("version"), 660 to arrayOf("first", "last", "count"), 661 to arrayOf("n"), 662 to arrayOf("n"), 691 to arrayOf("ref"), 696 to arrayOf("name"), 697 to arrayOf("name"), 699 to arrayOf("name"), 700 to arrayOf("name"), 701 to arrayOf("action"), 702 to arrayOf("label"), 703 to arrayOf("count", "plural"), 705 to arrayOf("path"), 706 to arrayOf("word", "kind", "count"), 707 to arrayOf("name"), 708 to arrayOf("name"), 709 to arrayOf("name"), 710 to arrayOf("name"), 711 to arrayOf("url"), 712 to arrayOf("count"), 713 to arrayOf("count"), 714 to arrayOf("device"), 715 to arrayOf("device"), 716 to arrayOf("count"), 717 to arrayOf("label"), 718 to arrayOf("label"), 719 to arrayOf("label"), 720 to arrayOf("title"), 721 to arrayOf("title"), 722 to arrayOf("state"), 723 to arrayOf("open", "kind"), 725 to arrayOf("count"), 726 to arrayOf("email"), 727 to arrayOf("email"), 851 to arrayOf("at", "count"), 855 to arrayOf("name"), 856 to arrayOf("name"), 905 to arrayOf("name"), 906 to arrayOf("name"), 977 to arrayOf("count"), 980 to arrayOf("name"), 981 to arrayOf("name", "count"), 982 to arrayOf("label", "n"), 983 to arrayOf("action"), 984 to arrayOf("count", "plural"), 985 to arrayOf("count"), 986 to arrayOf("waiting", "busy", "done"), 990 to arrayOf("count", "plural"), 1023 to arrayOf("name"), 1024 to arrayOf("name"), 1026 to arrayOf("seconds", "long"), 1027 to arrayOf("size", "triangles", "delayed", "waited", "built"), 1028 to arrayOf("size", "delayed", "waited"), 1044 to arrayOf("name"), 1047 to arrayOf("name"), 1048 to arrayOf("count"), 1075 to arrayOf("state"), 1076 to arrayOf("bytes"), 1077 to arrayOf("count"), 1078 to arrayOf("when"), 1079 to arrayOf("state", "name"), 1080 to arrayOf("name", "state"), 1081 to arrayOf("reason", "code"), 1084 to arrayOf("kind", "code"), 1085 to arrayOf("number"), 1089 to arrayOf("x", "y"), 1096 to arrayOf("state"), 1097 to arrayOf("label", "example"), 1109 to arrayOf("text"), 1117 to arrayOf("error"), 1118 to arrayOf("kind", "count"), 1121 to arrayOf("name"), 1122 to arrayOf("n"), 1147 to arrayOf("ago"), 1148 to arrayOf("name"), 1149 to arrayOf("kind", "place", "hub"), 1159 to arrayOf("label"), 1160 to arrayOf("word"), 1161 to arrayOf("count"), 1164 to arrayOf("hub"), 1166 to arrayOf("count"), 1167 to arrayOf("state"), 1168 to arrayOf("label"), 1169 to arrayOf("label"), 1174 to arrayOf("state", "text"), 1175 to arrayOf("text"), 1177 to arrayOf("question"), 1179 to arrayOf("label"), 1183 to arrayOf("title"), 1204 to arrayOf("count"), 1205 to arrayOf("name", "counts"), 1219 to arrayOf("n"), 1221 to arrayOf("mode"), 1238 to arrayOf("first", "last", "total"), 1239 to arrayOf("count"), 1242 to arrayOf("n"), 1243 to arrayOf("who", "name"), 1251 to arrayOf("name"), 1252 to arrayOf("when"), 1259 to arrayOf("why"), 1276 to arrayOf("name"), 1283 to arrayOf("kind"), 1284 to arrayOf("title"), 1285 to arrayOf("title"), 1286 to arrayOf("title"), 1287 to arrayOf("title"), 1292 to arrayOf("name"), 1302 to arrayOf("heard"), 1303 to arrayOf("out", "heard"), 1304 to arrayOf("heard"), 1312 to arrayOf("name", "mb"), 1314 to arrayOf("name"), 1317 to arrayOf("platform"), 1321 to arrayOf("heard", "out", "yes"), 1331 to arrayOf("name", "done", "total", "percent"), 1332 to arrayOf("name", "done"), 1333 to arrayOf("name"), 1334 to arrayOf("error"), 1336 to arrayOf("mb"), 1342 to arrayOf("mb"), 1345 to arrayOf("n"), 1346 to arrayOf("n"), 1349 to arrayOf("n"), 1350 to arrayOf("pct"), 1351 to arrayOf("px"), 1352 to arrayOf("key"), 1353 to arrayOf("key"), 1354 to arrayOf("why"), 1408 to arrayOf("n"), 1441 to arrayOf("title"), 1442 to arrayOf("note"), 1462 to arrayOf("title"), 1463 to arrayOf("more"), 1477 to arrayOf("bots"), 1488 to arrayOf("name"), 1489 to arrayOf("name", "time"), 1490 to arrayOf("name", "n"), 1491 to arrayOf("name", "time", "n"), 1492 to arrayOf("to"), 1493 to arrayOf("to", "step"), 1495 to arrayOf("note"), 1538 to arrayOf("why"), 1543 to arrayOf("e"), 1549 to arrayOf("max"), 1550 to arrayOf("secs", "max", "mib"), 1559 to arrayOf("path"), 1592 to arrayOf("secs"), 1615 to arrayOf("pct", "scope"), 1623 to arrayOf("n"), 1624 to arrayOf("n"), 1625 to arrayOf("n"), 1626 to arrayOf("n"), 1654 to arrayOf("d", "h"), 1655 to arrayOf("h", "m"), 1656 to arrayOf("m"), 1657 to arrayOf("window", "pct"), 1659 to arrayOf("when"), 1661 to arrayOf("label", "e"), 1663 to arrayOf("from", "to", "total"), 1667 to arrayOf("messages", "lines", "left"), 1669 to arrayOf("pct", "view", "max"), 1670 to arrayOf("pct"), 1671 to arrayOf("done", "total"), 1673 to arrayOf("n"), 1674 to arrayOf("n"), 1675 to arrayOf("time"), 1676 to arrayOf("view", "max"), 1677 to arrayOf("view", "max"), 1679 to arrayOf("more"), 1683 to arrayOf("n"), 1692 to arrayOf("n"), 1698 to arrayOf("page"), 1709 to arrayOf("title"), 1712 to arrayOf("n"), 1729 to arrayOf("name"), 1794 to arrayOf("line"), 1795 to arrayOf("quote"), 1796 to arrayOf("n"), 1797 to arrayOf("n"), 1798 to arrayOf("n"), 1799 to arrayOf("n"), 1800 to arrayOf("n"), 1805 to arrayOf("held"), 1806 to arrayOf("machine"), 1807 to arrayOf("machine"), 1815 to arrayOf("count", "total"), 1816 to arrayOf("count"), 1817 to arrayOf("n"), 1829 to arrayOf("name"), 1831 to arrayOf("n", "c", "total"), 1832 to arrayOf("n", "c"), 1833 to arrayOf("n", "c", "total", "before"), 1834 to arrayOf("n", "c", "before"), 1846 to arrayOf("name"), 1847 to arrayOf("path"), 1850 to arrayOf("file"), 1851 to arrayOf("path", "n"), 1852 to arrayOf("why"), 1853 to arrayOf("n"), 1854 to arrayOf("name"), 1855 to arrayOf("name"), 1856 to arrayOf("name"), 1857 to arrayOf("n"), 1858 to arrayOf("shown", "n"), 1861 to arrayOf("path"), 1863 to arrayOf("n"), 1872 to arrayOf("status"), 1889 to arrayOf("name", "pct"), 1890 to arrayOf("name", "mb"), 1891 to arrayOf("name"), 1892 to arrayOf("name", "why"), 1910 to arrayOf("machine"), 1913 to arrayOf("n"), 1914 to arrayOf("ref"), 1915 to arrayOf("ref", "sheet"), 1916 to arrayOf("name"), 1917 to arrayOf("name"), 1918 to arrayOf("file", "folder"), 1919 to arrayOf("name", "error"), 1920 to arrayOf("name", "status"), 1921 to arrayOf("name", "error"), 1923 to arrayOf("name"), 1926 to arrayOf("code"), 1927 to arrayOf("error"), 1930 to arrayOf("error"), 1931 to arrayOf("error"), 1935 to arrayOf("error"), 1953 to arrayOf("done", "of"), 1955 to arrayOf("why"), 1956 to arrayOf("path"), 1957 to arrayOf("error"), 1958 to arrayOf("secs"), 1959 to arrayOf("secs"), 1971 to arrayOf("code"), 1972 to arrayOf("code"), 1975 to arrayOf("state"), 1980 to arrayOf("hide", "copy", "paste"), 1981 to arrayOf("n"), 1984 to arrayOf("name"), 1985 to arrayOf("name", "folder"), 1986 to arrayOf("name"), 1987 to arrayOf("name", "percent"), 1993 to arrayOf("folder"), 2003 to arrayOf("w", "h"), 2007 to arrayOf("path"), 2010 to arrayOf("why"), 2011 to arrayOf("mb"), 2014 to arrayOf("n"), 2015 to arrayOf("delete", "undo"), 2016 to arrayOf("delete", "undo"), 2017 to arrayOf("undo"), 2038 to arrayOf("what", "secs"), 2039 to arrayOf("file", "holder"), 2046 to arrayOf("what"), 2047 to arrayOf("what"), 2048 to arrayOf("editor", "why"), 2067 to arrayOf("files"), 2077 to arrayOf("why"), 2079 to arrayOf("title"), 2080 to arrayOf("title"), 2081 to arrayOf("version"), 2082 to arrayOf("version", "size", "folder"), 2083 to arrayOf("version", "size", "folder"), 2092 to arrayOf("title"), 2093 to arrayOf("dir", "files"), 2099 to arrayOf("why"), 2101 to arrayOf("code"), 2115 to arrayOf("origin"), 2117 to arrayOf("why"), 2128 to arrayOf("dir"), 2129 to arrayOf("path"), 2130 to arrayOf("home", "other"), 2132 to arrayOf("path"), 2133 to arrayOf("code", "log"), 2134 to arrayOf("log"), 2136 to arrayOf("addr"), 2149 to arrayOf("home"), 2150 to arrayOf("addr"), 2165 to arrayOf("dir", "why"), 2166 to arrayOf("dir"), 2181 to arrayOf("phase"), 2183 to arrayOf("why"), 2184 to arrayOf("what"), 2185 to arrayOf("code"), 2191 to arrayOf("label"), 2196 to arrayOf("kind"), 2198 to arrayOf("project"), 2211 to arrayOf("what"), 2213 to arrayOf("when"), 2217 to arrayOf("n"), 2218 to arrayOf("n"), 2219 to arrayOf("n"), 2221 to arrayOf("agent"), 2222 to arrayOf("effort"), 2224 to arrayOf("n"), 2226 to arrayOf("model"), 2238 to arrayOf("word"), 2245 to arrayOf("more", "step"), 2249 to arrayOf("name"), 2253 to arrayOf("max", "skipped"), 2256 to arrayOf("name"), 2257 to arrayOf("n"), 2258 to arrayOf("name"), 2259 to arrayOf("name"), 2265 to arrayOf("n"), 2266 to arrayOf("name"), 2268 to arrayOf("price"), 2271 to arrayOf("name"), 2273 to arrayOf("name"), 2274 to arrayOf("name"), 2275 to arrayOf("name"), 2276 to arrayOf("text"), 2279 to arrayOf("key"), 2280 to arrayOf("key"), 2281 to arrayOf("pct"), 2282 to arrayOf("when"), 2293 to arrayOf("n", "upstream"), 2296 to arrayOf("mb"), 2306 to arrayOf("path"), 2307 to arrayOf("path"), 2329 to arrayOf("id"), 2333 to arrayOf("model"), 2334 to arrayOf("platform"), 2335 to arrayOf("version"), 2338 to arrayOf("version", "from", "into"), 2339 to arrayOf("version", "from"), 2342 to arrayOf("version", "path"), 2343 to arrayOf("version", "path"), 2344 to arrayOf("version", "pin", "from"), 2345 to arrayOf("path"), 2346 to arrayOf("version", "path"), 2347 to arrayOf("version", "path", "set"), 2361 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2368 to arrayOf("tool"), 2369 to arrayOf("tool"), 2370 to arrayOf("tool", "word"), 2371 to arrayOf("tool", "word"), 2372 to arrayOf("tool"), 2373 to arrayOf("tool"), 2374 to arrayOf("due"), 2375 to arrayOf("due"), 2376 to arrayOf("due"), 2377 to arrayOf("due"), 2378 to arrayOf("zone"), 2379 to arrayOf("zone"), 2380 to arrayOf("zone"), 2381 to arrayOf("zone"), 2382 to arrayOf("n"), 2383 to arrayOf("who"), 2384 to arrayOf("n", "who"), 2385 to arrayOf("harness"), 2386 to arrayOf("path"), 2387 to arrayOf("path"), 2388 to arrayOf("path"), 2391 to arrayOf("error", "line"), 2392 to arrayOf("label"), 2400 to arrayOf("who"), 2401 to arrayOf("who"), 2402 to arrayOf("label", "left", "when"), 2403 to arrayOf("left"), 2404 to arrayOf("name", "left"), 2405 to arrayOf("used"), 2406 to arrayOf("used", "limit"), 2407 to arrayOf("used", "reason"), 2408 to arrayOf("used", "limit", "reason"), 2410 to arrayOf("provider"), 2411 to arrayOf("used", "window", "pct"), 2412 to arrayOf("rate"), 2422 to arrayOf("n", "r"), 2427 to arrayOf("time", "n"), 2431 to arrayOf("n", "m"), 2433 to arrayOf("pct"), 2434 to arrayOf("cost", "n"), 2438 to arrayOf("in", "out", "cread", "cwrite"), 2439 to arrayOf("in", "out", "cread", "cwrite", "n"), 2448 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2449 to arrayOf("left", "when"), 2450 to arrayOf("left", "when"), 2451 to arrayOf("left", "when"), 2452 to arrayOf("left", "when"), 2476 to arrayOf("n"), 2499 to arrayOf("when"), 2506 to arrayOf("phrase", "now"), 2517 to arrayOf("s"), 2523 to arrayOf("now"), 2524 to arrayOf("now", "nudge", "sent", "undone"), 2534 to arrayOf("e"), 2535 to arrayOf("a", "ams", "b", "bms"), 2536 to arrayOf("ms"), 2537 to arrayOf("e"), 2538 to arrayOf("t"), 2539 to arrayOf("t"), 2540 to arrayOf("t"), 2546 to arrayOf("why"), 2556 to arrayOf("apps"), 2566 to arrayOf("n"), 2567 to arrayOf("n", "k"), 2572 to arrayOf("stt", "conf"), 2573 to arrayOf("words"), 2583 to arrayOf("into"), 2586 to arrayOf("origin"), 2598 to arrayOf("url"), 2600 to arrayOf("url"), 2608 to arrayOf("i", "n"), 2609 to arrayOf("d", "n"), 2618 to arrayOf("version"), 2619 to arrayOf("version"), 2620 to arrayOf("version"), 2623 to arrayOf("path"), 2631 to arrayOf("addr"), 2635 to arrayOf("label"), 2637 to arrayOf("label"), 2638 to arrayOf("label"), 2642 to arrayOf("label"), 2647 to arrayOf("from"), 2664 to arrayOf("done", "of"), 2670 to arrayOf("n"), 2671 to arrayOf("t", "m"), 2672 to arrayOf("m"), 2673 to arrayOf("b", "m"), 2674 to arrayOf("r", "p"), 2675 to arrayOf("n"), 2676 to arrayOf("n"), 2677 to arrayOf("n"), 2678 to arrayOf("n"), 2681 to arrayOf("n"), 2683 to arrayOf("n"), 2691 to arrayOf("n"), 2697 to arrayOf("name", "gb", "path"), 2699 to arrayOf("path", "why"), 2701 to arrayOf("names"), 2703 to arrayOf("why"), 2704 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2705 to arrayOf("done", "total"), 2706 to arrayOf("n"), 2707 to arrayOf("what"), 2708 to arrayOf("n"), 2709 to arrayOf("n"), 2712 to arrayOf("what"), 2713 to arrayOf("n"), 2715 to arrayOf("why", "from"), 2716 to arrayOf("why"), 2722 to arrayOf("path"), 2723 to arrayOf("path", "who"), 2724 to arrayOf("path"), 2725 to arrayOf("path", "cmd"), 2726 to arrayOf("version", "path"), 2727 to arrayOf("version", "path"), 2728 to arrayOf("version", "path", "who"), 2729 to arrayOf("version", "path"), 2730 to arrayOf("version", "path", "cmd"), 2733 to arrayOf("cmd"), 2743 to arrayOf("name", "version", "path"), 2744 to arrayOf("path", "why"), 2745 to arrayOf("name"), 2747 to arrayOf("version", "cli"), 2748 to arrayOf("cli"), 2750 to arrayOf("version"), 2751 to arrayOf("version"), 2753 to arrayOf("version"), 2755 to arrayOf("version"), 2757 to arrayOf("computer"), 2758 to arrayOf("version", "cli"), 2759 to arrayOf("cli"), 2760 to arrayOf("version", "cli"), 2761 to arrayOf("cli"), 2783 to arrayOf("n"), 2788 to arrayOf("code"), 2790 to arrayOf("e"), 2803 to arrayOf("n"), 2808 to arrayOf("channel"), 2822 to arrayOf("project"), 2828 to arrayOf("n"), 2840 to arrayOf("m"), 2852 to arrayOf("m"), 2855 to arrayOf("m"), 2862 to arrayOf("pages"), 2864 to arrayOf("name"), 2867 to arrayOf("name"), 2876 to arrayOf("d", "n"), 2897 to arrayOf("n", "tools"), 2898 to arrayOf("n", "tools", "d"), 2899 to arrayOf("n", "d"), 2900 to arrayOf("n", "what"), 2901 to arrayOf("n", "d", "what"), 2905 to arrayOf("head"), 2911 to arrayOf("name", "path"), 2917 to arrayOf("page", "net", "near"), 2918 to arrayOf("page", "what"), 2919 to arrayOf("ref"), 2923 to arrayOf("page"), 2946 to arrayOf("n"), 2947 to arrayOf("n"), 2948 to arrayOf("n"), 2950 to arrayOf("hub"), 2972 to arrayOf("project"), 2974 to arrayOf("n"), 2975 to arrayOf("n"), 2976 to arrayOf("word"), 2977 to arrayOf("n"), 2995 to arrayOf("name"), 3003 to arrayOf("answer"), 3008 to arrayOf("why"), 3010 to arrayOf("hub"), 3016 to arrayOf("from", "to"), 3023 to arrayOf("project"), 3033 to arrayOf("name"), 3037 to arrayOf("n"), 3043 to arrayOf("code"), 3044 to arrayOf("hub"), 3045 to arrayOf("hub"), 3046 to arrayOf("hub"), 3060 to arrayOf("n"), 3061 to arrayOf("n"), 3077 to arrayOf("status"), 3079 to arrayOf("status"), 3108 to arrayOf("project"), 3112 to arrayOf("code"), 3114 to arrayOf("why"), 3122 to arrayOf("title"), 3128 to arrayOf("title"), 3130 to arrayOf("q"), 3131 to arrayOf("title"), 3136 to arrayOf("room"), 3140 to arrayOf("q"), 3150 to arrayOf("title"), 3155 to arrayOf("n"), 3156 to arrayOf("n"), 3161 to arrayOf("at"), 3169 to arrayOf("size"), 3171 to arrayOf("n", "total"), 3188 to arrayOf("n"), 3189 to arrayOf("what"), 3192 to arrayOf("device"), 3193 to arrayOf("device"), 3202 to arrayOf("word", "count"), 3203 to arrayOf("heard"), 3215 to arrayOf("files"), 3216 to arrayOf("files"), 3219 to arrayOf("name"), 3247 to arrayOf("n"), 3248 to arrayOf("n"), 3259 to arrayOf("n"), 3293 to arrayOf("root"), 3294 to arrayOf("path"), 3317 to arrayOf("name"), 3320 to arrayOf("until"), 3321 to arrayOf("error"), 3328 to arrayOf("url"), 3332 to arrayOf("name"), 3333 to arrayOf("name"), 3341 to arrayOf("code", "hub", "until"), 3342 to arrayOf("url"), 3346 to arrayOf("kinds"), 3347 to arrayOf("address"), 3349 to arrayOf("address"), 3352 to arrayOf("url"), 3353 to arrayOf("url"), 3354 to arrayOf("url"), 3355 to arrayOf("url", "via"), 3360 to arrayOf("name"), 3361 to arrayOf("url", "check", "left"), 3363 to arrayOf("check"), 3364 to arrayOf("address"), 3365 to arrayOf("name"), 3366 to arrayOf("error"), 3367 to arrayOf("url"), 3368 to arrayOf("url"), 3375 to arrayOf("code", "address", "left"), 3381 to arrayOf("name"), 3382 to arrayOf("name"), 3393 to arrayOf("address"), 3400 to arrayOf("code", "body"), 3403 to arrayOf("code", "body"), 3409 to arrayOf("window", "used"), 3410 to arrayOf("window", "used", "when"), 3411 to arrayOf("window", "used"), 3412 to arrayOf("window", "used", "when"), 3413 to arrayOf("provider"), 3425 to arrayOf("label"), 3426 to arrayOf("when"), 3428 to arrayOf("provider"), 3429 to arrayOf("provider", "title", "why"), 3449 to arrayOf("reason"), 3457 to arrayOf("code"), 3466 to arrayOf("name"), 3469 to arrayOf("version"), 3470 to arrayOf("version"), 3471 to arrayOf("version"), 3473 to arrayOf("version"), 3474 to arrayOf("version"), 3475 to arrayOf("version"), 3476 to arrayOf("version", "why"), 3477 to arrayOf("version"), 3479 to arrayOf("code"), 3495 to arrayOf("name"), 3502 to arrayOf("count"), 3503 to arrayOf("title"), 3504 to arrayOf("name"), 3507 to arrayOf("n", "holder"), 3508 to arrayOf("n", "title"), 3509 to arrayOf("title"), 3512 to arrayOf("n"), 3513 to arrayOf("n"), 3514 to arrayOf("n"), 3515 to arrayOf("n"), 3516 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3526 to arrayOf("pid"), 3531 to arrayOf("left"), 3532 to arrayOf("left"), 3538 to arrayOf("left"), 3539 to arrayOf("left"), 3540 to arrayOf("left"), 3541 to arrayOf("left"), 3542 to arrayOf("label", "left"), 3543 to arrayOf("when"), 3544 to arrayOf("used"), 3545 to arrayOf("used", "limit"), 3567 to arrayOf("tracking"), 3571 to arrayOf("total"), 3572 to arrayOf("price"), 3573 to arrayOf("price"), 3578 to arrayOf("n"), 3579 to arrayOf("parts"), 3580 to arrayOf("note"), 3581 to arrayOf("error"), 3582 to arrayOf("error", "parts"), 3587 to arrayOf("state"), 3588 to arrayOf("name", "path"), 3589 to arrayOf("name", "path", "why"), 3591 to arrayOf("code"), 3595 to arrayOf("detail"), 3597 to arrayOf("why"), 3598 to arrayOf("parts"), 3601 to arrayOf("build", "to"), 3602 to arrayOf("build"), 3603 to arrayOf("build", "skip"), 3605 to arrayOf("why"), 3606 to arrayOf("why"), 3607 to arrayOf("build"), 3608 to arrayOf("build", "why"), 3609 to arrayOf("build"), 3610 to arrayOf("build"), 3614 to arrayOf("build"), 3615 to arrayOf("build"), 3617 to arrayOf("build"), 3624 to arrayOf("build"), 3658 to arrayOf("step"), 3659 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3660 to arrayOf("done", "total"), 3661 to arrayOf("n"), 3662 to arrayOf("n"), 3663 to arrayOf("n"), 3668 to arrayOf("n"), 3671 to arrayOf("why"), 3672 to arrayOf("why", "from"), 3673 to arrayOf("error"), 3675 to arrayOf("n"), 3676 to arrayOf("n"), 3680 to arrayOf("n"), 3683 to arrayOf("name", "gb", "path"), 3684 to arrayOf("path", "why"), 3685 to arrayOf("names"), 3687 to arrayOf("why"), 3698 to arrayOf("n", "total"), 3702 to arrayOf("title"), 3704 to arrayOf("n"), 3708 to arrayOf("name"), 3709 to arrayOf("title"), 3710 to arrayOf("note"), 3712 to arrayOf("machine"), 3713 to arrayOf("machines"), 3714 to arrayOf("machine"), 3725 to arrayOf("n"), 3727 to arrayOf("n"), 3731 to arrayOf("name"), 3734 to arrayOf("name"), 3751 to arrayOf("why"), 3757 to arrayOf("project"), 3798 to arrayOf("path"), 3799 to arrayOf("path"), 3801 to arrayOf("have", "total"), 3806 to arrayOf("n"), 3815 to arrayOf("hub"), 3818 to arrayOf("title"), 3822 to arrayOf("project"), 3823 to arrayOf("project"), 3824 to arrayOf("n"), 3825 to arrayOf("hub"), 3827 to arrayOf("n"), 3828 to arrayOf("n"), 3829 to arrayOf("model"), 3835 to arrayOf("name"), 3854 to arrayOf("word"), 3860 to arrayOf("answer"), 3870 to arrayOf("version", "build"), 3871 to arrayOf("hub"), 3876 to arrayOf("name"), 3879 to arrayOf("when", "who", "mark"), 3883 to arrayOf("who"), 3887 to arrayOf("time"), 3888 to arrayOf("address"), 3890 to arrayOf("kind", "name"), 3905 to arrayOf("title"), 3906 to arrayOf("query"), 3909 to arrayOf("room"), 3910 to arrayOf("query"), 3912 to arrayOf("n"), 3913 to arrayOf("n"), 3914 to arrayOf("n"), 3920 to arrayOf("size"), 3924 to arrayOf("n"), 3925 to arrayOf("n"), 3926 to arrayOf("n"), 3940 to arrayOf("status"), 3942 to arrayOf("status"), 4093 to arrayOf("code"), 4095 to arrayOf("n"), 4097 to arrayOf("why"), 4109 to arrayOf("done", "of"), 4113 to arrayOf("thread"), 4116 to arrayOf("n"), 4124 to arrayOf("title"), 4125 to arrayOf("note"), 4126 to arrayOf("label"), 4127 to arrayOf("machine"), 4128 to arrayOf("machine"), 4135 to arrayOf("at", "total"), 4136 to arrayOf("at", "total"), 4140 to arrayOf("machine"), 4141 to arrayOf("machine"), 4142 to arrayOf("machines"), 4144 to arrayOf("device"), 4151 to arrayOf("price"), 4152 to arrayOf("price"), 4159 to arrayOf("home"), 4164 to arrayOf("from"), 4166 to arrayOf("note"), 4167 to arrayOf("note"), 4169 to arrayOf("v"), 4170 to arrayOf("v"), 4171 to arrayOf("v", "who"), 4173 to arrayOf("who"), 4174 to arrayOf("v"), 4176 to arrayOf("v", "cmd"), 4177 to arrayOf("cmd"), 4182 to arrayOf("v", "path"), 4183 to arrayOf("v", "note"), 4184 to arrayOf("v"), 4189 to arrayOf("tool"), 4190 to arrayOf("tool"), 4215 to arrayOf("n", "w"), 4216 to arrayOf("why"), 4217 to arrayOf("state", "why"), 4229 to arrayOf("project"), 4230 to arrayOf("n"), 4241 to arrayOf("why"), 4247 to arrayOf("name"), 4258 to arrayOf("project"), 4263 to arrayOf("n"), 4271 to arrayOf("names"), 4279 to arrayOf("dest"), 4281 to arrayOf("repo"), 4282 to arrayOf("repo"), 4284 to arrayOf("url"), 4308 to arrayOf("group"), 4312 to arrayOf("project"), 4313 to arrayOf("n"), 4314 to arrayOf("n"), 4315 to arrayOf("n"), 4323 to arrayOf("n"), 4380 to arrayOf("n"), 4381 to arrayOf("n"), 4382 to arrayOf("a", "b"), 4383 to arrayOf("n"), 4385 to arrayOf("parts", "lines"), 4386 to arrayOf("n"), 4417 to arrayOf("what", "project", "fab"), 4418 to arrayOf("rev", "day"), 4426 to arrayOf("n"), 4437 to arrayOf("layer"), 4438 to arrayOf("n"), 4443 to arrayOf("board"), 4455 to arrayOf("others"), 4456 to arrayOf("must", "should", "notes"), 4457 to arrayOf("id", "w"), 4467 to arrayOf("what"), 4470 to arrayOf("why"), 4471 to arrayOf("why"), 4478 to arrayOf("n"), 4494 to arrayOf("price", "n"), 4495 to arrayOf("n", "need"), 4496 to arrayOf("n"), 4497 to arrayOf("n"), 4498 to arrayOf("cost"), 4499 to arrayOf("cost"), 4512 to arrayOf("day", "n"), 4513 to arrayOf("day"), 4514 to arrayOf("cost", "n", "lines"), 4515 to arrayOf("stock", "price"), 4516 to arrayOf("lines"), 4537 to arrayOf("host"), 4548 to arrayOf("n"), 4549 to arrayOf("a", "b"), 4550 to arrayOf("n"), 4551 to arrayOf("n"), 4554 to arrayOf("day"), 4555 to arrayOf("n"), 4596 to arrayOf("turn"), 4710 to arrayOf("text"), 4713 to arrayOf("repo", "dest"), 4714 to arrayOf("repo", "dest"), 4715 to arrayOf("repo"), 4720 to arrayOf("dir"), 4721 to arrayOf("dir"), 4725 to arrayOf("editor", "job", "secs"), 4726 to arrayOf("editor", "secs"), 4727 to arrayOf("editor"), 4744 to arrayOf("time"), 4750 to arrayOf("status"), 4758 to arrayOf("time"), 4759 to arrayOf("time", "dur"), 4762 to arrayOf("answer"), 4766 to arrayOf("type"), 4767 to arrayOf("max"), 4795 to arrayOf("bytes", "tokens"), 4828 to arrayOf("what"), 4832 to arrayOf("n"), 4834 to arrayOf("n")) } @@ -27702,4 +27802,25 @@ object Msg { fun web_plan_awaiting(n: Any): String = Tr.f(4832, arrayOf(n)) val web_plan_net_one: String get() = Tr.s(4833) fun web_plan_nets(n: Any): String = Tr.f(4834, arrayOf(n)) + val gpui_mgmt_plan_view_canvas: String get() = Tr.s(4835) + val gpui_mgmt_plan_view_split: String get() = Tr.s(4836) + val gpui_mgmt_plan_view_list: String get() = Tr.s(4837) + val gpui_mgmt_plan_grid_all: String get() = Tr.s(4838) + val gpui_mgmt_plan_grid_pair: String get() = Tr.s(4839) + val gpui_mgmt_plan_grid_single: String get() = Tr.s(4840) + val gpui_mgmt_plan_expand: String get() = Tr.s(4841) + val gpui_mgmt_plan_compact: String get() = Tr.s(4842) + val gpui_mgmt_plan_sync: String get() = Tr.s(4843) + val gpui_mgmt_plan_fit: String get() = Tr.s(4844) + val gpui_mgmt_plan_lock: String get() = Tr.s(4845) + val gpui_mgmt_plan_unlock: String get() = Tr.s(4846) + val gpui_mgmt_plan_layer_move: String get() = Tr.s(4847) + val gpui_mgmt_plan_width: String get() = Tr.s(4848) + val gpui_mgmt_plan_addnote: String get() = Tr.s(4849) + val gpui_mgmt_plan_note_placeholder: String get() = Tr.s(4850) + val gpui_mgmt_plan_hint: String get() = Tr.s(4851) + val gpui_mgmt_plan_rejectlayer: String get() = Tr.s(4852) + val gpui_mgmt_plan_edited: String get() = Tr.s(4853) + val gpui_mgmt_plan_locked: String get() = Tr.s(4854) + val gpui_mgmt_plan_noitems: String get() = Tr.s(4855) } diff --git a/mobile/ios/Shared/TrCatalog.swift b/mobile/ios/Shared/TrCatalog.swift index 72ae4875a4..736591b745 100644 --- a/mobile/ios/Shared/TrCatalog.swift +++ b/mobile/ios/Shared/TrCatalog.swift @@ -4838,6 +4838,27 @@ gpui.keys.mgmt.plan Plan panel beside the design: open or close 設計横の計 web.plan.awaiting {n} awaiting approval {n} 件が承認待ち {n} esperando aprobación web.plan.net.one 1 net 1 ネット 1 red web.plan.nets {n} nets {n} ネット {n} redes +gpui.mgmt.plan.view.canvas Canvas キャンバス Lienzo +gpui.mgmt.plan.view.split Split 分割 Dividido +gpui.mgmt.plan.view.list List リスト Lista +gpui.mgmt.plan.grid.all All layers 全レイヤー Todas las capas +gpui.mgmt.plan.grid.pair Side by side 並べて表示 Lado a lado +gpui.mgmt.plan.grid.single Single 単一 Única +gpui.mgmt.plan.expand Expand 拡大 Expandir +gpui.mgmt.plan.compact Compact 標準 Compacto +gpui.mgmt.plan.sync Link zoom ズーム連動 Vincular zoom +gpui.mgmt.plan.fit Fit 全体表示 Ajustar +gpui.mgmt.plan.lock Lock ロック Bloquear +gpui.mgmt.plan.unlock Unlock ロック解除 Desbloquear +gpui.mgmt.plan.layer.move Move to layer レイヤー移動 Mover a capa +gpui.mgmt.plan.width Width 幅 Ancho +gpui.mgmt.plan.addnote Add note メモを追加 Añadir nota +gpui.mgmt.plan.note.placeholder Steering note for router… ルーターへの指示メモ… Nota de guiado para el router… +gpui.mgmt.plan.hint Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove 頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除 Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar +gpui.mgmt.plan.rejectlayer Reject layer レイヤーを却下 Rechazar capa +gpui.mgmt.plan.edited Edited 編集済み Editado +gpui.mgmt.plan.locked Locked ロック中 Bloqueado +gpui.mgmt.plan.noitems No corridors or planes on this layer このレイヤーにコリドーまたはプレーンがありません Sin corredores ni planos en esta capa """# /// thread.count = {n, plural, one {# thread} other {# threads}} diff --git a/native/gpui/src/screens/mgmt.rs b/native/gpui/src/screens/mgmt.rs index 6f33bc7da0..4eb9cc9361 100644 --- a/native/gpui/src/screens/mgmt.rs +++ b/native/gpui/src/screens/mgmt.rs @@ -46,6 +46,7 @@ pub struct Mgmt { pub plan_next: Option<(String, Instant, bool)>, pub plan_sel: Option, pub plan_stackup_open: bool, + pub plan_ui: super::mgmt_plan_canvas::State, } /// What a pressed plan review link does now, on the page drawn: open the Plan panel (the board shown is the plan's, or its board could not be shown /// within a few seconds: the panel then names the board whose plan waits), show its board first, or wait for the page. @@ -122,7 +123,7 @@ impl Mgmt { fn want(app: &mut Backplane, project: &str) { if app.screens.mgmt.asked == project { return } app.screens.mgmt.asked = project.to_string(); - if app.screens.mgmt.project != project { app.screens.mgmt.digest.clear(); app.screens.mgmt.bom = Default::default(); app.screens.mgmt.checks.reset(); app.screens.mgmt.error.clear(); app.screens.mgmt.plan_sel = None; app.screens.mgmt.plan_stackup_open = false; } + if app.screens.mgmt.project != project { app.screens.mgmt.digest.clear(); app.screens.mgmt.bom = Default::default(); app.screens.mgmt.checks.reset(); app.screens.mgmt.error.clear(); app.screens.mgmt.plan_sel = None; app.screens.mgmt.plan_stackup_open = false; app.screens.mgmt.plan_ui.reset(); } let _ = app.tx.try_send(Command::Ask("mgmt.watch".into(), json!({"project": project}), WATCH_TAG)); } /// `mgmt.watch`'s answer: the project's digest (what its info keys end in). @@ -130,6 +131,7 @@ pub fn answered(app: &mut Backplane, id: u64, reply: &Value, cx: &mut Context [(u64, &'static str); 5] { pub fn shown(l: &Value, hide_done: bool) -> Vec { l["items"].as_array().into_iter().flatten().filter(|i| !(hide_done && done(i))).cloned().collect() } fn hex(c: &str) -> u32 { u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap_or(0x8a8a8a) } -fn send(app: &mut Backplane, m: &str, mut p: Value, cx: &mut Context) { +pub(super) fn send(app: &mut Backplane, m: &str, mut p: Value, cx: &mut Context) { let pro = app.screens.mgmt.project.clone(); if pro.is_empty() { return } p["pro"] = json!(pro); eprintln!("GPUI_LOG {}", json!({"event": "plan_press", "method": m, "params": p})); - let _ = app.tx.try_send(Command::Rpc(m.into(), Secret(p), if m == "plan.approve" { "plan" } else { "mgmt" })); + let tag = if matches!(m, "plan.approve" | "plan.update") { "plan" } else { "mgmt" }; + let _ = app.tx.try_send(Command::Rpc(m.into(), Secret(p), tag)); app.ui_epoch += 1; cx.notify(); } pub fn approve(app: &mut Backplane, layer: &str, ids: &[String], yes: bool, cx: &mut Context) { *REFUSED.lock().unwrap() = None; send(app, "plan.approve", json!({"layer": layer, "ids": ids, "approve": yes}), cx) } @@ -79,12 +80,18 @@ static REFUSED: std::sync::Mutex> = std::sync::Mutex::new(None); /// plan.approve's answer (tag "plan"): a refusal is said in the panel; an approval shows in the plan itself. pub fn answered(app: &mut Backplane, ok: bool, why: &str, cx: &mut Context) { *REFUSED.lock().unwrap() = (!ok).then(|| if why.is_empty() { trs("KiCad refused") } else { why.to_string() }); + if !ok { app.screens.mgmt.plan_ui.optimistic.clear(); } app.ui_epoch += 1; cx.notify(); } /// The e2e harness's controls (`mgmt:plan:`). pub fn controls(m: &super::mgmt::Mgmt) -> Vec<(String, String, String)> { if m.peek()["open"] != "plan" { return vec![] } - let d = m.data("plan"); let mut v: Vec<(String, String, String)> = vec![("mgmt:plan:on".into(), "On".into(), "plan:enable:on".into()), ("mgmt:plan:off".into(), "Off".into(), "plan:enable:off".into())]; // i18n-ok: ctl ids + let d = m.data("plan"); let mut v: Vec<(String, String, String)> = vec![ + ("mgmt:plan:on".into(), "On".into(), "plan:enable:on".into()), ("mgmt:plan:off".into(), "Off".into(), "plan:enable:off".into()), // i18n-ok: ctl ids + ("mgmt:plan:view:canvas".into(), "Canvas".into(), "plan:view:canvas".into()), ("mgmt:plan:view:split".into(), "Split".into(), "plan:view:split".into()), ("mgmt:plan:view:list".into(), "List".into(), "plan:view:list".into()), // i18n-ok: ctl ids + ("mgmt:plan:grid:pair".into(), "Side by side".into(), "plan:grid:pair".into()), ("mgmt:plan:grid:all".into(), "All layers".into(), "plan:grid:all".into()), ("mgmt:plan:grid:single".into(), "Single".into(), "plan:grid:single".into()), // i18n-ok: ctl ids + ("mgmt:plan:expand".into(), "Expand".into(), "plan:expand".into()), ("mgmt:plan:fit".into(), "Fit".into(), "plan:fit".into()), // i18n-ok: ctl ids + ]; if d["awaiting"].as_u64().unwrap_or(0) > 0 { v.push(("mgmt:plan:approve-all".into(), "Approve all".into(), "plan:all".into())) } // i18n-ok: ctl ids if d["routing"] == true { v.push(("mgmt:plan:stop".into(), "Stop routing".into(), "plan:stop".into())) } // i18n-ok: ctl ids if d["live"] == true && d["done"].as_u64().unwrap_or(0) > 0 { v.push(("mgmt:plan:verify".into(), "Verify".into(), "plan:verify".into())) } // i18n-ok: ctl ids @@ -99,6 +106,14 @@ pub fn act(app: &mut Backplane, a: &str, cx: &mut Context) { else if let Some(x) = a.strip_prefix("enable:") { enable(app, x == "on", cx) } else if a == "stop" { send(app, "plan.stop", json!({}), cx) } else if a == "verify" { send(app, "plan.verify", json!({}), cx) } + else if a == "view:canvas" { app.screens.mgmt.plan_ui.view_mode = ViewMode::Canvas; cx.notify(); } + else if a == "view:split" { app.screens.mgmt.plan_ui.view_mode = ViewMode::Split; cx.notify(); } + else if a == "view:list" { app.screens.mgmt.plan_ui.view_mode = ViewMode::List; cx.notify(); } + else if a == "grid:pair" { app.screens.mgmt.plan_ui.grid_mode = GridMode::Pair; cx.notify(); } + else if a == "grid:all" { app.screens.mgmt.plan_ui.grid_mode = GridMode::All; cx.notify(); } + else if a == "grid:single" { app.screens.mgmt.plan_ui.grid_mode = GridMode::Single; cx.notify(); } + else if a == "expand" { toggle_expand(app, cx); } + else if a == "fit" { app.screens.mgmt.plan_ui.fit_all(); cx.notify(); } else if let Some(id) = a.strip_prefix("approve:") { approve(app, "", &[id.to_string()], true, cx) } else if let Some(id) = a.strip_prefix("reject:") { approve(app, "", &[id.to_string()], false, cx) } else if let Some(id) = a.strip_prefix("focus:") { @@ -107,6 +122,20 @@ pub fn act(app: &mut Backplane, a: &str, cx: &mut Context) { } } +fn toggle_expand(app: &mut Backplane, cx: &mut Context) { + let next = !app.screens.mgmt.plan_ui.expanded; + app.screens.mgmt.plan_ui.expanded = next; + let target = if next { mgmt_plan_canvas::EXPANDED_PANEL_W } else { mgmt_plan_canvas::COMPACT_PANEL_W }; + let mut st = app.screens.mgmt.state(); + if !st.is_null() { + st["size"] = json!(target); + super::mgmt::set(app, st, json!({"size": target}), cx); + } else { + app.ui_epoch += 1; + cx.notify(); + } +} + /// The Boards menu's value for a board the hub names (absolute `pcb`, `rel` from the project's folder): the menu's own entry when it /// lists it, else `rel`. pub fn board_value(boards: &[crate::viewers::boards::Board], pcb: &str, rel: &str) -> String { @@ -178,7 +207,12 @@ pub fn body(app: &mut Backplane, d: &Value, light: bool, cx: &mut Context = mgmt_plan_canvas::visible_layers(&app.screens.mgmt.plan_ui, &all_layers_arr) + .iter() + .filter_map(|l| l["layer"].as_str().map(str::to_string)) + .collect(); + let layer_bar = (view_mode != ViewMode::List && all_layers_arr.len() > 1).then(|| { + let mut row = div().flex_shrink_0().flex().flex_wrap().items_center().gap(px(4.)).px_2().py(px(3.)).border_b_1().border_color(c("rule")).bg(c("bg")).text_size(crate::scale::tpx(10.)); + for l in &all_layers_arr { + let lname = s(l, "layer").to_string(); + let title = l["title"].as_str().filter(|x| !x.is_empty()).unwrap_or(&lname).to_string(); + let active = shown_names.contains(&lname); + let lc = lname.clone(); + row = row.child(chip(cx, light, &format!("mgmt:plan:layerpill:{lname}"), title, active, move |a, cx| { + mgmt_plan_canvas::pick_layer_in_grid(&mut a.screens.mgmt.plan_ui, lc.clone()); + cx.notify(); + })); + } + row.into_any_element() + }); + + let sel_inspector = app.screens.mgmt.plan_sel.as_ref().and_then(|sel_id| { + let mut found: Option<(String, Value)> = None; + for l in &all_layers_arr { + for it in l["items"].as_array().into_iter().flatten() { + if it["id"].as_str() == Some(sel_id.as_str()) { + found = Some((s(l, "layer").to_string(), it.clone())); + break; + } + } + if found.is_some() { break } + } + let (cur_layer, item) = found?; + let id = sel_id.clone(); + let name = s(&item, "name").to_string(); + let stt = s(&item, "state").to_string(); + let locked = item["locked"] == true; + let edited = item["edited"] == true || stt == "edited"; + let is_corridor = s(&item, "kind") == "corridor"; + let width_mm = item["width"].as_f64().unwrap_or(1.5); + let col = if is_corridor { + mgmt_plan_canvas::bus_color(&name, s(&item, "color")) + } else { + mgmt_plan_canvas::rail_color(&name, s(&item, "color")) + }; + let copper_opts: Vec = d["copper_layers"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| c["layer"].as_str().map(str::to_string)) + .collect(); + let move_layers = if copper_opts.is_empty() { + all_layers_arr.iter().filter_map(|l| l["layer"].as_str().map(str::to_string)).collect() + } else { + copper_opts + }; + + let id_lock = id.clone(); + let id_ok = id.clone(); + let id_no = id.clone(); + let id_wdown = id.clone(); + let id_wup = id.clone(); + + let mut box_el = div() + .flex_shrink_0() + .flex() + .flex_col() + .gap(px(4.)) + .px_2() + .py(px(6.)) + .border_b_1() + .border_color(c("rule")) + .bg(c("panel")) + .text_size(crate::scale::tpx(11.)) + .child( + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(6.)) + .child(div().size(px(10.)).bg(rgb(col))) + .child(div().font_weight(FontWeight::BOLD).text_color(c("text")).child(name)) + .child(div().text_color(c("dim")).child(cur_layer.clone())) + .when(edited, |x| x.child(div().px_1().border_1().border_color(c("warn")).text_size(crate::scale::tpx(10.)).text_color(c("warn")).child(trs("Edited")))) + .when(locked, |x| x.child(div().px_1().border_1().border_color(c("line")).text_size(crate::scale::tpx(10.)).text_color(c("dim")).child(trs("Locked")))) + .child(div().flex_1()) + .child(btn(cx, light, "mgmt:plan:ins:lock".into(), if locked { trs("Unlock") } else { trs("Lock") }, false, move |a, cx| { + mgmt_plan_canvas::commit_item_fields(a, &id_lock, json!({"locked": !locked}), cx); + })) + .when(matches!(stt.as_str(), "proposed" | "edited"), |x| { + let a_id = id_ok.clone(); + let r_id = id_no.clone(); + x.child(btn(cx, light, "mgmt:plan:ins:ok".into(), trs("Approve"), true, move |a, cx| approve(a, "", &[a_id.clone()], true, cx))) + .child(btn(cx, light, "mgmt:plan:ins:no".into(), trs("Reject"), false, move |a, cx| approve(a, "", &[r_id.clone()], false, cx))) + }) + .child(btn(cx, light, "mgmt:plan:ins:note".into(), trs("Add note"), false, |a, cx| { + a.screens.mgmt.plan_ui.note_open = !a.screens.mgmt.plan_ui.note_open; + cx.notify(); + })) + .child(div().id("plan-ins-close").cursor_pointer().px_1().text_color(c("dim")).hover(|s| s.text_color(c("text"))).child("\u{d7}") + .on_click(cx.listener(|a, _, _, cx| { a.screens.mgmt.plan_sel = None; a.screens.mgmt.plan_ui.selected_vertex = None; cx.notify(); }))), + ); + + if !locked { + let mut steer_row = div().flex().flex_wrap().items_center().gap(px(5.)).text_size(crate::scale::tpx(10.)); + if is_corridor { + let wd_dn = (((width_mm - 0.25).clamp(0.15, 25.0)) * 100.0).round() / 100.0; + let wd_up = (((width_mm + 0.25).clamp(0.15, 25.0)) * 100.0).round() / 100.0; + steer_row = steer_row + .child(div().text_color(c("dim")).child(trs("Width"))) + .child(btn(cx, light, "mgmt:plan:ins:w-".into(), "-".into(), false, move |a, cx| { + mgmt_plan_canvas::commit_item_fields(a, &id_wdown, json!({"width": wd_dn}), cx); + })) + /* i18n-ok: metric width readout */ + .child(div().px_1().font(crate::art::mono_font()).text_color(c("text")).child(format!("{width_mm:.2}mm"))) + .child(btn(cx, light, "mgmt:plan:ins:w+".into(), "+".into(), false, move |a, cx| { + mgmt_plan_canvas::commit_item_fields(a, &id_wup, json!({"width": wd_up}), cx); + })) + .child(div().w(px(1.)).h(px(12.)).bg(c("line"))); + } + if !move_layers.is_empty() { + steer_row = steer_row.child(div().text_color(c("dim")).child(trs("Move to layer"))); + for ml in move_layers { + let is_cur = ml == cur_layer; + let id_mv = id.clone(); + let ml_c = ml.clone(); + steer_row = steer_row.child(chip(cx, light, &format!("mgmt:plan:ins:mv:{ml}"), ml, is_cur, move |a, cx| { + if !is_cur { + mgmt_plan_canvas::commit_item_fields(a, &id_mv, json!({"layer": ml_c.clone()}), cx); + mgmt_plan_canvas::pick_layer_in_grid(&mut a.screens.mgmt.plan_ui, ml_c.clone()); + } + })); + } + } + box_el = box_el.child(steer_row); + } + + if app.screens.mgmt.plan_ui.note_open { + if app.screens.mgmt.plan_ui.note_input.is_none() { + let f = cx.new(|cx| { + let mut comp = Composer::with_context(cx, "AskInput"); + comp.set_placeholder(&trs("Steering note for router…")); + comp.max_lines = 1.0; + comp + }); + cx.subscribe(&f, |this, e, ev: &ComposerEvent, cx| { + if matches!(ev, ComposerEvent::Submit) { + let txt = e.read(cx).content.to_string().trim().to_string(); + if !txt.is_empty() { + if let Some(target_id) = this.screens.mgmt.plan_sel.clone() { + send(this, "plan.update", json!({"ops": [{"op": "note", "id": target_id, "text": txt}]}), cx); + } + e.update(cx, |comp, cx| comp.set(String::new(), cx)); + this.screens.mgmt.plan_ui.note_open = false; + cx.notify(); + } + } + }).detach(); + app.screens.mgmt.plan_ui.note_input = Some(f); + } + if let Some(field) = app.screens.mgmt.plan_ui.note_input.clone() { + let f_sub = field.clone(); + box_el = box_el.child( + div().flex().items_center().gap_1() + .child(div().flex_1().min_w_0().bg(c("bg")).border_1().border_color(c("line")).px_1().child(field)) + .child(btn(cx, light, "mgmt:plan:ins:notesend".into(), trs("Add note"), true, move |this, cx| { + let txt = f_sub.read(cx).content.to_string().trim().to_string(); + if !txt.is_empty() { + if let Some(target_id) = this.screens.mgmt.plan_sel.clone() { + send(this, "plan.update", json!({"ops": [{"op": "note", "id": target_id, "text": txt}]}), cx); + } + f_sub.update(cx, |comp, cx| comp.set(String::new(), cx)); + this.screens.mgmt.plan_ui.note_open = false; + cx.notify(); + } + })), + ); + } + } + + if view_mode != ViewMode::List && !locked { + box_el = box_el.child(div().text_size(crate::scale::tpx(10.)).text_color(c("faint")).child(trs("Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"))); + } + + Some(box_el.into_any_element()) + }); + let mut list = div().id("plan-rows").flex_1().min_h_0().overflow_y_scroll().flex().flex_col().text_size(crate::scale::tpx(12.)); let sel = app.screens.mgmt.plan_sel.clone(); - for l in d["layers"].as_array().cloned().unwrap_or_default() { + for l in all_layers_arr { let layer = s(&l, "layer").to_string(); let total = l["items"].as_array().map_or(0, Vec::len); let stack = s(&l, "stackup").to_string(); @@ -331,7 +579,20 @@ pub fn body(app: &mut Backplane, d: &Value, light: bool, cx: &mut Context div().flex_1().min_h_0().children(canvas_el).into_any_element(), + ViewMode::Split => div() + .flex_1() + .min_h_0() + .flex() + .flex_col() + .child(div().flex_1().min_h(px(210.)).border_b_1().border_color(c("rule")).children(canvas_el)) + .child(div().h(px(190.)).flex_shrink_0().min_h(px(120.)).flex().flex_col().child(list)) + .into_any_element(), + ViewMode::List => list.into_any_element(), + }; + div().size_full().flex().flex_col().children(head).child(status_row).child(act_row).child(view_bar).children(layer_bar).children(ask_banner).children(refused).children(keys).children(stackup_box).children(sel_inspector).child(main_body).children(drawn).into_any_element() } #[cfg(test)] diff --git a/native/gpui/src/screens/mgmt_plan_canvas.rs b/native/gpui/src/screens/mgmt_plan_canvas.rs new file mode 100644 index 0000000000..7a88e20ef6 --- /dev/null +++ b/native/gpui/src/screens/mgmt_plan_canvas.rs @@ -0,0 +1,1947 @@ +//! Per-layer interactive PCB routing floorplanner canvas rendered in GPUI. +//! Mirrors `web/src/plan-canvas.ts` so desktop and browser show identical board geometry, +//! signal corridors with glowing multi-pass highways, diamond vias, net-count pills, +//! translucent power pours, collision-free refdes labels, and direct vertex/layer/width steering. +use crate::{art::mono_font, hub::Command, i18n::trs, screens::mgmt_plan, theme, Backplane}; +use gpui::{prelude::*, *}; +use lyon::tessellation::{LineCap, LineJoin}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +pub const BOARD_TAG: u64 = 9042; +pub const COMPACT_PANEL_W: u64 = 400; +pub const EXPANDED_PANEL_W: u64 = 880; +const SIDE_BY_SIDE_MIN_W: f32 = 540.0; + +// PCB darkroom palette (matches reference floorplanner visual language regardless of chrome theme). +const SUBSTRATE_BG: u32 = 0x111917; +const BOARD_FILL: u32 = 0x16201d; +const EDGE_STROKE: u32 = 0xd4e0db; +const PART_STROKE: u32 = 0x3d5049; +const PART_OVERHANG: u32 = 0x526b61; +const REFDES_COLOR: u32 = 0x8fa39b; +const BADGE_BG: u32 = 0x111917; +const BADGE_FG: u32 = 0xeef5f2; +const HANDLE_BG: u32 = 0xeef5f2; +const HANDLE_ACTIVE: u32 = 0xf59e0b; +const BAD_RED: u32 = 0xef4444; + +const RAIL_PALETTE: &[u32] = &[ + 0xf59e0b, 0x38bdf8, 0xc084fc, 0x2dd4bf, 0xef4444, 0xa3e635, 0xf97316, 0xec4899, +]; +const BUS_PALETTE: &[u32] = &[ + 0x14b8a6, 0xf59e0b, 0xc084fc, 0x22c55e, 0x38bdf8, 0xef4444, 0xe879f9, 0x84cc16, +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ViewMode { + Canvas, + Split, + List, +} +impl Default for ViewMode { + fn default() -> Self { Self::Split } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GridMode { + Pair, + All, + Single, +} +impl Default for GridMode { + fn default() -> Self { Self::Pair } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub cx: f32, + pub cy: f32, + pub scale: f32, + pub fitted: f32, + pub touched: bool, +} + +impl Camera { + pub fn fit(bbox: [f32; 4], w: f32, h: f32, pad: f32) -> Self { + let bw = (bbox[2] - bbox[0]).abs().max(1.0); + let bh = (bbox[3] - bbox[1]).abs().max(1.0); + let uw = (w - pad * 2.0).max(20.0); + let uh = (h - pad * 2.0).max(20.0); + let scale = (uw / bw).min(uh / bh).clamp(0.05, 200.0); + Self { + cx: (bbox[0] + bbox[2]) * 0.5, + cy: (bbox[1] + bbox[3]) * 0.5, + scale, + fitted: scale, + touched: false, + } + } + + pub fn to_px(&self, x: f32, y: f32, w: f32, h: f32) -> (f32, f32) { + (w * 0.5 + (x - self.cx) * self.scale, h * 0.5 + (y - self.cy) * self.scale) + } + + pub fn to_world(&self, px_x: f32, px_y: f32, w: f32, h: f32) -> (f32, f32) { + ( + self.cx + (px_x - w * 0.5) / self.scale.max(1e-4), + self.cy + (px_y - h * 0.5) / self.scale.max(1e-4), + ) + } + + pub fn pan(&self, dx_px: f32, dy_px: f32) -> Self { + Self { + cx: self.cx - dx_px / self.scale.max(1e-4), + cy: self.cy - dy_px / self.scale.max(1e-4), + touched: true, + ..*self + } + } + + pub fn zoom(&self, factor: f32, mx: f32, my: f32, w: f32, h: f32) -> Self { + let min_s = (self.fitted * 0.35).max(0.02); + let max_s = (self.fitted * 24.0).max(40.0); + let ns = (self.scale * factor).clamp(min_s, max_s); + let (wx, wy) = self.to_world(mx, my, w, h); + Self { + cx: wx - (mx - w * 0.5) / ns, + cy: wy - (my - h * 0.5) / ns, + scale: ns, + touched: true, + ..*self + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Hit { + Vertex { id: String, is_plane: bool, idx: usize }, + Midpoint { id: String, is_plane: bool, seg_idx: usize, pos: [f64; 2] }, + Band { id: String }, + Region { id: String }, +} + +impl Hit { + pub fn item_id(&self) -> &str { + match self { + Hit::Vertex { id, .. } | Hit::Midpoint { id, .. } | Hit::Band { id } | Hit::Region { id } => id, + } + } +} + +#[derive(Clone, Debug)] +pub enum DragAction { + Pan { last_x: f32, last_y: f32 }, + Vertex { id: String, is_plane: bool, idx: usize }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PlacedLabel { + pub text: String, + pub cx: f32, + pub cy: f32, +} + +pub struct State { + pub view_mode: ViewMode, + pub grid_mode: GridMode, + pub sync_zoom: bool, + pub expanded: bool, + pub shown_layers: Vec, + pub shared_cam: Option, + pub layer_cams: HashMap, + pub card_bounds: HashMap>, + pub hover: Option<(String, Hit)>, + pub hover_px: Option<(f32, f32)>, + pub selected_vertex: Option<(String, usize)>, + pub drag: Option<(String, DragAction)>, + pub down_pos: Option<(f32, f32)>, + pub optimistic: HashMap, + pub optimistic_at: Option, + pub last_rev: Option, + pub hydrated_key: String, + pub hydrated_board: Option, + pub hydrated_draw: Option, + pub note_open: bool, + pub note_input: Option>, + pub focus: Option, +} + +impl Default for State { + fn default() -> Self { + Self { + view_mode: ViewMode::Split, + grid_mode: GridMode::Pair, + sync_zoom: true, + expanded: false, + shown_layers: Vec::new(), + shared_cam: None, + layer_cams: HashMap::new(), + card_bounds: HashMap::new(), + hover: None, + hover_px: None, + selected_vertex: None, + drag: None, + down_pos: None, + optimistic: HashMap::new(), + optimistic_at: None, + last_rev: None, + hydrated_key: String::new(), + hydrated_board: None, + hydrated_draw: None, + note_open: false, + note_input: None, + focus: None, + } + } +} + +impl State { + pub fn reset(&mut self) { + self.shown_layers.clear(); + self.shared_cam = None; + self.layer_cams.clear(); + self.card_bounds.clear(); + self.hover = None; + self.hover_px = None; + self.selected_vertex = None; + self.drag = None; + self.down_pos = None; + self.optimistic.clear(); + self.optimistic_at = None; + self.last_rev = None; + self.hydrated_key.clear(); + self.hydrated_board = None; + self.hydrated_draw = None; + self.note_open = false; + self.note_input = None; + } + + pub fn fit_all(&mut self) { + self.shared_cam = None; + self.layer_cams.clear(); + } +} + +pub fn parse_hex_rgb(c: &str, fallback: u32) -> u32 { + let trimmed = c.trim().trim_start_matches('#'); + if trimmed.is_empty() { + return fallback; + } + u32::from_str_radix(trimmed, 16).unwrap_or(fallback) +} + +fn stable_hash(s: &str) -> usize { + let mut h: u32 = 2166136261; + for b in s.bytes() { + h ^= b as u32; + h = h.wrapping_mul(16777619); + } + h as usize +} + +/// Distinct semantic rail colors for power planes (keeps explicit non-default hex when set). +pub fn rail_color(net: &str, fallback: &str) -> u32 { + let lower = fallback.trim().to_ascii_lowercase(); + if !lower.is_empty() && lower != "#5a7a9a" && lower != "#8a8a8a" { + return parse_hex_rgb(fallback, 0x5a7a9a); + } + let up = net.to_ascii_uppercase(); + if up.contains("3V3A") || up.contains("AVDD") || up.contains("VDDA") { + return 0x38bdf8; + } + if up.contains("1V8") || up.contains("1.8V") { + return 0xc084fc; + } + if up.contains("2V5") || up.contains("2.5V") { + return 0xa3e635; + } + if up.contains("3V3") || up.contains("3.3V") || up.contains("VCC") { + return 0xf59e0b; + } + if up.contains("5V") || up.starts_with("+5") { + return 0xef4444; + } + if up.contains("12V") || up.contains("24V") { + return 0xf97316; + } + if up.contains("VBAT") || up.contains("VIN") { + return 0xec4899; + } + if up.contains("GND") { + return 0x2dd4bf; + } + RAIL_PALETTE[stable_hash(&up) % RAIL_PALETTE.len()] +} + +/// High-contrast signal corridor colors (keeps explicit non-default hex when set). +pub fn bus_color(name: &str, fallback: &str) -> u32 { + let lower = fallback.trim().to_ascii_lowercase(); + if !lower.is_empty() && lower != "#8a8a8a" { + return parse_hex_rgb(fallback, 0x14b8a6); + } + BUS_PALETTE[stable_hash(name) % BUS_PALETTE.len()] +} + +pub fn pts_from_val(v: &Value) -> Vec<[f64; 2]> { + v.as_array() + .into_iter() + .flatten() + .filter_map(|p| Some([p[0].as_f64()?, p[1].as_f64()?])) + .collect() +} + +pub fn pts_to_val(pts: &[[f64; 2]]) -> Value { + let arr: Vec = pts + .iter() + .map(|[x, y]| json!([(x * 1000.0).round() / 1000.0, (y * 1000.0).round() / 1000.0])) + .collect(); + Value::Array(arr) +} + +/// Exact arc-length 50% midpoint of a multi-segment polyline (for net-count badge placement). +pub fn polyline_midpoint(pts: &[[f64; 2]]) -> Option<[f64; 2]> { + if pts.is_empty() { + return None; + } + if pts.len() == 1 { + return Some(pts[0]); + } + let mut total = 0.0f64; + for w in pts.windows(2) { + total += (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]); + } + if total < 1e-6 { + return Some(pts[0]); + } + let target = total * 0.5; + let mut acc = 0.0; + for w in pts.windows(2) { + let len = (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]); + if acc + len >= target && len > 1e-9 { + let t = (target - acc) / len; + return Some([ + w[0][0] + (w[1][0] - w[0][0]) * t, + w[0][1] + (w[1][1] - w[0][1]) * t, + ]); + } + acc += len; + } + pts.last().copied() +} + +pub fn insert_vertex(pts: &[[f64; 2]], seg_idx: usize, pos: [f64; 2], closed: bool) -> Vec<[f64; 2]> { + let mut out = pts.to_vec(); + if out.is_empty() { + return vec![pos]; + } + let at = if closed && seg_idx + 1 >= out.len() { + out.len() + } else { + (seg_idx + 1).min(out.len()) + }; + out.insert(at, pos); + out +} + +pub fn remove_vertex(pts: &[[f64; 2]], idx: usize, closed: bool) -> Option> { + let min_pts = if closed { 3 } else { 2 }; + if pts.len() <= min_pts || idx >= pts.len() { + return None; + } + let mut out = pts.to_vec(); + out.remove(idx); + Some(out) +} + +fn dist_to_segment_sq(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32) -> f32 { + let dx = bx - ax; + let dy = by - ay; + let len_sq = dx * dx + dy * dy; + if len_sq < 1e-6 { + let ex = px - ax; + let ey = py - ay; + return ex * ex + ey * ey; + } + let t = (((px - ax) * dx + (py - ay) * dy) / len_sq).clamp(0.0, 1.0); + let cx = ax + t * dx; + let cy = ay + t * dy; + let ex = px - cx; + let ey = py - cy; + ex * ex + ey * ey +} + +fn point_in_ring(x: f64, y: f64, ring: &[[f64; 2]]) -> bool { + if ring.len() < 3 { + return false; + } + let mut inside = false; + let mut j = ring.len() - 1; + for i in 0..ring.len() { + let (xi, yi) = (ring[i][0], ring[i][1]); + let (xj, yj) = (ring[j][0], ring[j][1]); + let intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / ((yj - yi) + 1e-12) + xi); + if intersect { + inside = !inside; + } + j = i; + } + inside +} + +fn band_stroke_px(width_mm: f64, scale: f32) -> f32 { + ((width_mm as f32) * scale).clamp(5.0, 32.0) +} + +/// Priority hit-test on a layer canvas: Vertex > Midpoint > Band > Region (respecting polygon holes). +pub fn hit_test( + bands: &[Value], + regions: &[Value], + layer: &str, + selected_id: Option<&str>, + cam: &Camera, + w: f32, + h: f32, + mx: f32, + my: f32, +) -> Option { + // 1 & 2: Handles for currently selected unlocked item on this layer + if let Some(sel) = selected_id { + for b in bands.iter().filter(|b| b["layer"] == layer && b["id"] == sel) { + if b["locked"] != true { + let pts = pts_from_val(&b["path"]); + for (i, p) in pts.iter().enumerate() { + let (vx, vy) = cam.to_px(p[0] as f32, p[1] as f32, w, h); + if (mx - vx).hypot(my - vy) <= 9.5 { + return Some(Hit::Vertex { id: sel.to_string(), is_plane: false, idx: i }); + } + } + for (i, seg) in pts.windows(2).enumerate() { + let mid = [(seg[0][0] + seg[1][0]) * 0.5, (seg[0][1] + seg[1][1]) * 0.5]; + let (hx, hy) = cam.to_px(mid[0] as f32, mid[1] as f32, w, h); + if (mx - hx).hypot(my - hy) <= 8.5 { + return Some(Hit::Midpoint { id: sel.to_string(), is_plane: false, seg_idx: i, pos: mid }); + } + } + } + } + for r in regions.iter().filter(|r| r["layer"] == layer && r["id"] == sel) { + if r["locked"] != true { + let pts = pts_from_val(&r["outline"]); + for (i, p) in pts.iter().enumerate() { + let (vx, vy) = cam.to_px(p[0] as f32, p[1] as f32, w, h); + if (mx - vx).hypot(my - vy) <= 9.5 { + return Some(Hit::Vertex { id: sel.to_string(), is_plane: true, idx: i }); + } + } + let n = pts.len(); + if n >= 3 { + for i in 0..n { + let a = pts[i]; + let b = pts[(i + 1) % n]; + let mid = [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]; + let (hx, hy) = cam.to_px(mid[0] as f32, mid[1] as f32, w, h); + if (mx - hx).hypot(my - hy) <= 8.5 { + return Some(Hit::Midpoint { id: sel.to_string(), is_plane: true, seg_idx: i, pos: mid }); + } + } + } + } + } + } + + // 3: Bands on this layer (reverse order so top-painted wins) + let mut best_band: Option<(f32, String)> = None; + for b in bands.iter().filter(|b| b["layer"] == layer) { + let pts = pts_from_val(&b["path"]); + if pts.len() < 2 { + continue; + } + let thresh = (band_stroke_px(b["width"].as_f64().unwrap_or(1.5), cam.scale) * 0.5 + 3.0).max(7.0); + let mut min_d2 = f32::MAX; + for wseg in pts.windows(2) { + let (ax, ay) = cam.to_px(wseg[0][0] as f32, wseg[0][1] as f32, w, h); + let (bx, by) = cam.to_px(wseg[1][0] as f32, wseg[1][1] as f32, w, h); + min_d2 = min_d2.min(dist_to_segment_sq(mx, my, ax, ay, bx, by)); + } + let d = min_d2.sqrt(); + if d <= thresh && best_band.as_ref().map_or(true, |(bd, _)| d <= *bd) { + if let Some(id) = b["id"].as_str() { + best_band = Some((d, id.to_string())); + } + } + } + if let Some((_, id)) = best_band { + return Some(Hit::Band { id }); + } + + // 4: Regions on this layer (reverse order; exclude holes) + let (wx, wy) = cam.to_world(mx, my, w, h); + let (wx, wy) = (wx as f64, wy as f64); + for r in regions.iter().filter(|r| r["layer"] == layer).rev() { + let outer = pts_from_val(&r["outline"]); + if !point_in_ring(wx, wy, &outer) { + continue; + } + let in_hole = r["holes"] + .as_array() + .into_iter() + .flatten() + .any(|h| point_in_ring(wx, wy, &pts_from_val(h))); + if !in_hole { + if let Some(id) = r["id"].as_str() { + return Some(Hit::Region { id: id.to_string() }); + } + } + } + None +} + +/// Default 2-layer pair: primary signal layer (most corridors) + primary power layer (most planes). +pub fn default_layer_pair(layers: &[Value]) -> Vec { + let mut best_sig: Option<(usize, String)> = None; + let mut best_pwr: Option<(usize, String)> = None; + let mut all_names: Vec = Vec::new(); + for l in layers { + let name = l["layer"].as_str().unwrap_or("").to_string(); + if name.is_empty() { + continue; + } + all_names.push(name.clone()); + let items = l["items"].as_array().cloned().unwrap_or_default(); + let cor_n = items.iter().filter(|i| i["kind"] == "corridor").count(); + let pln_n = items.iter().filter(|i| i["kind"] == "plane").count(); + let role = l["role"].as_str().unwrap_or(""); + if (cor_n > 0 || role == "signal") && best_sig.as_ref().map_or(true, |(c, _)| cor_n > *c) { + best_sig = Some((cor_n, name.clone())); + } + if (pln_n > 0 || role == "power" || role == "plane") && best_pwr.as_ref().map_or(true, |(p, _)| pln_n > *p) { + best_pwr = Some((pln_n, name)); + } + } + let mut out = Vec::new(); + if let Some((_, s)) = best_sig { + out.push(s); + } + if let Some((_, p)) = best_pwr { + if !out.contains(&p) { + out.push(p); + } + } + for n in all_names { + if out.len() >= 2 { + break; + } + if !out.contains(&n) { + out.push(n); + } + } + out +} + +/// Greedy screen-space collision-free placement of component refdes labels. +pub fn layout_labels(parts: &[Value], cam: &Camera, w: f32, h: f32, pinned: &[&str]) -> Vec { + let pin_set: HashSet<&str> = pinned.iter().copied().collect(); + struct Cand<'a> { + r: &'a str, + cx: f32, + cy: f32, + box_w: f32, + box_h: f32, + score: f32, + } + let mut cands: Vec> = Vec::new(); + for p in parts { + let r = p["r"].as_str().unwrap_or(""); + let b = match p["b"].as_array() { + Some(a) if a.len() == 4 => [ + a[0].as_f64().unwrap_or(0.0) as f32, + a[1].as_f64().unwrap_or(0.0) as f32, + a[2].as_f64().unwrap_or(0.0) as f32, + a[3].as_f64().unwrap_or(0.0) as f32, + ], + _ => continue, + }; + if r.is_empty() { + continue; + } + let (x0, y0) = cam.to_px(b[0], b[1], w, h); + let (x1, y1) = cam.to_px(b[2], b[3], w, h); + let bw = (x1 - x0).abs(); + let bh = (y1 - y0).abs(); + if bw < 13.0 || bh < 9.0 { + continue; + } + let cx = (x0 + x1) * 0.5; + let cy = (y0 + y1) * 0.5; + if cx < 8.0 || cx > w - 8.0 || cy < 8.0 || cy > h - 8.0 { + continue; + } + let is_pin = pin_set.contains(r); + let area = bw * bh; + let score = area + if is_pin { 10_000.0 } else { 0.0 }; + let tw = (r.len() as f32) * 5.8 + 4.0; + let th = 11.0; + cands.push(Cand { r, cx, cy, box_w: tw, box_h: th, score }); + } + cands.sort_by(|a, b| b.score.total_cmp(&a.score)); + + let mut placed_boxes: Vec<[f32; 4]> = Vec::new(); + let mut out = Vec::new(); + for c in cands { + let rect = [ + c.cx - c.box_w * 0.5, + c.cy - c.box_h * 0.5, + c.cx + c.box_w * 0.5, + c.cy + c.box_h * 0.5, + ]; + let overlaps = placed_boxes + .iter() + .any(|o| !(rect[2] <= o[0] || rect[0] >= o[2] || rect[3] <= o[1] || rect[1] >= o[3])); + if !overlaps { + placed_boxes.push(rect); + out.push(PlacedLabel { text: c.r.to_string(), cx: c.cx, cy: c.cy }); + } + } + out +} + +pub fn merge_optimistic_into_draw(draw: &Value, optimistic: &HashMap) -> Value { + if optimistic.is_empty() { + return draw.clone(); + } + let mut out = draw.clone(); + for key in ["bands", "regions"] { + if let Some(arr) = out[key].as_array_mut() { + for item in arr.iter_mut() { + if let Some(id) = item["id"].as_str() { + if let Some(patch) = optimistic.get(id) { + if let Some(obj) = patch.as_object() { + for (k, v) in obj { + item[k] = v.clone(); + } + if item["state"] == "proposed" { + item["state"] = json!("edited"); + } + item["edited"] = json!(true); + } + } + } + } + } + } + out +} + +pub fn merge_optimistic_into_layers(layers: &Value, optimistic: &HashMap) -> Value { + if optimistic.is_empty() { + return layers.clone(); + } + let mut arr = layers.as_array().cloned().unwrap_or_default(); + let mut moved: Vec<(String, Value)> = Vec::new(); + for l in arr.iter_mut() { + let lname = l["layer"].as_str().unwrap_or("").to_string(); + if let Some(items) = l["items"].as_array_mut() { + items.retain_mut(|item| { + let id = item["id"].as_str().unwrap_or(""); + if let Some(patch) = optimistic.get(id) { + if let Some(w) = patch.get("width") { + item["width"] = w.clone(); + } + if let Some(lk) = patch.get("locked") { + item["locked"] = lk.clone(); + } + if item["state"] == "proposed" { + item["state"] = json!("edited"); + } + item["edited"] = json!(true); + if let Some(nl) = patch["layer"].as_str() { + if nl != lname { + moved.push((nl.to_string(), item.clone())); + return false; + } + } + } + true + }); + } + } + for (target, item) in moved { + if let Some(l) = arr.iter_mut().find(|l| l["layer"] == target) { + if let Some(items) = l["items"].as_array_mut() { + items.push(item); + } + } + } + Value::Array(arr) +} + +pub fn resolved_board_and_draw(app: &Backplane, d: &Value) -> (Value, Value) { + let ui = &app.screens.mgmt.plan_ui; + let pro = &app.screens.mgmt.project; + let rev = d["revision"].as_u64().unwrap_or(0); + let key = format!("{pro}:{rev}"); + let use_hyd = ui.hydrated_key == key; + let board = if use_hyd { + ui.hydrated_board.clone().unwrap_or_else(|| d["board"].clone()) + } else { + d["board"].clone() + }; + let raw_draw = if use_hyd { + ui.hydrated_draw.clone().unwrap_or_else(|| d["draw"].clone()) + } else { + d["draw"].clone() + }; + (board, merge_optimistic_into_draw(&raw_draw, &ui.optimistic)) +} + +pub fn board_answered(app: &mut Backplane, reply: &Value, cx: &mut Context) { + let ui = &mut app.screens.mgmt.plan_ui; + let panel = &reply["panel"]; + if panel.is_null() { + return; + } + let rev = panel["revision"].as_u64().unwrap_or(0); + ui.hydrated_key = format!("{}:{rev}", app.screens.mgmt.project); + ui.hydrated_board = Some(panel["board"].clone()); + ui.hydrated_draw = Some(panel["draw"].clone()); + cx.notify(); +} + +pub fn sync_revision_and_hydrate(app: &mut Backplane, d: &Value) { + let rev = d["revision"].as_u64(); + let pro = app.screens.mgmt.project.clone(); + let ui = &mut app.screens.mgmt.plan_ui; + if ui.last_rev != rev { + ui.last_rev = rev; + ui.optimistic.clear(); + ui.optimistic_at = None; + } else if let Some(at) = ui.optimistic_at { + if at.elapsed() > Duration::from_secs(3) { + ui.optimistic.clear(); + ui.optimistic_at = None; + } + } + let key = format!("{pro}:{}", rev.unwrap_or(0)); + if d["board_trimmed"] == true && ui.hydrated_key != key && !pro.is_empty() { + ui.hydrated_key = key; + let _ = app.tx.try_send(Command::Ask("plan.get".into(), json!({"pro": pro, "board": true}), BOARD_TAG)); + } +} + +pub fn apply_optimistic(app: &mut Backplane, id: &str, patch: Value) { + let ui = &mut app.screens.mgmt.plan_ui; + let entry = ui.optimistic.entry(id.to_string()).or_insert_with(|| json!({})); + if let (Some(dst), Some(src)) = (entry.as_object_mut(), patch.as_object()) { + for (k, v) in src { + dst.insert(k.clone(), v.clone()); + } + } + ui.optimistic_at = Some(Instant::now()); +} + +pub fn commit_item_fields(app: &mut Backplane, id: &str, fields: Value, cx: &mut Context) { + apply_optimistic(app, id, fields.clone()); + mgmt_plan::send(app, "plan.update", json!({"ops": [{"op": "set", "id": id, "fields": fields}]}), cx); +} + +fn board_bbox_f32(board: &Value) -> [f32; 4] { + let bb = &board["bbox"]; + let x0 = bb[0].as_f64().unwrap_or(0.0) as f32; + let y0 = bb[1].as_f64().unwrap_or(0.0) as f32; + let x1 = bb[2].as_f64().unwrap_or(100.0) as f32; + let y1 = bb[3].as_f64().unwrap_or(70.0) as f32; + if (x1 - x0).abs() < 0.5 || (y1 - y0).abs() < 0.5 { + [0.0, 0.0, 100.0, 70.0] + } else { + [x0, y0, x1, y1] + } +} + +fn alpha_col(rgb_hex: u32, alpha: u32) -> Hsla { + rgba((rgb_hex << 8) | (alpha & 0xff)).into() +} + +fn band_alphas(state: &str, selected: bool, hovered: bool) -> (u32, u32, u32, bool) { + let (mut glow, mut body, mut core, bad) = match state { + "approved" | "routing" => (0x2a, 0x82, 0xe8, false), + "edited" => (0x34, 0x90, 0xf2, false), + "routed" | "verified" => (0x16, 0x42, 0x96, false), + "rejected" | "failed" => (0x0c, 0x20, 0x44, false), + "blocked" => (0x2e, 0x7a, 0xe0, true), + _ => (0x24, 0x72, 0xd8, false), + }; + if selected { + glow = (glow + 0x18).min(0x58); + body = (body + 0x1e).min(0xb4); + core = 0xff; + } else if hovered { + glow = (glow + 0x0e).min(0x48); + body = (body + 0x12).min(0xa0); + } + (glow, body, core, bad) +} + +fn region_alphas(state: &str, selected: bool, hovered: bool) -> (u32, u32, bool) { + let (mut fill_a, mut edge_a, bad) = match state { + "approved" | "routing" => (0x5c, 0xe8, false), + "edited" => (0x62, 0xf2, false), + "routed" | "verified" => (0x28, 0x8a, false), + "rejected" | "failed" => (0x14, 0x45, false), + "blocked" => (0x50, 0xf0, true), + _ => (0x46, 0xd4, false), + }; + if selected { + fill_a = (fill_a + 0x1e).min(0x88); + edge_a = 0xff; + } else if hovered { + fill_a = (fill_a + 0x10).min(0x74); + edge_a = (edge_a + 0x18).min(0xff); + } + (fill_a, edge_a, bad) +} + +fn paint_shaped_text( + window: &mut Window, + cx: &mut App, + text: &str, + size_px: f32, + color: Hsla, + center_x: f32, + center_y: f32, + bold: bool, +) { + if text.is_empty() { + return; + } + let mut font = mono_font(); + if bold { + font.weight = FontWeight::BOLD; + } + let run = TextRun { + len: text.len(), + font, + color, + background_color: None, + underline: None, + strikethrough: None, + }; + let shaped = window + .text_system() + .shape_line(SharedString::from(text.to_string()), px(size_px), &[run], None); + let x = center_x - f32::from(shaped.width) * 0.5; + let y = center_y - size_px * 0.56; + let _ = shaped.paint(point(px(x), px(y)), px(size_px * 1.25), window, cx); +} + +#[allow(clippy::too_many_arguments)] +fn paint_layer_scene( + window: &mut Window, + cx: &mut App, + bounds: Bounds, + layer: &str, + board: &Value, + draw: &Value, + cam: &Camera, + selected_id: Option<&str>, + selected_vertex: Option<(&str, usize)>, + hover: Option<&Hit>, +) { + let w = f32::from(bounds.size.width).max(1.0); + let h = f32::from(bounds.size.height).max(1.0); + let ox = f32::from(bounds.origin.x); + let oy = f32::from(bounds.origin.y); + let pt = |wx: f32, wy: f32| { + let (x, y) = cam.to_px(wx, wy, w, h); + point(px(ox + x), px(oy + y)) + }; + + window.with_content_mask(Some(ContentMask { bounds }), |window| { + // 1. Dark PCB substrate background + window.paint_quad(fill(bounds, rgb(SUBSTRATE_BG))); + + // 2. Board interior fill (#16201d) from Edge.Cuts outline (or bbox fallback) + let outline_polys: Vec> = board["outline"] + .as_array() + .into_iter() + .flatten() + .map(pts_from_val) + .filter(|p| p.len() >= 3) + .collect(); + if !outline_polys.is_empty() { + let mut pb = PathBuilder::fill().with_style(PathStyle::Fill(gpui::FillOptions::even_odd().with_tolerance(0.05))); + for poly in &outline_polys { + for (i, p) in poly.iter().enumerate() { + let q = pt(p[0] as f32, p[1] as f32); + if i == 0 { pb.move_to(q); } else { pb.line_to(q); } + } + pb.close(); + } + if let Ok(path) = pb.build() { + window.paint_path(path, rgb(BOARD_FILL)); + } + } else { + let bb = board_bbox_f32(board); + let p0 = cam.to_px(bb[0], bb[1], w, h); + let p1 = cam.to_px(bb[2], bb[3], w, h); + let rect = Bounds::new(point(px(ox + p0.0), px(oy + p0.1)), size(px((p1.0 - p0.0).max(1.0)), px((p1.1 - p0.1).max(1.0)))); + window.paint_quad(fill(rect, rgb(BOARD_FILL))); + } + + // 3. Power plane pours (on this layer, under parts & Edge.Cuts) + let regions: Vec<&Value> = draw["regions"] + .as_array() + .into_iter() + .flatten() + .filter(|r| r["layer"] == layer) + .collect(); + for r in ®ions { + let id = r["id"].as_str().unwrap_or(""); + let outer = pts_from_val(&r["outline"]); + if outer.len() < 3 { + continue; + } + let sel = selected_id == Some(id); + let hov = hover.map_or(false, |x| x.item_id() == id); + let (fa, oa, bad) = region_alphas(r["state"].as_str().unwrap_or("proposed"), sel, hov); + let col = rail_color(r["net"].as_str().unwrap_or(""), r["color"].as_str().unwrap_or("")); + + let mut fpb = PathBuilder::fill().with_style(PathStyle::Fill(gpui::FillOptions::even_odd().with_tolerance(0.05))); + for (i, p) in outer.iter().enumerate() { + let q = pt(p[0] as f32, p[1] as f32); + if i == 0 { fpb.move_to(q); } else { fpb.line_to(q); } + } + fpb.close(); + for hole_v in r["holes"].as_array().into_iter().flatten() { + let hole = pts_from_val(hole_v); + if hole.len() >= 3 { + for (i, p) in hole.iter().enumerate() { + let q = pt(p[0] as f32, p[1] as f32); + if i == 0 { fpb.move_to(q); } else { fpb.line_to(q); } + } + fpb.close(); + } + } + if let Ok(path) = fpb.build() { + window.paint_path(path, alpha_col(col, fa)); + } + + let sw = if sel || bad { 2.0 } else { 1.25 }; + let mut spb = PathBuilder::stroke(px(sw)).with_style(PathStyle::Stroke( + gpui::StrokeOptions::default() + .with_line_width(sw) + .with_line_join(LineJoin::Round) + .with_tolerance(0.05), + )); + for (i, p) in outer.iter().chain(outer.first()).enumerate() { + let q = pt(p[0] as f32, p[1] as f32); + if i == 0 { spb.move_to(q); } else { spb.line_to(q); } + } + if let Ok(path) = spb.build() { + let scol = if bad { alpha_col(BAD_RED, 0xf2) } else if sel { alpha_col(0xffffff, 0xe8) } else { alpha_col(col, oa) }; + window.paint_path(path, scol); + } + } + + // 4. Crisp Edge.Cuts outline (#d4e0db) + if !outline_polys.is_empty() { + let mut epb = PathBuilder::stroke(px(1.25)).with_style(PathStyle::Stroke( + gpui::StrokeOptions::default() + .with_line_width(1.25) + .with_line_cap(LineCap::Round) + .with_line_join(LineJoin::Round) + .with_tolerance(0.05), + )); + for poly in &outline_polys { + for (i, p) in poly.iter().chain(poly.first()).enumerate() { + let q = pt(p[0] as f32, p[1] as f32); + if i == 0 { epb.move_to(q); } else { epb.line_to(q); } + } + } + if let Ok(path) = epb.build() { + window.paint_path(path, alpha_col(EDGE_STROKE, 0xe8)); + } + } else { + let bb = board_bbox_f32(board); + let mut epb = PathBuilder::stroke(px(1.25)); + let corners = [(bb[0], bb[1]), (bb[2], bb[1]), (bb[2], bb[3]), (bb[0], bb[3]), (bb[0], bb[1])]; + for (i, (x, y)) in corners.into_iter().enumerate() { + let q = pt(x, y); + if i == 0 { epb.move_to(q); } else { epb.line_to(q); } + } + if let Ok(path) = epb.build() { + window.paint_path(path, alpha_col(EDGE_STROKE, 0xe8)); + } + } + + // 5. Component courtyard/body outlines (solid top, dashed bottom/overhang) + let parts = board["parts"].as_array().cloned().unwrap_or_default(); + let mut solid_pb = PathBuilder::stroke(px(0.85)); + let mut dash_pb = PathBuilder::stroke(px(0.95)).dash_array(&[px(4.0), px(3.0)]); + let (mut has_solid, mut has_dash) = (false, false); + for p in &parts { + let Some(arr) = p["b"].as_array().filter(|a| a.len() == 4) else { continue }; + let (x0, y0) = (arr[0].as_f64().unwrap_or(0.0) as f32, arr[1].as_f64().unwrap_or(0.0) as f32); + let (x1, y1) = (arr[2].as_f64().unwrap_or(0.0) as f32, arr[3].as_f64().unwrap_or(0.0) as f32); + let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]; + let target = if p["o"] == true { has_dash = true; &mut dash_pb } else { has_solid = true; &mut solid_pb }; + for (i, (cx_w, cy_w)) in corners.into_iter().enumerate() { + let q = pt(cx_w, cy_w); + if i == 0 { target.move_to(q); } else { target.line_to(q); } + } + } + if has_solid { + if let Ok(path) = solid_pb.build() { window.paint_path(path, alpha_col(PART_STROKE, 0xb8)); } + } + if has_dash { + if let Ok(path) = dash_pb.build() { window.paint_path(path, alpha_col(PART_OVERHANG, 0xd8)); } + } + + // 6. Collision-free component refdes labels + let bands: Vec<&Value> = draw["bands"] + .as_array() + .into_iter() + .flatten() + .filter(|b| b["layer"] == layer) + .collect(); + let mut pinned_refs: Vec<&str> = Vec::new(); + for b in &bands { + for k in ["from", "to"] { + for r in b[k].as_array().into_iter().flatten().filter_map(Value::as_str) { + pinned_refs.push(r); + } + } + } + for lbl in layout_labels(&parts, cam, w, h, &pinned_refs) { + paint_shaped_text(window, cx, &lbl.text, 9.5, alpha_col(REFDES_COLOR, 0xdd), ox + lbl.cx, oy + lbl.cy, false); + } + + // 7. Faint color-tinted signal ratsnest guides + for b in &bands { + let guides = b["guides"].as_array().into_iter().flatten().collect::>(); + if guides.is_empty() { + continue; + } + let id = b["id"].as_str().unwrap_or(""); + let active = selected_id == Some(id) || hover.map_or(false, |x| x.item_id() == id); + let col = bus_color(b["name"].as_str().unwrap_or(id), b["color"].as_str().unwrap_or("")); + let mut gpb = PathBuilder::stroke(px(if active { 1.0 } else { 0.7 })); + let mut any = false; + for seg in guides { + if let (Some(x1), Some(y1), Some(x2), Some(y2)) = (seg[0].as_f64(), seg[1].as_f64(), seg[2].as_f64(), seg[3].as_f64()) { + gpb.move_to(pt(x1 as f32, y1 as f32)); + gpb.line_to(pt(x2 as f32, y2 as f32)); + any = true; + } + } + if any { + if let Ok(path) = gpb.build() { + window.paint_path(path, alpha_col(col, if active { 0x62 } else { 0x2c })); + } + } + } + + // 8. Multi-pass rounded-cap signal bus corridors + diamond vias + net-count pills + for b in &bands { + let pts = pts_from_val(&b["path"]); + if pts.len() < 2 { + continue; + } + let id = b["id"].as_str().unwrap_or(""); + let sel = selected_id == Some(id); + let hov = hover.map_or(false, |x| x.item_id() == id); + let stt = b["state"].as_str().unwrap_or("proposed"); + let (glow_a, body_a, core_a, bad) = band_alphas(stt, sel, hov); + let col = bus_color(b["name"].as_str().unwrap_or(id), b["color"].as_str().unwrap_or("")); + let wpx = band_stroke_px(b["width"].as_f64().unwrap_or(1.5), cam.scale); + + let stroke_poly = |sw: f32| { + let mut pb = PathBuilder::stroke(px(sw)).with_style(PathStyle::Stroke( + gpui::StrokeOptions::default() + .with_line_width(sw) + .with_line_cap(LineCap::Round) + .with_line_join(LineJoin::Round) + .with_tolerance(0.05), + )); + for (i, p) in pts.iter().enumerate() { + let q = pt(p[0] as f32, p[1] as f32); + if i == 0 { pb.move_to(q); } else { pb.line_to(q); } + } + pb.build().ok() + }; + + // Pass 1: outer halo glow + if let Some(p) = stroke_poly(wpx + 6.0) { + window.paint_path(p, alpha_col(col, glow_a)); + } + // Optional blocked / selected outer border + if bad || sel { + if let Some(p) = stroke_poly(wpx + 2.5) { + window.paint_path(p, alpha_col(if bad { BAD_RED } else { 0xffffff }, if bad { 0xe8 } else { 0xb8 })); + } + } + // Pass 2: translucent corridor envelope + if let Some(p) = stroke_poly(wpx) { + window.paint_path(p, alpha_col(col, body_a)); + } + // Pass 3: crisp bright spine + if let Some(p) = stroke_poly((wpx * 0.34).clamp(1.8, 5.0)) { + window.paint_path(p, alpha_col(col, core_a)); + } + + // 9. Diamond via/escape markers + for via in b["vias"].as_array().into_iter().flatten() { + if let (Some(vx), Some(vy)) = (via[0].as_f64(), via[1].as_f64()) { + let (px_x, px_y) = cam.to_px(vx as f32, vy as f32, w, h); + let r = 4.2f32; + let dpts = [ + point(px(ox + px_x), px(oy + px_y - r)), + point(px(ox + px_x + r), px(oy + px_y)), + point(px(ox + px_x), px(oy + px_y + r)), + point(px(ox + px_x - r), px(oy + px_y)), + ]; + let mut fpb = PathBuilder::fill(); + for (i, q) in dpts.iter().enumerate() { + if i == 0 { fpb.move_to(*q); } else { fpb.line_to(*q); } + } + fpb.close(); + if let Ok(path) = fpb.build() { + window.paint_path(path, alpha_col(SUBSTRATE_BG, 0xf2)); + } + let mut spb = PathBuilder::stroke(px(1.5)); + for (i, q) in dpts.iter().chain(dpts.first()).enumerate() { + if i == 0 { spb.move_to(*q); } else { spb.line_to(*q); } + } + if let Ok(path) = spb.build() { + window.paint_path(path, alpha_col(if sel { 0xffffff } else { col }, 0xff)); + } + } + } + + // 10. Centered net-count pill at arc-length midpoint + let nets = b["nets"].as_u64().unwrap_or(0); + if nets > 0 { + if let Some(mid) = polyline_midpoint(&pts) { + let txt = nets.to_string(); + let (mx_px, my_px) = cam.to_px(mid[0] as f32, mid[1] as f32, w, h); + let pw = (txt.len() as f32 * 6.5 + 8.0).max(16.0); + let ph = 15.0f32; + let badge_bounds = Bounds::new( + point(px(ox + mx_px - pw * 0.5), px(oy + my_px - ph * 0.5)), + size(px(pw), px(ph)), + ); + window.paint_quad(gpui::quad( + badge_bounds, + px(0.), + alpha_col(BADGE_BG, 0xf2), + px(1.2), + alpha_col(if sel { 0xffffff } else { col }, 0xee), + BorderStyle::Solid, + )); + paint_shaped_text(window, cx, &txt, 10.0, alpha_col(BADGE_FG, 0xff), ox + mx_px, oy + my_px, true); + } + } + } + + // 11. Interactive vertex & midpoint handles on selected item (if unlocked) + if let Some(sel) = selected_id { + let paint_handles = |pts: &[[f64; 2]], closed: bool, window: &mut Window| { + let segs = if closed { pts.len() } else { pts.len().saturating_sub(1) }; + for i in 0..segs { + let a = pts[i]; + let b = pts[(i + 1) % pts.len()]; + let (mx_w, my_w) = ((a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5); + let (hx, hy) = cam.to_px(mx_w as f32, my_w as f32, w, h); + let is_hov = matches!(hover, Some(Hit::Midpoint { id, seg_idx, .. }) if id == sel && *seg_idx == i); + let s = if is_hov { 9.0f32 } else { 7.5f32 }; + let hb = Bounds::new(point(px(ox + hx - s * 0.5), px(oy + hy - s * 0.5)), size(px(s), px(s))); + window.paint_quad(gpui::quad( + hb, + px(0.), + alpha_col(BOARD_FILL, 0xe8), + px(1.0), + alpha_col(if is_hov { HANDLE_ACTIVE } else { 0x94a3b8 }, 0xee), + BorderStyle::Solid, + )); + } + for (i, p) in pts.iter().enumerate() { + let (vx, vy) = cam.to_px(p[0] as f32, p[1] as f32, w, h); + let is_sel_v = selected_vertex == Some((sel, i)); + let is_hov_v = matches!(hover, Some(Hit::Vertex { id, idx, .. }) if id == sel && *idx == i); + let s = if is_sel_v || is_hov_v { 9.5f32 } else { 7.5f32 }; + let vb = Bounds::new(point(px(ox + vx - s * 0.5), px(oy + vy - s * 0.5)), size(px(s), px(s))); + window.paint_quad(gpui::quad( + vb, + px(0.), + alpha_col(if is_sel_v || is_hov_v { HANDLE_ACTIVE } else { HANDLE_BG }, 0xff), + px(1.2), + alpha_col(SUBSTRATE_BG, 0xff), + BorderStyle::Solid, + )); + } + }; + for b in &bands { + if b["id"] == sel && b["locked"] != true { + paint_handles(&pts_from_val(&b["path"]), false, window); + } + } + for r in ®ions { + if r["id"] == sel && r["locked"] != true { + paint_handles(&pts_from_val(&r["outline"]), true, window); + } + } + } + + // 12. Subtle top-right hover HUD pill + if let Some(h_item) = hover { + let hid = h_item.item_id(); + let hud_txt = bands + .iter() + .find(|b| b["id"] == hid) + .map(|b| { + let name = b["name"].as_str().unwrap_or(hid); + let n = b["nets"].as_u64().unwrap_or(0); + let wd = b["width"].as_f64().unwrap_or(0.0); + format!("{name} · {n}n · {wd:.2}mm") // i18n-ok: compact metric hud + }) + .or_else(|| { + regions.iter().find(|r| r["id"] == hid).map(|r| { + let net = r["net"].as_str().unwrap_or(hid); + let refr = r["reference"].as_str().unwrap_or(""); + if refr.is_empty() { net.to_string() } else { format!("{net} · {refr}") } // i18n-ok: compact metric hud + }) + }); + if let Some(txt) = hud_txt { + let pw = (txt.len() as f32 * 6.0 + 12.0).max(48.0); + let hb = Bounds::new(point(px(ox + w - pw - 8.0), px(oy + 8.0)), size(px(pw), px(18.0))); + window.paint_quad(gpui::quad( + hb, + px(0.), + alpha_col(SUBSTRATE_BG, 0xee), + px(1.0), + alpha_col(PART_OVERHANG, 0xee), + BorderStyle::Solid, + )); + paint_shaped_text(window, cx, &txt, 10.0, alpha_col(BADGE_FG, 0xff), ox + w - pw * 0.5 - 8.0, oy + 17.0, false); + } + } + }); +} + +fn active_cam(ui: &State, layer: &str, bbox: [f32; 4], w: f32, h: f32) -> Camera { + let raw = if ui.sync_zoom { + ui.shared_cam + } else { + ui.layer_cams.get(layer).copied() + }; + match raw { + Some(c) if c.touched => c, + _ => Camera::fit(bbox, w, h, 14.0), + } +} + +fn set_cam(ui: &mut State, layer: &str, cam: Camera) { + if ui.sync_zoom { + ui.shared_cam = Some(cam); + } else { + ui.layer_cams.insert(layer.to_string(), cam); + } +} + +pub fn visible_layers(ui: &State, layers: &[Value]) -> Vec { + if layers.is_empty() { + return Vec::new(); + } + match ui.grid_mode { + GridMode::All => layers.to_vec(), + GridMode::Single => { + let target = ui + .shown_layers + .first() + .filter(|n| layers.iter().any(|l| l["layer"].as_str() == Some(n.as_str()))) + .cloned() + .or_else(|| default_layer_pair(layers).into_iter().next()) + .or_else(|| layers.first().and_then(|l| l["layer"].as_str().map(str::to_string))); + target + .and_then(|t| layers.iter().find(|l| l["layer"].as_str() == Some(t.as_str())).cloned()) + .into_iter() + .collect() + } + GridMode::Pair => { + let names: Vec = if !ui.shown_layers.is_empty() + && ui.shown_layers.iter().all(|n| layers.iter().any(|l| l["layer"].as_str() == Some(n.as_str()))) + { + ui.shown_layers.iter().take(2).cloned().collect() + } else { + default_layer_pair(layers) + }; + let mut out = Vec::new(); + for n in names { + if let Some(l) = layers.iter().find(|l| l["layer"].as_str() == Some(n.as_str())) { + out.push(l.clone()); + } + } + if out.is_empty() { + layers.iter().take(2).cloned().collect() + } else { + out + } + } + } +} + +pub fn pick_layer_in_grid(ui: &mut State, layer_name: String) { + if ui.grid_mode == GridMode::Single { + ui.shown_layers = vec![layer_name]; + } else if ui.grid_mode == GridMode::Pair { + if !ui.shown_layers.contains(&layer_name) { + if ui.shown_layers.len() >= 2 { + ui.shown_layers[1] = layer_name; + } else { + ui.shown_layers.push(layer_name); + } + } + } else { + ui.grid_mode = GridMode::Single; + ui.shown_layers = vec![layer_name]; + } +} + +fn layer_status_badge(l: &Value) -> (String, &'static str) { + let items = l["items"].as_array().map(|a| a.as_slice()).unwrap_or(&[]); + let any_blocked = items.iter().any(|i| matches!(i["state"].as_str(), Some("blocked" | "failed"))); + let any_routing = items.iter().any(|i| i["state"] == "routing"); + let any_awaiting = items.iter().any(|i| matches!(i["state"].as_str(), Some("proposed" | "edited"))); + let all_done = !items.is_empty() && items.iter().all(|i| matches!(i["state"].as_str(), Some("routed" | "verified"))); + let all_approved = !items.is_empty() && items.iter().all(|i| matches!(i["state"].as_str(), Some("approved" | "routed" | "verified"))); + if any_blocked { (trs("Blocked"), "bad") } + else if any_routing { (trs("Routing"), "accent") } + else if any_awaiting { (trs("Awaiting review"), "warn") } + else if all_done { (trs("Routed"), "ok") } + else if all_approved { (trs("Approved"), "accent") } + else { (trs("Empty"), "dim") } +} + +/// Interactive per-layer PCB floorplanner canvas grid view. +pub fn view(app: &mut Backplane, d: &Value, light: bool, cx: &mut Context) -> AnyElement { + let c = |n: &str| theme::color(light, n); + let (board, draw) = resolved_board_and_draw(app, d); + let layers_val = merge_optimistic_into_layers(&d["layers"], &app.screens.mgmt.plan_ui.optimistic); + let all_layers = layers_val.as_array().cloned().unwrap_or_default(); + let shown = visible_layers(&app.screens.mgmt.plan_ui, &all_layers); + + if app.screens.mgmt.plan_ui.focus.is_none() { + app.screens.mgmt.plan_ui.focus = Some(cx.focus_handle()); + } + let focus = app.screens.mgmt.plan_ui.focus.clone().unwrap(); + + let two_cols = app.screens.mgmt.panel_w >= SIDE_BY_SIDE_MIN_W && shown.len() > 1; + let bb = board_bbox_f32(&board); + let aspect = ((bb[3] - bb[1]).abs() / (bb[2] - bb[0]).abs().max(1.0)).clamp(0.45, 1.35); + let avail_card_w = if two_cols { + (app.screens.mgmt.panel_w - 28.0) * 0.5 + } else { + (app.screens.mgmt.panel_w - 18.0).max(240.0) + }; + let canvas_h = if app.screens.mgmt.plan_ui.view_mode == ViewMode::Canvas && shown.len() == 1 { + (avail_card_w * aspect).clamp(260.0, 480.0) + } else { + (avail_card_w * aspect).clamp(190.0, 340.0) + }; + + let selected_id = app.screens.mgmt.plan_sel.clone(); + let entity = cx.entity(); + + let mut cards: Vec = Vec::with_capacity(shown.len()); + for l in &shown { + let layer_name = l["layer"].as_str().unwrap_or("").to_string(); + let title = l["title"].as_str().filter(|s| !s.is_empty()).unwrap_or(&layer_name).to_string(); + let subtitle = l["subtitle"].as_str().filter(|s| !s.is_empty()).or_else(|| l["stackup"].as_str()).unwrap_or("").to_string(); + let (st_label, st_tone) = layer_status_badge(l); + let items = l["items"].as_array().cloned().unwrap_or_default(); + let has_awaiting = items.iter().any(|i| matches!(i["state"].as_str(), Some("proposed" | "edited"))); + let is_power = l["role"] == "power" || (!items.is_empty() && items.iter().all(|i| i["kind"] == "plane")); + + let ln_paint = layer_name.clone(); + let ln_down_l = layer_name.clone(); + let ln_down_r = layer_name.clone(); + let ln_move = layer_name.clone(); + let ln_up = layer_name.clone(); + let ln_wheel = layer_name.clone(); + let focus_down = focus.clone(); + let entity_paint = entity.clone(); + let board_c = board.clone(); + let draw_c = draw.clone(); + let bb_c = bb; + + let el = canvas(|b, _, _| b, move |_, b, window, cx| { + let snap = entity_paint.update(cx, |app, _| { + app.screens.mgmt.plan_ui.card_bounds.insert(ln_paint.clone(), b); + let ui = &app.screens.mgmt.plan_ui; + let w = f32::from(b.size.width).max(1.0); + let h = f32::from(b.size.height).max(1.0); + let cam = active_cam(ui, &ln_paint, bb_c, w, h); + let hov = ui.hover.as_ref().filter(|(l, _)| l == &ln_paint).map(|(_, h)| h.clone()); + let sv = ui.selected_vertex.clone(); + (cam, app.screens.mgmt.plan_sel.clone(), sv, hov) + }); + paint_layer_scene( + window, + cx, + b, + &ln_paint, + &board_c, + &draw_c, + &snap.0, + snap.1.as_deref(), + snap.2.as_ref().map(|(i, idx)| (i.as_str(), *idx)), + snap.3.as_ref(), + ); + }).size_full(); + + let ln_cursor = layer_name.clone(); + let canvas_box = div() + .id(SharedString::from(format!("plan-card-canvas-{layer_name}"))) + .w_full() + .h(px(canvas_h)) + .bg(rgb(SUBSTRATE_BG)) + .cursor(if app.screens.mgmt.plan_ui.hover.as_ref().map_or(false, |(l, h)| l == &ln_cursor && matches!(h, Hit::Vertex { .. } | Hit::Midpoint { .. })) { + CursorStyle::PointingHand + } else { + CursorStyle::Crosshair + }) + .child(el) + .on_mouse_down(MouseButton::Left, cx.listener(move |this, e: &MouseDownEvent, window, cx| { + window.focus(&focus_down); + handle_left_down(this, &ln_down_l, e, cx); + })) + .on_mouse_down(MouseButton::Right, cx.listener(move |this, e: &MouseDownEvent, _, cx| { + handle_right_down(this, &ln_down_r, e, cx); + })) + .on_mouse_move(cx.listener(move |this, e: &MouseMoveEvent, _, cx| { + handle_mouse_move(this, &ln_move, e, cx); + })) + .on_mouse_up(MouseButton::Left, cx.listener(move |this, e: &MouseUpEvent, _, cx| { + handle_left_up(this, &ln_up, e, cx); + })) + .on_mouse_up_out(MouseButton::Left, cx.listener(|this, _, _, cx| { + if let Some((_l, DragAction::Vertex { id, is_plane, .. })) = this.screens.mgmt.plan_ui.drag.take() { + commit_optimistic_geometry(this, &id, is_plane, cx); + } + this.screens.mgmt.plan_ui.drag = None; + this.screens.mgmt.plan_ui.down_pos = None; + cx.notify(); + })) + .on_scroll_wheel(cx.listener(move |this, e: &ScrollWheelEvent, _, cx| { + handle_wheel(this, &ln_wheel, e, cx); + })); + + let ln_ok = layer_name.clone(); + let ln_no = layer_name.clone(); + let mut head = div() + .flex_shrink_0() + .flex() + .flex_col() + .gap(px(2.)) + .px_2() + .py(px(5.)) + .bg(c("panel")) + .border_b_1() + .border_color(c("line")) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(div().w(px(3.)).h(px(14.)).bg(c(if is_power { "warn" } else { "accent" }))) + .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().font_weight(FontWeight::BOLD).text_size(crate::scale::tpx(12.)).text_color(c("text")).child(title)) + .child(div().px_1().border_1().border_color(c(st_tone)).bg(c("raise")).text_size(crate::scale::tpx(10.)).text_color(c(st_tone)).child(st_label)) + .when(has_awaiting, |hdr| { + let lo = ln_ok.clone(); + let ln = ln_no.clone(); + hdr.child(small_btn(cx, light, format!("mgmt:plan:card-ok:{ln_ok}"), "✓".into(), false, move |a, cx| mgmt_plan::approve(a, &lo, &[], true, cx))) // i18n-ok: a mark + .child(small_btn(cx, light, format!("mgmt:plan:card-no:{ln_no}"), "✗".into(), false, move |a, cx| mgmt_plan::approve(a, &ln, &[], false, cx))) // i18n-ok: a mark + }), + ); + if !subtitle.is_empty() { + head = head.child(div().text_size(crate::scale::tpx(10.)).text_color(c("dim")).overflow_hidden().whitespace_nowrap().text_ellipsis().child(subtitle)); + } + + // Power rail legend footer for power layers + let mut card = div() + .flex_shrink_0() + .flex() + .flex_col() + .border_1() + .border_color(c("line")) + .bg(c("panel")) + .child(head) + .child(canvas_box); + + let regions_on_layer: Vec<&Value> = draw["regions"] + .as_array() + .into_iter() + .flatten() + .filter(|r| r["layer"] == layer_name) + .collect(); + if !regions_on_layer.is_empty() { + let mut legend = div() + .flex_shrink_0() + .flex() + .flex_wrap() + .items_center() + .gap(px(5.)) + .px_2() + .py(px(5.)) + .bg(c("panel")) + .border_t_1() + .border_color(c("line")); + for r in regions_on_layer { + let rid = r["id"].as_str().unwrap_or("").to_string(); + let net = r["net"].as_str().unwrap_or(&rid).to_string(); + let col = rail_color(&net, r["color"].as_str().unwrap_or("")); + let is_sel = selected_id.as_deref() == Some(rid.as_str()); + let rid_c = rid.clone(); + legend = legend.child( + div() + .id(SharedString::from(format!("plan-legend-{layer_name}-{rid}"))) + .flex() + .items_center() + .gap(px(4.)) + .px(px(5.)) + .py(px(2.)) + .cursor_pointer() + .border_1() + .border_color(if is_sel { c("accent") } else { c("line") }) + .bg(if is_sel { c("raise") } else { c("bg") }) + .hover(|s| s.bg(c("raise"))) + .child(div().size(px(8.)).bg(rgb(col))) + .child(div().text_size(crate::scale::tpx(10.)).font(mono_font()).text_color(c(if is_sel { "text" } else { "dim" })).child(net)) + .on_click(cx.listener(move |this, _, _, cx| { + this.screens.mgmt.plan_sel = Some(rid_c.clone()); + mgmt_plan::send(this, "plan.focus", json!({"id": rid_c}), cx); + })), + ); + } + card = card.child(legend); + } + + cards.push(card.into_any_element()); + } + + // Build 1-col or 2-col layout + let mut grid = div() + .id("plan-canvas-grid") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .p(px(6.)) + .flex() + .flex_col() + .gap(px(8.)); + + if two_cols { + let mut iter = cards.into_iter(); + while let Some(a) = iter.next() { + let mut row = div().w_full().flex().items_start().gap(px(8.)).child(div().flex_1().min_w_0().child(a)); + if let Some(b) = iter.next() { + row = row.child(div().flex_1().min_w_0().child(b)); + } else { + row = row.child(div().flex_1().min_w_0()); + } + grid = grid.child(row); + } + } else { + for card in cards { + grid = grid.child(card); + } + } + + div() + .id("plan-canvas-root") + .track_focus(&focus) + .key_context("PlanCanvas") // i18n-ok: key context id + .size_full() + .flex() + .flex_col() + .min_h_0() + .bg(c("bg")) + .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| { + handle_key_down(this, e, cx); + })) + .child(grid) + .into_any_element() +} + +fn small_btn(cx: &mut Context, light: bool, id: String, label: String, primary: bool, on: impl Fn(&mut Backplane, &mut Context) + 'static) -> AnyElement { + let c = |n: &str| theme::color(light, n); + div() + .id(SharedString::from(id)) + .h(crate::scale::tpx(18.)) + .px(px(6.)) + .flex() + .items_center() + .cursor_pointer() + .border_1() + .text_size(crate::scale::tpx(10.)) + .when(primary, |d| d.bg(c("accent")).border_color(c("accent")).text_color(c("on-accent"))) + .when(!primary, |d| d.bg(c("raise")).border_color(c("line")).text_color(c("text")).hover(|s| s.bg(c("line")))) + .child(label) + .on_click(cx.listener(move |this, _, _, cx| { on(this, cx); cx.notify(); })) + .into_any_element() +} + +fn canvas_hit_at(app: &Backplane, layer: &str, abs_x: f32, abs_y: f32) -> Option<(Bounds, Camera, Option, f32, f32)> { + let ui = &app.screens.mgmt.plan_ui; + let b = ui.card_bounds.get(layer).copied()?; + let w = f32::from(b.size.width).max(1.0); + let h = f32::from(b.size.height).max(1.0); + let lx = abs_x - f32::from(b.origin.x); + let ly = abs_y - f32::from(b.origin.y); + let d = app.screens.mgmt.data("plan"); + let (board, draw) = resolved_board_and_draw(app, &d); + let bb = board_bbox_f32(&board); + let cam = active_cam(ui, layer, bb, w, h); + let bands = draw["bands"].as_array().cloned().unwrap_or_default(); + let regions = draw["regions"].as_array().cloned().unwrap_or_default(); + let hit = hit_test(&bands, ®ions, layer, app.screens.mgmt.plan_sel.as_deref(), &cam, w, h, lx, ly); + Some((b, cam, hit, lx, ly)) +} + +fn handle_left_down(app: &mut Backplane, layer: &str, e: &MouseDownEvent, cx: &mut Context) { + let (ax, ay) = (f32::from(e.position.x), f32::from(e.position.y)); + let Some((b, cam, hit, lx, ly)) = canvas_hit_at(app, layer, ax, ay) else { return }; + app.screens.mgmt.plan_ui.down_pos = Some((ax, ay)); + let w = f32::from(b.size.width).max(1.0); + let h = f32::from(b.size.height).max(1.0); + + match hit { + Some(Hit::Vertex { id, is_plane, idx }) => { + app.screens.mgmt.plan_sel = Some(id.clone()); + app.screens.mgmt.plan_ui.selected_vertex = Some((id.clone(), idx)); + app.screens.mgmt.plan_ui.drag = Some((layer.to_string(), DragAction::Vertex { id, is_plane, idx })); + } + Some(Hit::Midpoint { id, is_plane, seg_idx, pos }) => { + let d = app.screens.mgmt.data("plan"); + let (_, draw) = resolved_board_and_draw(app, &d); + let pts = if is_plane { + draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == id).map(|r| pts_from_val(&r["outline"])).unwrap_or_default() + } else { + draw["bands"].as_array().into_iter().flatten().find(|b| b["id"] == id).map(|b| pts_from_val(&b["path"])).unwrap_or_default() + }; + let new_pts = insert_vertex(&pts, seg_idx, pos, is_plane); + let inserted_idx = if is_plane && seg_idx + 1 >= pts.len() { new_pts.len() - 1 } else { (seg_idx + 1).min(new_pts.len() - 1) }; + let field_key = if is_plane { "outline" } else { "path" }; + apply_optimistic(app, &id, json!({ field_key: pts_to_val(&new_pts) })); + app.screens.mgmt.plan_sel = Some(id.clone()); + app.screens.mgmt.plan_ui.selected_vertex = Some((id.clone(), inserted_idx)); + app.screens.mgmt.plan_ui.drag = Some((layer.to_string(), DragAction::Vertex { id, is_plane, idx: inserted_idx })); + } + Some(Hit::Band { id } | Hit::Region { id }) => { + app.screens.mgmt.plan_sel = Some(id.clone()); + app.screens.mgmt.plan_ui.selected_vertex = None; + app.screens.mgmt.plan_ui.drag = Some((layer.to_string(), DragAction::Pan { last_x: lx, last_y: ly })); + let _ = cam; let _ = w; let _ = h; + } + None => { + app.screens.mgmt.plan_ui.selected_vertex = None; + app.screens.mgmt.plan_ui.drag = Some((layer.to_string(), DragAction::Pan { last_x: lx, last_y: ly })); + } + } + cx.notify(); +} + +fn handle_right_down(app: &mut Backplane, layer: &str, e: &MouseDownEvent, cx: &mut Context) { + let (ax, ay) = (f32::from(e.position.x), f32::from(e.position.y)); + let Some((_b, _cam, Some(Hit::Vertex { id, is_plane, idx }), _, _)) = canvas_hit_at(app, layer, ax, ay) else { return }; + let d = app.screens.mgmt.data("plan"); + let (_, draw) = resolved_board_and_draw(app, &d); + let pts = if is_plane { + draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == id).map(|r| pts_from_val(&r["outline"])).unwrap_or_default() + } else { + draw["bands"].as_array().into_iter().flatten().find(|b| b["id"] == id).map(|b| pts_from_val(&b["path"])).unwrap_or_default() + }; + if let Some(new_pts) = remove_vertex(&pts, idx, is_plane) { + let key = if is_plane { "outline" } else { "path" }; + app.screens.mgmt.plan_ui.selected_vertex = None; + commit_item_fields(app, &id, json!({ key: pts_to_val(&new_pts) }), cx); + } +} + +fn handle_mouse_move(app: &mut Backplane, layer: &str, e: &MouseMoveEvent, cx: &mut Context) { + let (ax, ay) = (f32::from(e.position.x), f32::from(e.position.y)); + let drag_copy = app.screens.mgmt.plan_ui.drag.clone(); + if let Some((drag_layer, action)) = drag_copy { + if drag_layer == layer && e.dragging() { + let Some(b) = app.screens.mgmt.plan_ui.card_bounds.get(layer).copied() else { return }; + let w = f32::from(b.size.width).max(1.0); + let h = f32::from(b.size.height).max(1.0); + let lx = ax - f32::from(b.origin.x); + let ly = ay - f32::from(b.origin.y); + match action { + DragAction::Pan { last_x, last_y } => { + let d = app.screens.mgmt.data("plan"); + let (board, _) = resolved_board_and_draw(app, &d); + let bb = board_bbox_f32(&board); + let cur = active_cam(&app.screens.mgmt.plan_ui, layer, bb, w, h); + let next = cur.pan(lx - last_x, ly - last_y); + set_cam(&mut app.screens.mgmt.plan_ui, layer, next); + app.screens.mgmt.plan_ui.drag = Some((drag_layer, DragAction::Pan { last_x: lx, last_y: ly })); + cx.notify(); + return; + } + DragAction::Vertex { id, is_plane, idx } => { + let d = app.screens.mgmt.data("plan"); + let (board, draw) = resolved_board_and_draw(app, &d); + let bb = board_bbox_f32(&board); + let cam = active_cam(&app.screens.mgmt.plan_ui, layer, bb, w, h); + let (wx, wy) = cam.to_world(lx, ly, w, h); + let mut pts = if is_plane { + draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == id).map(|r| pts_from_val(&r["outline"])).unwrap_or_default() + } else { + draw["bands"].as_array().into_iter().flatten().find(|b| b["id"] == id).map(|b| pts_from_val(&b["path"])).unwrap_or_default() + }; + if let Some(slot) = pts.get_mut(idx) { + *slot = [wx as f64, wy as f64]; + let key = if is_plane { "outline" } else { "path" }; + apply_optimistic(app, &id, json!({ key: pts_to_val(&pts) })); + cx.notify(); + } + return; + } + } + } + } + + if let Some((_b, _cam, hit, lx, ly)) = canvas_hit_at(app, layer, ax, ay) { + let next = hit.map(|h| (layer.to_string(), h)); + if app.screens.mgmt.plan_ui.hover != next { + app.screens.mgmt.plan_ui.hover = next; + app.screens.mgmt.plan_ui.hover_px = Some((lx, ly)); + cx.notify(); + } + } +} + +fn commit_optimistic_geometry(app: &mut Backplane, id: &str, is_plane: bool, cx: &mut Context) { + let key = if is_plane { "outline" } else { "path" }; + if let Some(pts) = app.screens.mgmt.plan_ui.optimistic.get(id).and_then(|p| p.get(key)).cloned() { + commit_item_fields(app, id, json!({ key: pts }), cx); + } +} + +fn handle_left_up(app: &mut Backplane, layer: &str, e: &MouseUpEvent, cx: &mut Context) { + let (ax, ay) = (f32::from(e.position.x), f32::from(e.position.y)); + let down = app.screens.mgmt.plan_ui.down_pos.take(); + let drag = app.screens.mgmt.plan_ui.drag.take(); + if let Some((_, DragAction::Vertex { id, is_plane, .. })) = drag { + commit_optimistic_geometry(app, &id, is_plane, cx); + return; + } + if e.click_count >= 2 { + app.screens.mgmt.plan_ui.fit_all(); + cx.notify(); + return; + } + if let Some((dx, dy)) = down { + if (dx - ax).hypot(dy - ay) < 4.5 { + if let Some((_b, _cam, hit, _, _)) = canvas_hit_at(app, layer, ax, ay) { + match hit { + Some(Hit::Band { id } | Hit::Region { id }) => { + app.screens.mgmt.plan_sel = Some(id.clone()); + mgmt_plan::send(app, "plan.focus", json!({"id": id}), cx); + } + None => { + app.screens.mgmt.plan_sel = None; + cx.notify(); + } + _ => {} + } + } + } + } +} + +fn handle_wheel(app: &mut Backplane, layer: &str, e: &ScrollWheelEvent, cx: &mut Context) { + let Some(b) = app.screens.mgmt.plan_ui.card_bounds.get(layer).copied() else { return }; + let w = f32::from(b.size.width).max(1.0); + let h = f32::from(b.size.height).max(1.0); + let mx = f32::from(e.position.x - b.origin.x); + let my = f32::from(e.position.y - b.origin.y); + let d = app.screens.mgmt.data("plan"); + let (board, _) = resolved_board_and_draw(app, &d); + let bb = board_bbox_f32(&board); + let cur = active_cam(&app.screens.mgmt.plan_ui, layer, bb, w, h); + let (lines, _x, y) = crate::mousecfg::delta(&e.delta); + let dy = if lines { y * 16.0 } else { y }; + let factor = (1.0 + dy * 0.002).clamp(0.65, 1.55); + let next = cur.zoom(factor, mx, my, w, h); + set_cam(&mut app.screens.mgmt.plan_ui, layer, next); + cx.notify(); +} + +fn handle_key_down(app: &mut Backplane, e: &KeyDownEvent, cx: &mut Context) { + let key = e.keystroke.key.as_str(); + match key { + "0" | "home" => { + app.screens.mgmt.plan_ui.fit_all(); + cx.notify(); + return; + } + "escape" => { + app.screens.mgmt.plan_sel = None; + app.screens.mgmt.plan_ui.selected_vertex = None; + cx.notify(); + return; + } + _ => {} + } + let Some(sel_id) = app.screens.mgmt.plan_sel.clone() else { return }; + let d = app.screens.mgmt.data("plan"); + let layers = merge_optimistic_into_layers(&d["layers"], &app.screens.mgmt.plan_ui.optimistic); + let mut locked = false; + let mut width = 1.5f64; + let mut is_corridor = false; + for l in layers.as_array().into_iter().flatten() { + for it in l["items"].as_array().into_iter().flatten() { + if it["id"] == sel_id { + locked = it["locked"] == true; + is_corridor = it["kind"] == "corridor"; + if let Some(w) = it["width"].as_f64() { + width = w; + } + } + } + } + match key { + "a" => mgmt_plan::approve(app, "", &[sel_id], true, cx), + "r" => mgmt_plan::approve(app, "", &[sel_id], false, cx), + "l" => commit_item_fields(app, &sel_id, json!({"locked": !locked}), cx), + "w" if is_corridor && !locked => { + let delta = if e.keystroke.modifiers.shift { -0.25 } else { 0.25 }; + let nw = ((width + delta).clamp(0.15, 25.0) * 100.0).round() / 100.0; + commit_item_fields(app, &sel_id, json!({"width": nw}), cx); + } + "delete" | "backspace" if !locked => { + if let Some((vid, idx)) = app.screens.mgmt.plan_ui.selected_vertex.clone() { + if vid == sel_id { + let (_, draw) = resolved_board_and_draw(app, &d); + let is_plane = !is_corridor; + let pts = if is_plane { + draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == sel_id).map(|r| pts_from_val(&r["outline"])).unwrap_or_default() + } else { + draw["bands"].as_array().into_iter().flatten().find(|b| b["id"] == sel_id).map(|b| pts_from_val(&b["path"])).unwrap_or_default() + }; + if let Some(new_pts) = remove_vertex(&pts, idx, is_plane) { + let fk = if is_plane { "outline" } else { "path" }; + app.screens.mgmt.plan_ui.selected_vertex = None; + commit_item_fields(app, &sel_id, json!({ fk: pts_to_val(&new_pts) }), cx); + } + } + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::prelude::v1::test; + + #[test] + fn polyline_midpoint_handles_variable_segments() { + assert_eq!(polyline_midpoint(&[]), None); + assert_eq!(polyline_midpoint(&[[5.0, 6.0]]), Some([5.0, 6.0])); + // 10mm horizontal + 30mm vertical => midpoint at total=20mm => (10, 10) + let m = polyline_midpoint(&[[0.0, 0.0], [10.0, 0.0], [10.0, 30.0]]).unwrap(); + assert!((m[0] - 10.0).abs() < 1e-6 && (m[1] - 10.0).abs() < 1e-6); + } + + #[test] + fn hit_test_prioritizes_vertices_midpoints_bands_then_regions_with_holes() { + let cam = Camera::fit([0.0, 0.0, 100.0, 100.0], 200.0, 200.0, 0.0); + // scale is 2.0 px/mm, center=(50,50) -> (100,100) + let bands = vec![json!({ + "id": "c1", "layer": "In1.Cu", "width": 4.0, "locked": false, + "path": [[10.0, 50.0], [90.0, 50.0]] + })]; + let regions = vec![json!({ + "id": "p1", "layer": "In1.Cu", "locked": false, + "outline": [[5.0, 5.0], [95.0, 5.0], [95.0, 95.0], [5.0, 95.0]], + "holes": [[[30.0, 70.0], [45.0, 70.0], [45.0, 85.0], [30.0, 85.0]]] + })]; + + // Hit vertex of selected band c1 at (10,50) -> px(20,100) + let h_v = hit_test(&bands, ®ions, "In1.Cu", Some("c1"), &cam, 200.0, 200.0, 22.0, 101.0); + assert_eq!(h_v, Some(Hit::Vertex { id: "c1".into(), is_plane: false, idx: 0 })); + + // Hit midpoint handle at (50,50) -> px(100,100) + let h_m = hit_test(&bands, ®ions, "In1.Cu", Some("c1"), &cam, 200.0, 200.0, 100.0, 100.0); + assert!(matches!(h_m, Some(Hit::Midpoint { ref id, seg_idx: 0, .. }) if id == "c1")); + + // Without c1 selected, hitting (60,50) -> px(120,100) picks Band before Region under it + let h_b = hit_test(&bands, ®ions, "In1.Cu", None, &cam, 200.0, 200.0, 120.0, 100.0); + assert_eq!(h_b, Some(Hit::Band { id: "c1".into() })); + + // Hit region at (15,20) -> px(30,40) + let h_r = hit_test(&bands, ®ions, "In1.Cu", None, &cam, 200.0, 200.0, 30.0, 40.0); + assert_eq!(h_r, Some(Hit::Region { id: "p1".into() })); + + // Hole inside region at (38,78) -> px(76,156) yields None + let h_hole = hit_test(&bands, ®ions, "In1.Cu", None, &cam, 200.0, 200.0, 76.0, 156.0); + assert_eq!(h_hole, None); + } + + #[test] + fn vertex_insertion_and_removal_enforces_minimum_counts() { + let open = vec![[0.0, 0.0], [10.0, 0.0]]; + assert_eq!(remove_vertex(&open, 0, false), None); + let open3 = insert_vertex(&open, 0, [5.0, 4.0], false); + assert_eq!(open3, vec![[0.0, 0.0], [5.0, 4.0], [10.0, 0.0]]); + assert_eq!(remove_vertex(&open3, 1, false), Some(open)); + + let tri = vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]; + assert_eq!(remove_vertex(&tri, 0, true), None); + let quad = insert_vertex(&tri, 2, [0.0, 10.0], true); + assert_eq!(quad.len(), 4); + assert_eq!(quad[3], [0.0, 10.0]); + } + + #[test] + fn default_pair_picks_busiest_signal_and_power_layers() { + let layers = vec![ + json!({"layer": "F.Cu", "role": "signal", "items": [{"kind": "corridor"}]}), + json!({"layer": "In1.Cu", "role": "power", "items": []}), + json!({"layer": "In3.Cu", "role": "power", "items": [{"kind": "plane"}, {"kind": "plane"}]}), + json!({"layer": "In5.Cu", "role": "signal", "items": [{"kind": "corridor"}, {"kind": "corridor"}, {"kind": "corridor"}]}), + ]; + assert_eq!(default_layer_pair(&layers), vec!["In5.Cu".to_string(), "In3.Cu".to_string()]); + } + + #[test] + fn layout_labels_avoids_overlapping_boxes_and_keeps_pinned_first() { + let cam = Camera::fit([0.0, 0.0, 100.0, 100.0], 400.0, 400.0, 0.0); + let parts = vec![ + json!({"r": "U_BIG", "b": [20.0, 20.0, 40.0, 40.0], "o": false}), + json!({"r": "R_OVERLAP", "b": [26.0, 26.0, 34.0, 34.0], "o": false}), + json!({"r": "TINY", "b": [60.0, 60.0, 61.0, 61.0], "o": false}), + json!({"r": "U2", "b": [70.0, 70.0, 85.0, 85.0], "o": false}), + ]; + let placed = layout_labels(&parts, &cam, 400.0, 400.0, &[]); + let names: Vec<&str> = placed.iter().map(|p| p.text.as_str()).collect(); + assert!(names.contains(&"U_BIG")); + assert!(names.contains(&"U2")); + assert!(!names.contains(&"R_OVERLAP")); + assert!(!names.contains(&"TINY")); + } + + #[test] + fn rail_and_bus_palette_assignment() { + assert_eq!(rail_color("+3V3", "#5a7a9a"), 0xf59e0b); + assert_eq!(rail_color("+1V8", ""), 0xc084fc); + assert_eq!(rail_color("+5V", "#123456"), 0x123456); + assert_eq!(bus_color("USB_DP", "#14b8a6"), 0x14b8a6); + } +} diff --git a/native/gpui/src/screens/mod.rs b/native/gpui/src/screens/mod.rs index 01ef32f1ad..2a815e5eb4 100644 --- a/native/gpui/src/screens/mod.rs +++ b/native/gpui/src/screens/mod.rs @@ -89,6 +89,7 @@ pub mod mgmt; pub mod mgmt_bom; pub mod mgmt_fab; pub mod mgmt_plan; +pub mod mgmt_plan_canvas; pub mod kcomment; pub mod mgmt_checks; pub mod mgmt_life; diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index 1a1a09e851..fb8f1cb3af 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -314,8 +314,8 @@ pub async fn call(hub: &Arc, c: &mut Conn, m: &str, p: &Value, is_browser: "order.buy" => { let th = s(p, "thread"); if th.is_empty() { return Some(Err(err("thread"))) } rpc(hub, c, "order.buy", json!({"thread":th})).await.map(|r| json!({"thread":r["thread"]})) } // feature "fabprofile": the project's fab profile (fab/mod.rs Fab.view), the same the desktop and the agents' fab_profile read; `action` get, pick or seen - // feature "plan": the routing plan's person-side calls (plan/mod.rs): approve or reject items, a layer or all, stop routing, verify, focus an item, or toggle plan-before-routing - "plan.approve" | "plan.stop" | "plan.verify" | "plan.focus" | "plan.enable" => { if m != "plan.enable" && s(p, "pro").is_empty() && s(p, "path").is_empty() { return Some(Err(err("pro (the project's .kicad_pro)"))) } + // feature "plan": the routing plan's person-side calls (plan/mod.rs): approve, steer/update, stop routing, verify, focus an item, read board geometry, or toggle plan-before-routing + "plan.approve" | "plan.update" | "plan.stop" | "plan.verify" | "plan.focus" | "plan.get" | "plan.enable" => { if m != "plan.enable" && s(p, "pro").is_empty() && s(p, "path").is_empty() { return Some(Err(err("pro (the project's .kicad_pro)"))) } rpc(hub, c, m, p.clone()).await.map(|r| json!({"result": r["result"]})) } // feature "mgmt": the management panels (docs/MANAGEMENT.md) and the design checks, the same calls the desktop makes; a BOM edit from the // phone is the person's, as the desktop's (kicad/bomedit.rs) diff --git a/native/host/src/data/webpolicy.rs b/native/host/src/data/webpolicy.rs index f5d51aa517..f99856685b 100644 --- a/native/host/src/data/webpolicy.rs +++ b/native/host/src/data/webpolicy.rs @@ -55,6 +55,7 @@ fn classify(method: &str, params: &Value) -> Option { | "plan.enable" | "plan.focus" | "plan.stop" + | "plan.update" | "plan.verify" | "turn.interrupt" | "viewer.compare" @@ -97,6 +98,7 @@ fn classify(method: &str, params: &Value) -> Option { | "mgmt.life.part" | "mgmt.watch" | "models.list" + | "plan.get" | "project.card" | "projects.list" | "review.list" diff --git a/native/host/src/kicad/board.rs b/native/host/src/kicad/board.rs index a824e20ef5..59ce4a3c65 100644 --- a/native/host/src/kicad/board.rs +++ b/native/host/src/kicad/board.rs @@ -152,7 +152,7 @@ fn pad(out: &mut Vec, x: &Sx, key: String, sig: u32, pl: &Place, ctx: &str if let Some(k) = hole { out.push(Item { key: k, sig, layer: 24, prim: Prim::Circ { c, r: drill / 2.0, w: 0.0, fill: true }, info }) } } /// Fp.place: 10.99 writes the footprint origin and angle as a TRS transform; its presence is authoritative. -fn fp_place(x: &Sx) -> Place { +pub fn fp_place(x: &Sx) -> Place { let tr = x.get("transform"); if tr.name().is_empty() { let a = x.get("at"); Place::new(a.f(0), a.f(1), rad(a.f(2))) } else { let t = tr.get("translate"); Place::new(t.f(0), t.f(1), rad(fl::num(tr.attr("rotate")))) } diff --git a/native/host/src/plan/geom.rs b/native/host/src/plan/geom.rs new file mode 100644 index 0000000000..344b0a8c9e --- /dev/null +++ b/native/host/src/plan/geom.rs @@ -0,0 +1,923 @@ +//! Pure `.kicad_pcb` geometry & stackup extractor for the Plan floorplanner canvas. +//! Parses Edge.Cuts outline (lines/arcs/rects/polys/circles, chained into continuous contours), +//! component courtyard/fab bounding boxes + refdes labels, copper layer stackup metadata, +//! and pad-to-pad ratsnest guides per net/corridor, cached by `(path, mtime, len)`. +use crate::files::kicad::{board, sexpr::{self, Sx}}; +use serde::Serialize; +use serde_json::{json, Value}; +use std::{ + collections::{HashMap, HashSet}, + path::Path, + sync::{Arc, Mutex, OnceLock}, + time::UNIX_EPOCH, +}; + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub struct PartBox { + /// Component reference designator (e.g. "U1", "J1"). + pub r: String, + /// Board side: "F" or "B". + pub s: &'static str, + /// World bounding box [x0, y0, x1, y1] in mm. + pub b: [f64; 4], + /// True if on bottom side or extending > 1.0 mm past Edge.Cuts (drawn dashed). + pub o: bool, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub struct CopperLayer { + pub layer: String, + pub index: usize, + pub role: String, + pub alias: String, + pub title: String, + pub subtitle: String, + #[serde(skip)] + pub above: Option<(String, f64, bool)>, + #[serde(skip)] + pub below: Option<(String, f64, bool)>, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub struct BoardGeom { + pub bbox: [f64; 4], + pub outline: Vec>, + pub parts: Vec, + pub copper_layers: Vec, +} + +#[derive(Clone, Debug)] +pub struct CachedBoard { + pub geom: BoardGeom, + /// Net name -> list of (refdes, x_mm, y_mm) pad coordinates. + pub pad_nets: HashMap>, +} + +#[derive(Clone)] +struct CacheEntry { + mtime_ns: u128, + len: u64, + board: Arc, +} + +static CACHE: OnceLock>> = OnceLock::new(); +fn cache() -> &'static Mutex> { + CACHE.get_or_init(Default::default) +} + +fn r2(v: f64) -> f64 { + (v * 100.0).round() / 100.0 +} + +fn pt2(x: f64, y: f64) -> [f64; 2] { + [r2(x), r2(y)] +} + +fn dist2(a: [f64; 2], b: [f64; 2]) -> f64 { + let (dx, dy) = (a[0] - b[0], a[1] - b[1]); + (dx * dx + dy * dy).sqrt() +} + +fn is_closed(pts: &[[f64; 2]]) -> bool { + pts.len() >= 3 && dist2(pts[0], pts[pts.len() - 1]) < 0.05 +} + +fn chain_segments(mut segs: Vec>) -> Vec> { + let mut closed = Vec::new(); + let mut open: Vec> = Vec::new(); + for s in segs.drain(..) { + if s.len() < 2 { + continue; + } + if is_closed(&s) { + closed.push(s); + } else { + open.push(s); + } + } + let mut out = closed; + while !open.is_empty() { + let mut cur = open.remove(0); + let mut grew = true; + while grew && !is_closed(&cur) { + grew = false; + let (head, tail) = (cur[0], cur[cur.len() - 1]); + let mut best: Option<(usize, bool, bool, f64)> = None; + for (i, cand) in open.iter().enumerate() { + let (ch, ct) = (cand[0], cand[cand.len() - 1]); + for (append_end, rev_cand, d) in [ + (true, false, dist2(tail, ch)), + (true, true, dist2(tail, ct)), + (false, false, dist2(head, ct)), + (false, true, dist2(head, ch)), + ] { + if d <= 0.05 && best.map_or(true, |b| d < b.3) { + best = Some((i, append_end, rev_cand, d)); + } + } + } + if let Some((idx, append_end, rev_cand, _)) = best { + let mut cand = open.remove(idx); + if rev_cand { + cand.reverse(); + } + if append_end { + cur.extend_from_slice(&cand[1..]); + } else { + cand.pop(); + cand.extend(cur); + cur = cand; + } + grew = true; + } + } + out.push(cur); + } + out +} + +fn sample_arc(a: board::Pt, b: board::Pt, c: board::Pt) -> Vec<[f64; 2]> { + let pts = board::arc_points(a, b, c); + if pts.len() <= 17 { + return pts.into_iter().map(|p| pt2(p.x as f64, p.y as f64)).collect(); + } + let mut out = Vec::with_capacity(17); + let last = pts.len() - 1; + for k in 0..=16 { + let idx = (k * last) / 16; + out.push(pt2(pts[idx].x as f64, pts[idx].y as f64)); + } + out +} + +fn sample_circle(c: board::Pt, r: f64) -> Vec<[f64; 2]> { + (0..=32) + .map(|i| { + let a = std::f64::consts::TAU * (i as f64) / 32.0; + pt2(c.x as f64 + r * a.cos(), c.y as f64 + r * a.sin()) + }) + .collect() +} + +fn edge_graphic_pts(x: &Sx, pl: &board::Place) -> Option> { + match x.name() { + "gr_line" | "fp_line" => { + let a = pl.at(board::at(x, "start")); + let b = pl.at(board::at(x, "end")); + Some(vec![pt2(a.x as f64, a.y as f64), pt2(b.x as f64, b.y as f64)]) + } + "gr_arc" | "fp_arc" => { + let a = pl.at(board::at(x, "start")); + let b = pl.at(board::at(x, "mid")); + let c = pl.at(board::at(x, "end")); + Some(sample_arc(a, b, c)) + } + "gr_rect" | "fp_rect" => { + let a = board::at(x, "start"); + let b = board::at(x, "end"); + let corners = [ + pl.at(a), + pl.at(board::Pt { x: b.x, y: a.y }), + pl.at(b), + pl.at(board::Pt { x: a.x, y: b.y }), + pl.at(a), + ]; + Some(corners.into_iter().map(|p| pt2(p.x as f64, p.y as f64)).collect()) + } + "gr_poly" | "fp_poly" => { + let mut ps: Vec<[f64; 2]> = x + .get("pts") + .args() + .iter() + .filter(|c| c.name() == "xy") + .map(|c| { + let p = pl.at(board::pt(c)); + pt2(p.x as f64, p.y as f64) + }) + .collect(); + if ps.len() >= 3 && !is_closed(&ps) { + ps.push(ps[0]); + } + (ps.len() >= 2).then_some(ps) + } + "gr_circle" | "fp_circle" => { + let center = board::at(x, "center"); + let end = board::at(x, "end"); + let r = ((end.x - center.x).powi(2) + (end.y - center.y).powi(2)).sqrt() as f64; + if r > 0.01 { + Some(sample_circle(pl.at(center), r)) + } else { + None + } + } + _ => None, + } +} + +fn expand_bbox(bb: &mut [f64; 4], x: f64, y: f64) { + if !x.is_finite() || !y.is_finite() { + return; + } + bb[0] = bb[0].min(x); + bb[1] = bb[1].min(y); + bb[2] = bb[2].max(x); + bb[3] = bb[3].max(y); +} + +fn valid_bbox(bb: [f64; 4]) -> bool { + bb[2].is_finite() && bb[0].is_finite() && bb[2] > bb[0] && bb[3] > bb[1] +} + +fn layer_rank(name: &str) -> usize { + if name == "F.Cu" { + 0 + } else if name == "B.Cu" { + 10_000 + } else if let Some(inner) = name.strip_prefix("In").and_then(|s| s.strip_suffix(".Cu")) { + inner.parse::().unwrap_or(500) + } else { + 5_000 + } +} + +fn fmt_um(h_mm: f64) -> String { + let um = (h_mm * 1000.0).round() as i64; + format!("{um} µm") +} + +/// Build the concise stackup subtitle for a copper layer given an optional plan role override. +pub fn subtitle_for_layer(c: &CopperLayer, role_override: &str) -> String { + let role = if !role_override.is_empty() { + role_override + } else { + c.role.as_str() + }; + let is_power = matches!(role, "power" | "plane"); + if is_power { + let nearest = match (&c.above, &c.below) { + (Some(a), Some(b)) => Some(if a.1 <= b.1 { a } else { b }), + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (None, None) => None, + }; + if let Some((adj, h, _)) = nearest { + return format!("Faces {adj} across {}", fmt_um(*h)); + } + return String::new(); + } + match (&c.above, &c.below) { + (Some((an, ah, ac)), Some((bn, bh, bc))) => { + let part = |h: f64, core: bool| { + if core { + format!("{} core", fmt_um(h)) + } else { + fmt_um(h) + } + }; + format!("Stripline between {an} ({}) and {bn} ({})", part(*ah, *ac), part(*bh, *bc)) + } + (Some((an, ah, _)), None) => format!("Microstrip over {an} ({})", fmt_um(*ah)), + (None, Some((bn, bh, _))) => format!("Microstrip over {bn} ({})", fmt_um(*bh)), + (None, None) => String::new(), + } +} + +fn parse_copper_layers(fs: &[&[u8]]) -> Vec { + struct RawCu { + layer: String, + role: String, + alias: String, + } + let mut raw: Vec = Vec::new(); + for f in fs.iter().filter(|f| f.starts_with(b"(layers")) { + let sx = sexpr::parse(f); + for c in sx.args() { + let name = c.arg(0); + if !name.ends_with(".Cu") || name == "*.Cu" { + continue; + } + let typ = c.arg(1); + let alias = c.arg(2).trim().to_string(); + let role = if typ == "power" + || alias.to_ascii_uppercase().starts_with("PWR") + || alias.to_ascii_uppercase().starts_with("GND") + { + "power".to_string() + } else { + "signal".to_string() + }; + raw.push(RawCu { + layer: name.to_string(), + role, + alias, + }); + } + } + raw.sort_by_key(|r| layer_rank(&r.layer)); + + struct Ply { + name: String, + is_copper: bool, + is_core: bool, + h_mm: f64, + } + let mut plies: Vec = Vec::new(); + for f in fs.iter().filter(|f| f.starts_with(b"(setup")) { + let sx = sexpr::parse(f); + let stack = sx.get("stackup"); + for l in stack.args().iter().filter(|x| x.name() == "layer") { + let lname = l.arg(0).to_string(); + let typ = l.attr("type").to_ascii_lowercase(); + let h_mm = l.get("thickness").f(0) as f64; + let is_copper = typ == "copper" || lname.ends_with(".Cu"); + let is_dielectric = typ.contains("core") || typ.contains("prepreg") || typ.contains("dielectric") || lname.starts_with("dielectric"); + if (is_copper || is_dielectric) && (is_copper || h_mm > 0.0) { + plies.push(Ply { + name: lname, + is_copper, + is_core: typ.contains("core"), + h_mm, + }); + } + } + } + + let ref_name = |r: &RawCu| -> String { + if !r.alias.is_empty() && r.alias != "top_cu" && r.alias != "bottom_cu" { + r.alias.clone() + } else { + r.layer.clone() + } + }; + let cu_ply_idx: HashMap = plies + .iter() + .enumerate() + .filter(|(_, p)| p.is_copper) + .map(|(i, p)| (p.name.clone(), i)) + .collect(); + + let total = raw.len(); + let (mut sig_n, mut pwr_n) = (0usize, 0usize); + let mut out = Vec::with_capacity(total); + for (i, r) in raw.iter().enumerate() { + let tag = if !r.alias.is_empty() && r.alias != "top_cu" && r.alias != "bottom_cu" && r.alias != r.layer { + r.alias.clone() + } else if r.role == "power" { + pwr_n += 1; + format!("PWR{pwr_n}") + } else if total >= 4 { + sig_n += 1; + format!("SIG{sig_n}") + } else { + r.layer.clone() + }; + let index = i + 1; + let title = format!("L{index} · {tag}"); + let mut above: Option<(String, f64, bool)> = None; + let mut below: Option<(String, f64, bool)> = None; + if let Some(&pi) = cu_ply_idx.get(&r.layer) { + if i > 0 { + let prev = &raw[i - 1]; + if let Some(&ai) = cu_ply_idx.get(&prev.layer) { + if ai < pi { + let h: f64 = plies[ai + 1..pi].iter().filter(|p| !p.is_copper).map(|p| p.h_mm).sum(); + let core = plies[ai + 1..pi].iter().any(|p| !p.is_copper && p.is_core); + if h > 0.0 { + above = Some((ref_name(prev), h, core)); + } + } + } + } + if i + 1 < total { + let next = &raw[i + 1]; + if let Some(&bi) = cu_ply_idx.get(&next.layer) { + if pi < bi { + let h: f64 = plies[pi + 1..bi].iter().filter(|p| !p.is_copper).map(|p| p.h_mm).sum(); + let core = plies[pi + 1..bi].iter().any(|p| !p.is_copper && p.is_core); + if h > 0.0 { + below = Some((ref_name(next), h, core)); + } + } + } + } + } + let mut cl = CopperLayer { + layer: r.layer.clone(), + index, + role: r.role.clone(), + alias: r.alias.clone(), + title, + subtitle: String::new(), + above, + below, + }; + cl.subtitle = subtitle_for_layer(&cl, ""); + out.push(cl); + } + out +} + +fn footprint_ref<'a>(x: &'a Sx<'a>) -> &'a str { + let r = board::prop(x, "Reference"); + if !r.is_empty() { + return r; + } + x.args() + .iter() + .find(|c| c.name() == "fp_text" && c.arg(0) == "reference") + .map(|c| c.arg(1)) + .unwrap_or("") +} + +fn part_priority(r: &str) -> u8 { + let up = r.to_ascii_uppercase(); + if up.starts_with('U') || up.starts_with("IC") || up.starts_with("MCU") || up.starts_with("FPGA") { + 0 + } else if up.starts_with('J') || up.starts_with("CON") || up.starts_with('P') { + 1 + } else if up.starts_with('Q') || up.starts_with('Y') || up.starts_with('M') || up.starts_with("SW") { + 2 + } else { + 3 + } +} + +/// Parse a `.kicad_pcb` file's bytes into cached board floorplan geometry + pad nets. +pub fn parse_board(bytes: &[u8]) -> Option { + let fs = sexpr::forms(bytes)?; + let nets = board::nets(&fs); + let copper_layers = parse_copper_layers(&fs); + + let mut raw_outline: Vec> = Vec::new(); + let home = board::Place::new(0.0, 0.0, 0.0); + + struct RawPart { + r: String, + s: &'static str, + b: [f64; 4], + } + let mut raw_parts: Vec = Vec::new(); + let mut pad_nets: HashMap> = HashMap::new(); + + for f in &fs { + let sx = sexpr::parse(f); + match sx.name() { + "gr_line" | "gr_arc" | "gr_rect" | "gr_poly" | "gr_circle" => { + if sx.attr("layer") == "Edge.Cuts" { + if let Some(pts) = edge_graphic_pts(&sx, &home) { + raw_outline.push(pts); + } + } + } + "footprint" => { + let pl = board::fp_place(&sx); + let refdes = footprint_ref(&sx); + let side = if sx.attr("layer").starts_with("B.") { "B" } else { "F" }; + let mut crtyd = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + let mut fab = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + let mut pads = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + + for c in sx.args() { + let cname = c.name(); + if cname == "pad" { + let p = pl.at(board::at(c, "at")); + let sz = c.get("size"); + let hw = (sz.f(0).abs().max(0.2) as f64) * 0.5; + let hh = (sz.f(1).abs().max(0.2) as f64) * 0.5; + let rad = hw.max(hh); + expand_bbox(&mut pads, p.x as f64 - rad, p.y as f64 - rad); + expand_bbox(&mut pads, p.x as f64 + rad, p.y as f64 + rad); + + if !refdes.is_empty() && !refdes.starts_with('#') { + let n = c.get("net"); + let net_name = if !n.arg(1).is_empty() { + n.arg(1).to_string() + } else { + nets.get(n.arg(0)).cloned().unwrap_or_default() + }; + if !net_name.is_empty() { + pad_nets + .entry(net_name) + .or_default() + .push((refdes.to_string(), r2(p.x as f64), r2(p.y as f64))); + } + } + continue; + } + let layer = c.attr("layer"); + if layer == "Edge.Cuts" { + if let Some(pts) = edge_graphic_pts(c, &pl) { + raw_outline.push(pts); + } + } else if layer == "F.CrtYd" || layer == "B.CrtYd" { + if let Some(pts) = edge_graphic_pts(c, &pl) { + for p in pts { + expand_bbox(&mut crtyd, p[0], p[1]); + } + } + } else if layer == "F.Fab" || layer == "B.Fab" { + if let Some(pts) = edge_graphic_pts(c, &pl) { + for p in pts { + expand_bbox(&mut fab, p[0], p[1]); + } + } + } + } + + if !refdes.is_empty() && !refdes.starts_with('#') { + let chosen = if valid_bbox(crtyd) { + crtyd + } else if valid_bbox(fab) { + fab + } else { + pads + }; + if valid_bbox(chosen) { + raw_parts.push(RawPart { + r: refdes.to_string(), + s: side, + b: [r2(chosen[0]), r2(chosen[1]), r2(chosen[2]), r2(chosen[3])], + }); + } + } + } + _ => {} + } + } + + let outline = chain_segments(raw_outline); + let mut edge_bb = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for poly in &outline { + for p in poly { + expand_bbox(&mut edge_bb, p[0], p[1]); + } + } + let has_edge = valid_bbox(edge_bb); + let mut bbox = edge_bb; + if !has_edge { + for p in &raw_parts { + expand_bbox(&mut bbox, p.b[0], p.b[1]); + expand_bbox(&mut bbox, p.b[2], p.b[3]); + } + } + if !valid_bbox(bbox) { + bbox = [0.0, 0.0, 100.0, 80.0]; + } else { + bbox = [r2(bbox[0]), r2(bbox[1]), r2(bbox[2]), r2(bbox[3])]; + } + + let mut parts: Vec = raw_parts + .into_iter() + .map(|p| { + let overhang = p.s == "B" + || (has_edge + && (p.b[0] < edge_bb[0] - 1.0 + || p.b[1] < edge_bb[1] - 1.0 + || p.b[2] > edge_bb[2] + 1.0 + || p.b[3] > edge_bb[3] + 1.0)); + PartBox { + r: p.r, + s: p.s, + b: p.b, + o: overhang, + } + }) + .collect(); + + parts.sort_by(|a, b| { + let pa = part_priority(&a.r); + let pb = part_priority(&b.r); + let aa = (a.b[2] - a.b[0]) * (a.b[3] - a.b[1]); + let ab = (b.b[2] - b.b[0]) * (b.b[3] - b.b[1]); + pa.cmp(&pb) + .then_with(|| ab.partial_cmp(&aa).unwrap_or(std::cmp::Ordering::Equal)) + .then_with(|| a.r.cmp(&b.r)) + }); + + Some(CachedBoard { + geom: BoardGeom { + bbox, + outline, + parts, + copper_layers, + }, + pad_nets, + }) +} + +/// Read and cache board geometry for `pcb_path` by `(mtime, len)`. +pub fn load(pcb_path: &str) -> Option> { + if pcb_path.is_empty() { + return None; + } + let meta = std::fs::metadata(Path::new(pcb_path)).ok()?; + let mtime_ns = meta + .modified() + .ok() + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let len = meta.len(); + + { + let map = cache().lock().unwrap(); + if let Some(hit) = map.get(pcb_path).filter(|e| e.mtime_ns == mtime_ns && e.len == len) { + return Some(hit.board.clone()); + } + } + + let bytes = std::fs::read(pcb_path).ok()?; + let parsed = Arc::new(parse_board(&bytes)?); + let mut map = cache().lock().unwrap(); + if map.len() >= 32 && !map.contains_key(pcb_path) { + map.clear(); + } + map.insert( + pcb_path.to_string(), + CacheEntry { + mtime_ns, + len, + board: parsed.clone(), + }, + ); + Some(parsed) +} + +/// Select up to `max_parts` parts, ensuring any component referenced in the plan (`from`/`to`) stays included. +pub fn parts_for_plan(geom: &BoardGeom, plan: &Value, max_parts: usize) -> Vec { + if geom.parts.len() <= max_parts { + return geom.parts.clone(); + } + let mut pinned: HashSet<&str> = HashSet::new(); + for c in plan["corridors"].as_array().into_iter().flatten() { + for key in ["from", "to"] { + for r in c[key].as_array().into_iter().flatten().filter_map(Value::as_str) { + pinned.insert(r); + } + } + } + let mut out = Vec::with_capacity(max_parts); + for p in &geom.parts { + if pinned.contains(p.r.as_str()) { + out.push(p.clone()); + if out.len() >= max_parts { + return out; + } + } + } + for p in &geom.parts { + if !pinned.contains(p.r.as_str()) { + out.push(p.clone()); + if out.len() >= max_parts { + break; + } + } + } + out +} + +/// Compute faint ratsnest guide segments `[x1, y1, x2, y2]` per corridor id. +pub fn guides_for_plan(board: &CachedBoard, plan: &Value) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + let groups = plan["groups"].as_array().cloned().unwrap_or_default(); + let mut total_segs = 0usize; + const MAX_TOTAL_GUIDES: usize = 180; + const MAX_CORRIDOR_GUIDES: usize = 18; + + let part_center: HashMap<&str, [f64; 2]> = board + .geom + .parts + .iter() + .map(|p| (p.r.as_str(), [r2((p.b[0] + p.b[2]) * 0.5), r2((p.b[1] + p.b[3]) * 0.5)])) + .collect(); + + for c in plan["corridors"].as_array().into_iter().flatten() { + if total_segs >= MAX_TOTAL_GUIDES { + break; + } + let Some(cid) = c["id"].as_str() else { continue }; + let gid = c["group"].as_str().unwrap_or(""); + let nets: Vec<&str> = groups + .iter() + .find(|g| g["id"].as_str() == Some(gid)) + .and_then(|g| g["nets"].as_array()) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let from_refs: HashSet<&str> = c["from"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let to_refs: HashSet<&str> = c["to"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + + let mut segs: Vec<[f64; 4]> = Vec::new(); + for net in &nets { + if segs.len() >= MAX_CORRIDOR_GUIDES || total_segs + segs.len() >= MAX_TOTAL_GUIDES { + break; + } + let Some(pads) = board.pad_nets.get(*net) else { continue }; + if pads.len() < 2 { + continue; + } + // Prefer direct from -> to pad pair when both endpoint refs exist. + let from_pads: Vec<&(String, f64, f64)> = if from_refs.is_empty() { + vec![] + } else { + pads.iter().filter(|(r, _, _)| from_refs.contains(r.as_str())).collect() + }; + let to_pads: Vec<&(String, f64, f64)> = if to_refs.is_empty() { + vec![] + } else { + pads.iter().filter(|(r, _, _)| to_refs.contains(r.as_str())).collect() + }; + + if !from_pads.is_empty() && !to_pads.is_empty() { + let mut best: Option<(f64, [f64; 4])> = None; + for a in &from_pads { + for b in &to_pads { + let d = (a.1 - b.1).hypot(a.2 - b.2); + if d > 0.05 && best.map_or(true, |x| d < x.0) { + best = Some((d, [r2(a.1), r2(a.2), r2(b.1), r2(b.2)])); + } + } + } + if let Some((_, seg)) = best { + segs.push(seg); + continue; + } + } + // Nearest-neighbor MST over the net's pads (capped to avoid quadratic blowup on huge power nets). + let mut rem: Vec<(f64, f64)> = pads.iter().take(16).map(|p| (p.1, p.2)).collect(); + let mut tree = vec![rem.remove(0)]; + while !rem.is_empty() && segs.len() < MAX_CORRIDOR_GUIDES { + let mut best: Option<(usize, [f64; 4], f64)> = None; + for a in &tree { + for (bi, b) in rem.iter().enumerate() { + let d = (a.0 - b.0).hypot(a.1 - b.1); + if best.map_or(true, |x| d < x.2) { + best = Some((bi, [r2(a.0), r2(a.1), r2(b.0), r2(b.1)], d)); + } + } + } + if let Some((bi, seg, d)) = best { + let next = rem.remove(bi); + tree.push(next); + if d > 0.05 { + segs.push(seg); + } + } else { + break; + } + } + } + + // Graceful fallback for early/synthetic plans with from/to refs but unrouted/unassigned pads. + if segs.is_empty() && !from_refs.is_empty() && !to_refs.is_empty() { + for fr in &from_refs { + for tr in &to_refs { + if let (Some(a), Some(b)) = (part_center.get(fr), part_center.get(tr)) { + if (a[0] - b[0]).hypot(a[1] - b[1]) > 0.5 { + segs.push([a[0], a[1], b[0], b[1]]); + } + } + } + } + } + + if !segs.is_empty() { + total_segs += segs.len(); + out.insert(cid.to_string(), segs); + } + } + out +} + +/// Compute a fallback bbox from plan geometry when no board file is supplied. +pub fn fallback_bbox(plan: &Value) -> [f64; 4] { + let mut bb = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for c in plan["corridors"].as_array().into_iter().flatten() { + for p in c["path"].as_array().into_iter().flatten() { + if let (Some(x), Some(y)) = (p[0].as_f64(), p[1].as_f64()) { + expand_bbox(&mut bb, x, y); + } + } + } + for pl in plan["planes"].as_array().into_iter().flatten() { + for p in pl["outline"][0].as_array().into_iter().flatten() { + if let (Some(x), Some(y)) = (p[0].as_f64(), p[1].as_f64()) { + expand_bbox(&mut bb, x, y); + } + } + } + if valid_bbox(bb) { + [r2(bb[0] - 5.0), r2(bb[1] - 5.0), r2(bb[2] + 5.0), r2(bb[3] + 5.0)] + } else { + [0.0, 0.0, 100.0, 80.0] + } +} + +pub fn board_json(geom: &BoardGeom, plan: &Value, max_parts: usize) -> Value { + let parts = parts_for_plan(geom, plan, max_parts); + json!({ + "bbox": geom.bbox, + "outline": geom.outline, + "parts": parts, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_real_ecc83_fixture_outline_parts_and_layers() { + let pcb = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../test/files/fixtures/plot/ecc83-pp.kicad_pcb"); + let bytes = std::fs::read(&pcb).expect("read ecc83-pp.kicad_pcb"); + let cached = parse_board(&bytes).expect("parse ecc83-pp.kicad_pcb"); + assert!(!cached.geom.outline.is_empty(), "Edge.Cuts outline present"); + assert!(cached.geom.bbox[2] > cached.geom.bbox[0] && cached.geom.bbox[3] > cached.geom.bbox[1]); + assert!(cached.geom.parts.iter().any(|p| p.r == "U1"), "U1 extracted: {:?}", cached.geom.parts); + assert_eq!(cached.geom.copper_layers.len(), 2); + assert_eq!(cached.geom.copper_layers[0].layer, "F.Cu"); + assert_eq!(cached.geom.copper_layers[1].layer, "B.Cu"); + assert!(cached.geom.copper_layers[0].subtitle.contains("1510 µm")); + } + + #[test] + fn parses_multilayer_stackup_arcs_overhangs_and_ratsnest_guides() { + let pcb = br#"(kicad_pcb + (layers + (0 "F.Cu" signal "TOP") + (4 "In1.Cu" power "GND1") + (6 "In2.Cu" power "PWR1") + (8 "In3.Cu" power "GND2") + (10 "In4.Cu" power "PWR2") + (12 "In5.Cu" signal "SIG1") + (14 "In6.Cu" power "GND3") + (2 "B.Cu" signal "BOT") + ) + (setup + (stackup + (layer "F.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 1" (type "prepreg") (thickness 0.04)) + (layer "In1.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 2" (type "core") (thickness 0.1)) + (layer "In2.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 3" (type "prepreg") (thickness 0.05)) + (layer "In3.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 4" (type "core") (thickness 0.03)) + (layer "In4.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 5" (type "prepreg") (thickness 0.06)) + (layer "In5.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 6" (type "core") (thickness 0.05)) + (layer "In6.Cu" (type "copper") (thickness 0.035)) + (layer "dielectric 7" (type "prepreg") (thickness 0.04)) + (layer "B.Cu" (type "copper") (thickness 0.035)) + ) + ) + (net 1 "DDR_D0") + (net 2 "GND") + (gr_line (start 10 10) (end 90 10) (layer "Edge.Cuts") (width 0.1)) + (gr_arc (start 90 10) (mid 95 15) (end 100 20) (layer "Edge.Cuts") (width 0.1)) + (gr_line (start 100 20) (end 100 70) (layer "Edge.Cuts") (width 0.1)) + (gr_line (start 100 70) (end 10 70) (layer "Edge.Cuts") (width 0.1)) + (gr_line (start 10 70) (end 10 10) (layer "Edge.Cuts") (width 0.1)) + (footprint "Pkg:QFN" (layer "F.Cu") (at 30 40) + (property "Reference" "U1") + (fp_rect (start -5 -5) (end 5 5) (layer "F.CrtYd") (width 0.05)) + (pad "1" smd rect (at 4 0) (size 0.5 0.5) (layers "F.Cu") (net 1 "DDR_D0")) + ) + (footprint "Pkg:BGA" (layer "F.Cu") (at 75 40 90) + (property "Reference" "U2") + (fp_rect (start -8 -8) (end 8 8) (layer "F.CrtYd") (width 0.05)) + (pad "2" smd rect (at -6 0) (size 0.5 0.5) (layers "F.Cu") (net 1 "DDR_D0")) + ) + (footprint "Conn:Edge" (layer "F.Cu") (at 50 8) + (property "Reference" "J1") + (fp_rect (start -10 -4) (end 10 4) (layer "F.CrtYd") (width 0.05)) + ) + )"#; + let cached = parse_board(pcb).expect("parse synthetic board"); + assert_eq!(cached.geom.outline.len(), 1, "5 Edge.Cuts segments chain into 1 closed contour"); + assert!(is_closed(&cached.geom.outline[0])); + assert_eq!(cached.geom.bbox, [10.0, 10.0, 100.0, 70.0]); + + let j1 = cached.geom.parts.iter().find(|p| p.r == "J1").unwrap(); + assert!(j1.o, "J1 extends past top Edge.Cuts and is flagged overhanging"); + let u1 = cached.geom.parts.iter().find(|p| p.r == "U1").unwrap(); + assert!(!u1.o && u1.b == [25.0, 35.0, 35.0, 45.0]); + + let sig1 = cached.geom.copper_layers.iter().find(|l| l.layer == "In5.Cu").unwrap(); + assert_eq!(sig1.title, "L6 · SIG1"); + assert_eq!(sig1.subtitle, "Stripline between PWR2 (60 µm) and GND3 (50 µm core)"); + let pwr2 = cached.geom.copper_layers.iter().find(|l| l.layer == "In4.Cu").unwrap(); + assert_eq!(pwr2.title, "L5 · PWR2"); + assert_eq!(pwr2.subtitle, "Faces GND2 across 30 µm"); + + let plan = json!({ + "groups": [{"id": "g1", "nets": ["DDR_D0"]}], + "corridors": [{"id": "c1", "group": "g1", "from": ["U1"], "to": ["U2"]}] + }); + let guides = guides_for_plan(&cached, &plan); + assert_eq!(guides["c1"], vec![[34.0, 40.0, 75.0, 46.0]]); + } +} diff --git a/native/host/src/plan/mod.rs b/native/host/src/plan/mod.rs index c654e90e8e..43b9a75043 100644 --- a/native/host/src/plan/mod.rs +++ b/native/host/src/plan/mod.rs @@ -9,6 +9,7 @@ //! KiCad's ApprovePlan as the person. `plan_route` is refused here, before KiCad is asked, unless what it would route is approved. //! Laws `plan_*`. pub mod events; +pub mod geom; pub mod panel; use crate::{agents::mcp::ToolSet, api::{Caller, Fut, RpcHandler}, hub::Hub}; @@ -74,20 +75,31 @@ const NS: &str = "kiapi.backplane.plan."; /// One corridor or plane region as the gate and the diff see it. #[derive(Clone, Debug, PartialEq)] -pub struct Item { pub id: String, pub kind: &'static str, pub layer: String, pub group: String, pub status: String, pub edited: bool, pub locked: bool, pub nets: usize, pub progress: Option<(u64, u64)> } +pub struct Item { pub id: String, pub kind: &'static str, pub layer: String, pub group: String, pub status: String, pub edited: bool, pub locked: bool, pub nets: usize, pub progress: Option<(u64, u64)>, pub geom_hash: u64 } fn st<'a>(v: &'a Value, k: &str) -> &'a str { v[k].as_str().unwrap_or("") } pub fn layer_status<'a>(plan: &'a Value, layer: &str) -> &'a str { plan["layers"].as_array().into_iter().flatten().find(|l| st(l, "layer") == layer).map_or("proposed", |l| st(l, "status")) } fn group<'a>(plan: &'a Value, id: &str) -> Option<&'a Value> { plan["groups"].as_array().into_iter().flatten().find(|g| st(g, "id") == id) } +fn fnv_val(v: &Value, mut h: u64) -> u64 { + for b in v.to_string().as_bytes() { h = (h ^ *b as u64).wrapping_mul(1099511628211); } + h +} +fn item_geom_hash(v: &Value, keys: &[&str]) -> u64 { + let mut h = 14695981039346656037u64; + for k in keys { h = fnv_val(&v[*k], h ^ k.len() as u64); } + h +} pub fn items(plan: &Value) -> Vec { let mut v = vec![]; for c in plan["corridors"].as_array().into_iter().flatten() { let nets = group(plan, st(c, "group")).and_then(|g| g["nets"].as_array()).map_or(0, Vec::len); v.push(Item { id: st(c, "id").into(), kind: "corridor", layer: st(c, "layer").into(), group: st(c, "group").into(), status: st(c, "status").into(), edited: c["edited"] == true, locked: c["locked"] == true, nets, - progress: c["progress"]["total"].as_u64().map(|t| (c["progress"]["routed"].as_u64().unwrap_or(0), t)) }); + progress: c["progress"]["total"].as_u64().map(|t| (c["progress"]["routed"].as_u64().unwrap_or(0), t)), + geom_hash: item_geom_hash(c, &["path", "width", "vias"]) }); } for p in plan["planes"].as_array().into_iter().flatten() { v.push(Item { id: st(p, "id").into(), kind: "plane", layer: st(p, "layer").into(), group: st(p, "net").into(), status: st(p, "status").into(), edited: p["edited"] == true, locked: p["locked"] == true, nets: 1, - progress: p["progress"]["total"].as_u64().map(|t| (p["progress"]["routed"].as_u64().unwrap_or(0), t)) }); + progress: p["progress"]["total"].as_u64().map(|t| (p["progress"]["routed"].as_u64().unwrap_or(0), t)), + geom_hash: item_geom_hash(p, &["outline", "reference", "priority"]) }); } v } @@ -124,7 +136,7 @@ pub fn diff(old: &Value, new: &Value) -> Vec { None => out.push(json!({"id": i.id, "kind": i.kind, "change": "added", "status": i.status, "layer": i.layer})), Some(o) => { if o.status != i.status { out.push(json!({"id": i.id, "kind": i.kind, "change": "status", "from": o.status, "to": i.status})) } - if !o.edited && i.edited { out.push(json!({"id": i.id, "kind": i.kind, "change": "edited by the person"})) } + if (!o.edited && i.edited) || (i.edited && o.geom_hash != i.geom_hash) { out.push(json!({"id": i.id, "kind": i.kind, "change": "edited by the person"})) } if o.layer != i.layer { out.push(json!({"id": i.id, "kind": i.kind, "change": "layer", "from": o.layer, "to": i.layer})) } if o.locked != i.locked { out.push(json!({"id": i.id, "kind": i.kind, "change": if i.locked { "locked" } else { "unlocked" }})) } if o.progress != i.progress { if let Some((r, t)) = i.progress { out.push(json!({"id": i.id, "kind": i.kind, "change": "progress", "routed": r, "total": t})) } } @@ -250,13 +262,306 @@ impl ToolSet for Tools { } } +fn round3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 } +fn norm_pt(v: &Value) -> Result { + let a = v.as_array().filter(|x| x.len() >= 2).ok_or_else(|| "point must be [x, y]".to_string())?; + let (x, y) = (a[0].as_f64().unwrap_or(f64::NAN), a[1].as_f64().unwrap_or(f64::NAN)); + if !x.is_finite() || !y.is_finite() { return Err("point coordinates must be finite".into()) } + Ok(json!([round3(x), round3(y)])) +} +fn norm_ring(v: &Value, min_len: usize) -> Result, String> { + let arr = v.as_array().ok_or_else(|| "points must be an array".to_string())?; + if arr.len() < min_len { return Err(format!("need at least {min_len} points")) } + arr.iter().map(norm_pt).collect() +} +fn norm_outline(v: &Value) -> Result { + let arr = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| "outline must be a polygon".to_string())?; + let is_flat = arr[0].as_array().and_then(|p| p.first()).and_then(Value::as_f64).is_some(); + if is_flat { + Ok(Value::Array(vec![Value::Array(norm_ring(v, 3)?)])) + } else { + let mut rings = Vec::with_capacity(arr.len()); + for (i, ring) in arr.iter().enumerate() { + rings.push(Value::Array(norm_ring(ring, if i == 0 { 3 } else { 3 })?)); + } + Ok(Value::Array(rings)) + } +} +/// Validate and normalize person steering ops into KiCad `UpdatePlan` JSON ops (`set` uses `"fields"`, `"note"` becomes `add` note). +pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { + if ops.is_empty() { return Err("ops cannot be empty".into()) } + let mut out = Vec::with_capacity(ops.len()); + for (idx, op) in ops.iter().enumerate() { + let kind = op["op"].as_str().unwrap_or(""); + match kind { + "note" => { + let text = op["text"].as_str().unwrap_or("").trim(); + if text.is_empty() { return Err("note text cannot be empty".into()) } + let id = op["id"].as_str().filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| format!("note-{}-{idx}", crate::hub::now_ms())); + let mut item = json!({"id": id, "text": text, "author": "person"}); + if let Some(t) = op.get("target").filter(|v| !v.is_null()) { item["target"] = t.clone(); } + out.push(json!({"op": "add", "kind": "note", "item": item})); + } + "add" => { + let k = op["kind"].as_str().unwrap_or(""); + if k.is_empty() || !op["item"].is_object() { return Err("add needs kind and item".into()) } + let mut item = op["item"].clone(); + if k == "note" { + if item["text"].as_str().unwrap_or("").trim().is_empty() { return Err("note text cannot be empty".into()) } + if item["id"].as_str().unwrap_or("").is_empty() { item["id"] = json!(format!("note-{}-{idx}", crate::hub::now_ms())); } + item["author"] = json!("person"); + } + out.push(json!({"op": "add", "kind": k, "item": item})); + } + "set" => { + let id = op["id"].as_str().unwrap_or(""); + if id.is_empty() { return Err("set op needs id".into()) } + let src = op["fields"].as_object().or_else(|| op.as_object()).ok_or_else(|| "set op needs fields".to_string())?; + let mut fields = serde_json::Map::new(); + for k in ["path", "width", "outline", "layer", "locked", "vias", "reference", "status"] { + let Some(v) = src.get(k) else { continue }; + let clean = match k { + "path" => Value::Array(norm_ring(v, 2)?), + "width" => { + let w = v.as_f64().unwrap_or(f64::NAN); + if !w.is_finite() || !(0.1..=50.0).contains(&w) { return Err("width must be between 0.1 and 50.0 mm".into()) } + json!(round3(w)) + } + "outline" => norm_outline(v)?, + "layer" | "reference" | "status" => { + let s = v.as_str().map(str::trim).unwrap_or(""); + if s.is_empty() && k == "layer" { return Err("layer cannot be empty".into()) } + json!(s) + } + "locked" => json!(v.as_bool().ok_or_else(|| "locked must be a boolean".to_string())?), + "vias" => Value::Array(v.as_array().ok_or_else(|| "vias must be an array".to_string())?.iter().map(norm_pt).collect::, _>>()?), + _ => v.clone(), + }; + fields.insert(k.to_string(), clean); + } + if fields.is_empty() { return Err(format!("set op for {id} has no supported fields")) } + out.push(json!({"op": "set", "id": id, "fields": Value::Object(fields)})); + } + "status" | "delete" => { + let id = op["id"].as_str().unwrap_or(""); + if id.is_empty() { return Err(format!("{kind} op needs id")) } + out.push(op.clone()); + } + other => return Err(format!("unsupported plan op '{other}'")), + } + } + Ok(out) +} + +fn ensure_layer_entry(plan: &mut Value, layer: &str, role: &str) { + if layer.is_empty() { return } + let arr = plan.as_object_mut().and_then(|m| { + if !m.contains_key("layers") || !m["layers"].is_array() { m.insert("layers".into(), json!([])); } + m.get_mut("layers").and_then(Value::as_array_mut) + }); + if let Some(layers) = arr { + if !layers.iter().any(|l| l["layer"] == layer) { + layers.push(json!({"layer": layer, "role": role, "status": "proposed"})); + } + } +} + +/// Apply normalized person ops directly to a saved `.kicad_plan` JSON document. +pub fn apply_person_ops(plan: &mut Value, ops: &[Value]) -> Result, String> { + if !plan.is_object() { return Err("invalid routing plan JSON".into()) } + let mut touched = Vec::new(); + for op in ops { + match op["op"].as_str().unwrap_or("") { + "set" => { + let id = op["id"].as_str().unwrap_or(""); + let fields = op["fields"].as_object().or_else(|| op.as_object()).ok_or_else(|| "set op needs fields".to_string())?; + let mut new_layer = String::new(); + let role = if let Some(it) = plan["corridors"].as_array_mut().and_then(|a| a.iter_mut().find(|x| x["id"] == id)) { + if let Some(obj) = it.as_object_mut() { + for (k, v) in fields { + if matches!(k.as_str(), "op" | "id" | "fields") { continue } + if k == "layer" { if let Some(s) = v.as_str() { new_layer = s.to_string(); } } + obj.insert(k.clone(), v.clone()); + } + obj.insert("edited".into(), json!(true)); + obj.insert("author".into(), json!("person")); + } + "signal" + } else if let Some(it) = plan["planes"].as_array_mut().and_then(|a| a.iter_mut().find(|x| x["id"] == id)) { + if let Some(obj) = it.as_object_mut() { + for (k, v) in fields { + if matches!(k.as_str(), "op" | "id" | "fields") { continue } + if k == "layer" { if let Some(s) = v.as_str() { new_layer = s.to_string(); } } + obj.insert(k.clone(), v.clone()); + } + obj.insert("edited".into(), json!(true)); + obj.insert("author".into(), json!("person")); + } + "power" + } else { + return Err(format!("no such item: {id}")) + }; + if !new_layer.is_empty() { ensure_layer_entry(plan, &new_layer, role); } + touched.push(id.to_string()); + } + "add" => { + let kind = op["kind"].as_str().unwrap_or(""); + let arr_k = match kind { "note" => "notes", "constraint" => "constraints", "corridor" => "corridors", "plane" => "planes", _ => return Err(format!("unsupported add kind '{kind}'")) }; + let Some(obj) = plan.as_object_mut() else { return Err("invalid plan".into()) }; + if !obj.get(arr_k).is_some_and(Value::is_array) { obj.insert(arr_k.into(), json!([])); } + obj.get_mut(arr_k).and_then(Value::as_array_mut).unwrap().push(op["item"].clone()); + if let Some(id) = op["item"]["id"].as_str() { touched.push(id.to_string()); } + } + "status" => { + let id = op["id"].as_str().unwrap_or(""); + let mut ok = false; + for arr_k in ["corridors", "planes"] { + if let Some(it) = plan[arr_k].as_array_mut().and_then(|a| a.iter_mut().find(|x| x["id"] == id)) { + it["status"] = op["status"].clone(); + it["author"] = json!("person"); + ok = true; + break; + } + } + if !ok { return Err(format!("no such item: {id}")) } + touched.push(id.to_string()); + } + "delete" => { + let id = op["id"].as_str().unwrap_or(""); + let mut removed = false; + for arr_k in ["corridors", "planes", "notes", "constraints"] { + if let Some(arr) = plan[arr_k].as_array_mut() { + let before = arr.len(); + arr.retain(|x| x["id"] != id); + if arr.len() < before { removed = true; } + } + } + if !removed { return Err(format!("no such item: {id}")) } + touched.push(id.to_string()); + } + other => return Err(format!("unsupported plan op '{other}'")), + } + } + plan["revision"] = json!(plan["revision"].as_u64().unwrap_or(0) + 1); + Ok(touched) +} + +/// Apply person approval/rejection to a saved `.kicad_plan` JSON document. +pub fn apply_person_approve(plan: &mut Value, layer: &str, ids: &[String], yes: bool) -> Vec { + let target = if yes { "approved" } else { "rejected" }; + let mut changed = Vec::new(); + let keep_done = |v: &Value| matches!(v["status"].as_str(), Some("routed" | "verified")); + if !layer.is_empty() && ids.is_empty() { + if let Some(layers) = plan["layers"].as_array_mut() { + if let Some(lv) = layers.iter_mut().find(|l| l["layer"] == layer) { + lv["status"] = json!(target); + } else { + layers.push(json!({"layer": layer, "status": target})); + } + } + for k in ["corridors", "planes"] { + for it in plan[k].as_array_mut().into_iter().flatten() { + if it["layer"] == layer && !keep_done(it) { + it["status"] = json!(target); + if let Some(id) = it["id"].as_str() { changed.push(id.to_string()); } + } + } + } + } else if !ids.is_empty() { + for k in ["corridors", "planes"] { + for it in plan[k].as_array_mut().into_iter().flatten() { + let matched = it["id"].as_str().filter(|id| ids.iter().any(|x| x == id)).map(str::to_string); + if let Some(id) = matched { + if !keep_done(it) { + it["status"] = json!(target); + changed.push(id); + } + } + } + } + } else { + for lv in plan["layers"].as_array_mut().into_iter().flatten() { + lv["status"] = json!(target); + } + for k in ["corridors", "planes"] { + for it in plan[k].as_array_mut().into_iter().flatten() { + if !keep_done(it) { + it["status"] = json!(target); + if let Some(id) = it["id"].as_str() { changed.push(id.to_string()); } + } + } + } + } + plan["revision"] = json!(plan["revision"].as_u64().unwrap_or(0) + 1); + changed +} + +fn write_plan_file(pcb: &str, plan: &Value) -> Result<(), String> { + let f = Path::new(pcb).with_extension("kicad_plan"); + let tmp = f.with_extension("kicad_plan.tmp"); + let txt = serde_json::to_string_pretty(plan).map_err(|e| e.to_string())?; + std::fs::write(&tmp, txt).map_err(|e| e.to_string())?; + crate::plat::fs::rename(&tmp, &f).map_err(|e| e.to_string()) +} + +/// The person's steering edits (the Plan canvas/inspector): sends KiCad's `UpdatePlan` as the person when open, +/// else updates `.kicad_plan` atomically on disk and broadcasts the settled panel update. +pub async fn update(hub: &Arc, pcb: &str, base: Option, ops: &[Value]) -> Result { + let norm = normalize_person_ops(ops)?; + let pro = crate::files::kicad::project::read(&Path::new(pcb).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()).pro; + if let Some(r) = crate::files::kicad::embed::gui_route(&pro) { + let rev = match base { + Some(b) => b, + None => read_plan(hub, None, pcb, false).await.ok().and_then(|p| p["revision"].as_u64()).unwrap_or(0), + }; + let msg = json!({"board": spec(pcb), "base": rev, "ops": Value::Array(norm).to_string()}); + let o = crate::files::kicad::embed::gui_call_as(&r, &format!("{NS}UpdatePlan"), msg, &crate::files::kicad::coedit::client_name(&crate::files::kicad::coedit::Who::Person)).await; + if o["ok"].as_bool() != Some(true) { + return Err(refused(o["error"].as_str().unwrap_or("no answer"))); + } + let m = &o["message"]; + if m["refused"].as_array().is_some_and(|a| !a.is_empty()) { + let why = m["reasons"].as_array().map(|rs| rs.iter().filter_map(Value::as_str).collect::>().join("; ")).filter(|s| !s.is_empty()).unwrap_or_else(|| "KiCad refused plan update".into()); + return Err(why); + } + events::settle(hub, pcb).await; + return Ok(m.clone()); + } + let f = Path::new(pcb).with_extension("kicad_plan"); + let pcb_s = pcb.to_string(); + let res = tokio::task::spawn_blocking(move || -> Result<(Value, Vec), String> { + let raw = std::fs::read_to_string(&f).map_err(|_| "no saved routing plan for this board".to_string())?; + let mut plan: Value = serde_json::from_str(&raw).map_err(|_| "saved routing plan is not valid JSON".to_string())?; + let touched = apply_person_ops(&mut plan, &norm)?; + write_plan_file(&pcb_s, &plan)?; + Ok((plan["revision"].clone(), touched)) + }).await.map_err(|e| e.to_string())??; + events::settle(hub, pcb).await; + Ok(json!({"revision": res.0, "applied": res.1, "saved": true})) +} + /// The person's decision (the Plan panel, a phone): `plan.approve {pro|path, layer?, ids?, approve}` -> KiCad's ApprovePlan as the person. pub async fn approve(hub: &Arc, pcb: &str, layer: &str, ids: &[String], yes: bool) -> Result { let msg = json!({"board": spec(pcb), "layer": layer, "ids": ids, "approve": yes}); let pro = crate::files::kicad::project::read(&Path::new(pcb).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()).pro; let o = match crate::files::kicad::embed::gui_route(&pro) { Some(r) => { let o = crate::files::kicad::embed::gui_call_as(&r, &format!("{NS}ApprovePlan"), msg, &crate::files::kicad::coedit::client_name(&crate::files::kicad::coedit::Who::Person)).await; if o["ok"].as_bool().unwrap_or(false) { o["message"].clone() } else { return Err(refused(o["error"].as_str().unwrap_or("no answer"))) } } - None => call(hub, None, pcb, "ApprovePlan", msg).await?, + None => { + let f = Path::new(pcb).with_extension("kicad_plan"); + if f.exists() { + let (pcb_s, layer_s, ids_v) = (pcb.to_string(), layer.to_string(), ids.to_vec()); + let res = tokio::task::spawn_blocking(move || -> Result { + let raw = std::fs::read_to_string(&f).map_err(|e| e.to_string())?; + let mut plan: Value = serde_json::from_str(&raw).map_err(|_| "saved routing plan is not valid JSON".to_string())?; + let changed = apply_person_approve(&mut plan, &layer_s, &ids_v, yes); + write_plan_file(&pcb_s, &plan)?; + Ok(json!({"revision": plan["revision"], "changed": changed, "saved": true})) + }).await.map_err(|e| e.to_string())??; + events::settle(hub, pcb).await; + return Ok(res); + } + call(hub, None, pcb, "ApprovePlan", msg).await? + } }; events::settle(hub, pcb).await; // KiCad said yes: the plan must say so too (a runtime that accepts and records nothing, as bp.12.1 did, is told, never a silent success) @@ -281,7 +586,7 @@ pub fn refused(err: &str) -> String { } pub struct Rpc; impl RpcHandler for Rpc { - fn methods(&self) -> &'static [&'static str] { &["plan.approve", "plan.stop", "plan.verify", "plan.get", "plan.focus", "plan.enable"] } + fn methods(&self) -> &'static [&'static str] { &["plan.approve", "plan.update", "plan.stop", "plan.verify", "plan.get", "plan.focus", "plan.enable"] } fn call<'a>(&'a self, hub: &'a Arc, _who: &'a Caller, id: &'a Value, m: &'a str, p: &'a Value) -> Fut<'a, Vec> { Box::pin(async move { let path = if !sv(p, "pro").is_empty() { sv(p, "pro") } else { sv(p, "path") }; @@ -298,9 +603,18 @@ impl RpcHandler for Rpc { let ids: Vec = p["ids"].as_array().map(|x| x.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); match m { "plan.approve" => approve(hub, &pcb, sv(p, "layer"), &ids, p["approve"] != false).await, + "plan.update" => { + let ops = p["ops"].as_array().cloned().ok_or_else(|| "ops must be a JSON array".to_string())?; + update(hub, &pcb, p["base"].as_u64(), &ops).await + } "plan.focus" => panel::focus(hub, if sv(p, "pro").is_empty() { sv(p, "path") } else { sv(p, "pro") }, sv(p, "id")).await, "plan.stop" => { let r = call(hub, None, &pcb, "StopPlanRouting", json!({"board": spec(&pcb)})).await; events::settle(hub, &pcb).await; r } "plan.verify" => { let r = call(hub, None, &pcb, "VerifyPlan", json!({"board": spec(&pcb)})).await; events::settle(hub, &pcb).await; r } + _ if p["board"] == true || p["panel"] == true => { + let (plan, live) = panel::plan_now(hub, &pcb).await; + let pan = if plan.is_null() { Value::Null } else { panel::data_with_board(&plan, &events::open_asks(&pcb), live, Some(&pcb)) }; + Ok(json!({"plan": plan, "panel": pan})) + } _ => read_plan(hub, None, &pcb, true).await, } }.await; @@ -390,4 +704,51 @@ mod tests { assert!(diff(&a, &a).is_empty()); assert_eq!(summary(&a)["awaiting_approval"], json!(["c2", "p2"])); } + #[test] fn person_ops_normalize_apply_approve_and_reedit_diff() { + let mut p = json!({ + "revision": 3, + "layers": [{"layer": "In1.Cu", "role": "signal", "status": "proposed"}, {"layer": "In2.Cu", "role": "power", "status": "proposed"}], + "groups": [{"id": "g1", "nets": ["A", "B"], "status": "proposed"}], + "corridors": [{"id": "c1", "group": "g1", "layer": "In1.Cu", "path": [[10.0, 20.0], [30.0, 20.0]], "width": 2.0, "status": "proposed"}], + "planes": [{"id": "p1", "net": "GND", "layer": "In2.Cu", "outline": [[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]], "status": "proposed"}] + }); + let ops = normalize_person_ops(&[ + json!({"op": "set", "id": "c1", "path": [[10.0, 20.0], [20.0, 25.0], [30.0, 20.0]], "width": 2.5, "locked": true, "layer": "In3.Cu"}), + json!({"op": "set", "id": "p1", "fields": {"outline": [[0.0, 0.0], [15.0, 0.0], [15.0, 10.0]]}}), + json!({"op": "note", "target": "c1", "text": "Steer clear of U2"}) + ]).unwrap(); + assert!(ops[0]["fields"].is_object()); + assert_eq!(ops[1]["fields"]["outline"], json!([[[0.0, 0.0], [15.0, 0.0], [15.0, 10.0]]])); + assert_eq!(ops[2]["op"], "add"); + + let before = p.clone(); + let touched = apply_person_ops(&mut p, &ops).unwrap(); + assert_eq!(touched.len(), 3); + assert_eq!(p["revision"], 4); + assert_eq!(p["corridors"][0]["edited"], true); + assert_eq!(p["corridors"][0]["author"], "person"); + assert_eq!(p["corridors"][0]["locked"], true); + assert_eq!(p["corridors"][0]["layer"], "In3.Cu"); + assert_eq!(p["notes"][0]["text"], "Steer clear of U2"); + assert!(p["layers"].as_array().unwrap().iter().any(|l| l["layer"] == "In3.Cu")); + + let d1 = diff(&before, &p); + assert!(d1.iter().any(|x| x["id"] == "c1" && x["change"] == "edited by the person")); + assert!(d1.iter().any(|x| x["id"] == "c1" && x["change"] == "locked")); + assert!(d1.iter().any(|x| x["change"] == "note")); + + // Further geometry edit on an already-edited item is still surfaced by diff + let mid = p.clone(); + let ops2 = normalize_person_ops(&[json!({"op": "set", "id": "c1", "width": 3.2})]).unwrap(); + apply_person_ops(&mut p, &ops2).unwrap(); + let d2 = diff(&mid, &p); + assert!(d2.iter().any(|x| x["id"] == "c1" && x["change"] == "edited by the person")); + + let approved = apply_person_approve(&mut p, "In3.Cu", &[], true); + assert_eq!(approved, ["c1"]); + assert_eq!(p["corridors"][0]["status"], "approved"); + assert!(normalize_person_ops(&[json!({"op": "set", "id": "c1", "width": 0.01})]).is_err()); + assert!(normalize_person_ops(&[json!({"op": "set", "id": "c1", "path": [[0.0, 0.0]]})]).is_err()); + assert!(crate::api::RpcHandler::methods(&Rpc).contains(&"plan.update")); + } } diff --git a/native/host/src/plan/panel.rs b/native/host/src/plan/panel.rs index 51cfec8d32..bcb4071c13 100644 --- a/native/host/src/plan/panel.rs +++ b/native/host/src/plan/panel.rs @@ -33,8 +33,16 @@ fn problem_text(d: &Value) -> String { }).unwrap_or("").to_string() } -/// The panel's data from a plan (with its `derived` when KiCad gave it). +/// The panel's data from a plan (with its `derived` when KiCad gave it), optionally enriched with `.kicad_pcb` geometry. pub fn data(plan: &Value, asks: &[Value], live: bool) -> Value { + data_with_board(plan, asks, live, None) +} + +pub fn data_with_board(plan: &Value, asks: &[Value], live: bool, pcb: Option<&str>) -> Value { + let cached = pcb.and_then(super::geom::load); + let geom = cached.as_ref().map(|b| &b.geom); + let guides = cached.as_ref().map(|b| super::geom::guides_for_plan(b, plan)).unwrap_or_default(); + let groups = plan["groups"].as_array().cloned().unwrap_or_default(); let group = |id: &str| groups.iter().find(|g| st(g, "id") == id).cloned().unwrap_or(Value::Null); let der = |id: &str| plan["derived"]["items"][id].clone(); @@ -44,24 +52,44 @@ pub fn data(plan: &Value, asks: &[Value], live: bool) -> Value { let g = group(st(c, "group")); let d = der(st(c, "id")); let (r, t) = (d["routed"].as_u64().or(c["progress"]["routed"].as_u64()), d["total"].as_u64().or(c["progress"]["total"].as_u64())); rows.push((st(c, "layer").to_string(), json!({"id": c["id"], "kind": "corridor", "name": g["name"].as_str().unwrap_or(st(c, "group")), "color": g["color"].as_str().unwrap_or("#8a8a8a"), - "nets": g["nets"].as_array().map_or(0, Vec::len), "state": state(c, &d), "locked": c["locked"] == true, "order": c["order"], "routed": r, "total": t, + "nets": g["nets"].as_array().map_or(0, Vec::len), "state": state(c, &d), "locked": c["locked"] == true, "edited": c["edited"] == true, "order": c["order"], "routed": r, "total": t, "width": c["width"].as_f64().or_else(|| g["width"].as_f64()), "impedance": g["impedance"].clone(), "problems": d["problems"].as_array().map_or(0, Vec::len), "problem_text": problem_text(&d)}))); } for p in plan["planes"].as_array().into_iter().flatten() { let d = der(st(p, "id")); rows.push((st(p, "layer").to_string(), json!({"id": p["id"], "kind": "plane", "name": p["net"], "color": p["color"].as_str().unwrap_or("#5a7a9a"), "nets": 1, "state": state(p, &d), - "locked": p["locked"] == true, "reference": p["reference"], + "locked": p["locked"] == true, "edited": p["edited"] == true, "reference": p["reference"], "priority": p["priority"], "problems": d["problems"].as_array().map_or(0, Vec::len), "problem_text": problem_text(&d)}))); } for (l, _) in &rows { if !layers.contains(l) { layers.push(l.clone()) } } let stack = |l: &str| plan["derived"]["stackup"][l].as_str().map(str::to_string).unwrap_or_default(); - let ls: Vec = layers.iter().map(|l| { + let ls: Vec = layers.iter().enumerate().map(|(li, l)| { let its: Vec<&Value> = rows.iter().filter(|(x, _)| x == l).map(|(_, v)| v).collect(); let lv = plan["layers"].as_array().into_iter().flatten().find(|x| st(x, "layer") == l).cloned().unwrap_or(json!({"status": "proposed", "role": ""})); let done = its.iter().filter(|v| matches!(v["state"].as_str(), Some("routed") | Some("verified"))).count(); let approved = its.iter().filter(|v| v["state"] == "approved").count(); - json!({"layer": l, "role": lv["role"], "status": lv["status"], "stackup": stack(l), "done": done, "approved": approved, "total": its.len(), "items": its}) + let cl = geom.and_then(|g| g.copper_layers.iter().find(|c| c.layer == *l)); + let explicit_role = st(&lv, "role"); + let inferred_role = if !explicit_role.is_empty() { + explicit_role + } else if !its.is_empty() && its.iter().all(|v| v["kind"] == "plane") { + "power" + } else if its.iter().any(|v| v["kind"] == "corridor") { + "signal" + } else { + cl.map(|c| c.role.as_str()).unwrap_or("") + }; + let stackup_txt = stack(l); + let subtitle = if !stackup_txt.is_empty() { + stackup_txt.clone() + } else { + cl.map(|c| super::geom::subtitle_for_layer(c, inferred_role)).unwrap_or_default() + }; + let title = cl.map(|c| c.title.clone()).unwrap_or_else(|| format!("L{} · {}", li + 1, l)); + let index = cl.map(|c| c.index).unwrap_or(li + 1); + json!({"layer": l, "index": index, "title": title, "subtitle": subtitle, "role": if explicit_role.is_empty() { json!(inferred_role) } else { lv["role"].clone() }, + "status": lv["status"], "stackup": stackup_txt, "done": done, "approved": approved, "total": its.len(), "items": its}) }).collect(); let total = rows.len(); let awaiting = rows.iter().filter(|(_, v)| matches!(v["state"].as_str(), Some("proposed") | Some("edited"))).count(); @@ -84,33 +112,93 @@ pub fn data(plan: &Value, asks: &[Value], live: bool) -> Value { else { "rejected" }; let stackup_summary = plan["derived"]["stackup_summary"].as_str().map(str::to_string).unwrap_or_else(|| { ls.iter().filter_map(|l| { - let txt = l["stackup"].as_str().unwrap_or(""); + let txt = l["stackup"].as_str().filter(|s| !s.is_empty()).or_else(|| l["subtitle"].as_str()).unwrap_or(""); (!txt.is_empty()).then(|| format!("{}: {txt}", l["layer"].as_str().unwrap_or(""))) }).collect::>().join(" · ") }); let impedances = plan["derived"]["impedances"].clone(); - let draw = draw(plan, &rows); - json!({"draw": draw, "badge": {"n": awaiting + blocked, "tone": if blocked > 0 { "bad" } else if awaiting > 0 { "warn" } else { "" }}, "revision": plan["revision"], "live": live, + let draw = draw_enriched(plan, &rows, &guides); + let board = geom + .map(|g| super::geom::board_json(g, plan, 180)) + .unwrap_or_else(|| json!({"bbox": super::geom::fallback_bbox(plan), "outline": [], "parts": []})); + let copper_layers: Value = if let Some(g) = geom { + json!(g.copper_layers) + } else { + json!(ls.iter().map(|l| json!({"layer": l["layer"], "index": l["index"], "role": l["role"], "title": l["title"], "subtitle": l["subtitle"]})).collect::>()) + }; + json!({"draw": draw, "board": board, "copper_layers": copper_layers, "notes": plan["notes"], "constraints": plan["constraints"], + "badge": {"n": awaiting + blocked, "tone": if blocked > 0 { "bad" } else if awaiting > 0 { "warn" } else { "" }}, "revision": plan["revision"], "live": live, "total": total, "awaiting": awaiting, "approved": approved, "blocked": blocked, "routing": routing, "done": done, "routed": routed, "verified": verified, "rejected": rejected, "status": status, "stackup_summary": stackup_summary, "impedances": impedances, "asks": asks, "layers": ls, "empty": rows.is_empty()}) } -/// What the viewers draw over the board (read-only bands and regions, the floorplanner's look per state): corridors as bands along their +/// What the viewers draw over the board (bands and regions, the floorplanner's look per state): corridors as bands along their /// path at their width, plane regions as their outline; millimetres, board coordinates. At most `MAX_POINTS` points in all (the info's bound). pub const MAX_POINTS: usize = 3000; pub fn draw(plan: &Value, rows: &[(String, Value)]) -> Value { - let state = |id: &str| rows.iter().find(|(_, v)| v["id"] == id).map(|(_, v)| v["state"].clone()).unwrap_or(json!("proposed")); - let colour = |id: &str| rows.iter().find(|(_, v)| v["id"] == id).map(|(_, v)| v["color"].clone()).unwrap_or(json!("#8a8a8a")); - let nets = |id: &str| rows.iter().find(|(_, v)| v["id"] == id).map(|(_, v)| v["nets"].clone()).unwrap_or(json!(0)); + draw_enriched(plan, rows, &std::collections::HashMap::new()) +} + +fn draw_enriched(plan: &Value, rows: &[(String, Value)], guides: &std::collections::HashMap>) -> Value { + let row = |id: &str| rows.iter().find(|(_, v)| v["id"] == id).map(|(_, v)| v); + let state = |id: &str| row(id).map(|v| v["state"].clone()).unwrap_or(json!("proposed")); + let colour = |id: &str| row(id).map(|v| v["color"].clone()).unwrap_or(json!("#8a8a8a")); + let nets = |id: &str| row(id).map(|v| v["nets"].clone()).unwrap_or(json!(0)); let mut left = MAX_POINTS; let mut take = |pts: &Value| -> Option { let n = pts.as_array().map_or(0, Vec::len); if n == 0 || n > left { return None } left -= n; Some(pts.clone()) }; - let bands: Vec = plan["corridors"].as_array().into_iter().flatten().filter_map(|c| { let id = st(c, "id"); - Some(json!({"id": id, "layer": c["layer"], "width": c["width"].as_f64().unwrap_or(1.0), "path": take(&c["path"])?, "state": state(id), "color": colour(id), "nets": nets(id), "vias": c["vias"]})) }).collect(); - let regions: Vec = plan["planes"].as_array().into_iter().flatten().filter_map(|p| { let id = st(p, "id"); - Some(json!({"id": id, "layer": p["layer"], "net": p["net"], "outline": take(&p["outline"][0])?, "state": state(id), "color": colour(id)})) }).collect(); + let bands: Vec = plan["corridors"].as_array().into_iter().flatten().filter_map(|c| { + let id = st(c, "id"); + let r = row(id); + let g = guides.get(id).cloned().unwrap_or_default(); + Some(json!({"id": id, "layer": c["layer"], "width": c["width"].as_f64().unwrap_or(1.0), "path": take(&c["path"])?, "state": state(id), "color": colour(id), "nets": nets(id), "vias": c["vias"], + "name": r.map(|v| v["name"].clone()).unwrap_or(json!(id)), "group": c["group"], "locked": c["locked"] == true, "edited": c["edited"] == true, "order": c["order"], + "from": c["from"], "to": c["to"], "impedance": r.map(|v| v["impedance"].clone()).unwrap_or(Value::Null), "guides": g, + "problem_text": r.map(|v| v["problem_text"].clone()).unwrap_or(json!(""))})) + }).collect(); + let regions: Vec = plan["planes"].as_array().into_iter().flatten().filter_map(|p| { + let id = st(p, "id"); + let r = row(id); + let holes = p["outline"].as_array().map(|a| a.iter().skip(1).cloned().collect::>()).unwrap_or_default(); + Some(json!({"id": id, "layer": p["layer"], "net": p["net"], "outline": take(&p["outline"][0])?, "holes": holes, "state": state(id), "color": colour(id), + "locked": p["locked"] == true, "edited": p["edited"] == true, "reference": p["reference"], "priority": p["priority"], + "problem_text": r.map(|v| v["problem_text"].clone()).unwrap_or(json!(""))})) + }).collect(); json!({"bands": bands, "regions": regions}) } +/// Keep the published `mgmt.plan.` payload safely within the 64 KiB `hub.set_info` limit. +pub fn fit_info_budget(d: &mut Value) { + const BUDGET: usize = 58 * 1024; + if d.to_string().len() <= BUDGET { return } + let mut trimmed = false; + if let Some(bands) = d["draw"]["bands"].as_array_mut() { + for b in bands.iter_mut() { + if let Some(gs) = b["guides"].as_array_mut() { + if gs.len() > 6 { gs.truncate(6); trimmed = true; } + } + } + } + if d.to_string().len() <= BUDGET { if trimmed { d["board_trimmed"] = json!(true); } return } + if let Some(bands) = d["draw"]["bands"].as_array_mut() { + for b in bands.iter_mut() { + if b["guides"].as_array().is_some_and(|g| !g.is_empty()) { + b["guides"] = json!([]); + trimmed = true; + } + } + } + if d.to_string().len() <= BUDGET { if trimmed { d["board_trimmed"] = json!(true); } return } + if let Some(parts) = d["board"]["parts"].as_array_mut() { + if parts.len() > 80 { parts.truncate(80); trimmed = true; } + } + if d.to_string().len() > BUDGET { + if let Some(parts) = d["board"]["parts"].as_array_mut() { + if parts.len() > 40 { parts.truncate(40); trimmed = true; } + } + } + if trimmed { d["board_trimmed"] = json!(true); } +} + /// The board of a project's .kicad_pro. pub fn pcb_of(pro: &str) -> String { crate::files::kicad::project::read(&Path::new(pro).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()).pcb } /// The plan as it is now: the open KiCad's (live, with derived data) when the board is open there, else the saved `.kicad_plan` @@ -125,7 +213,7 @@ pub async fn plan_now(hub: &Arc, pcb: &str) -> (Value, bool) { pub async fn publish(hub: &Arc, pro: &str) { let pcb = pcb_of(pro); if pcb.is_empty() { return } let (plan, live) = plan_now(hub, &pcb).await; - let mut d = if plan.is_null() { json!({"badge": {"n": 0, "tone": ""}, "empty": true, "live": live, "layers": []}) } else { data(&plan, &super::events::open_asks(&pcb), live) }; + let mut d = if plan.is_null() { json!({"badge": {"n": 0, "tone": ""}, "empty": true, "live": live, "layers": []}) } else { data_with_board(&plan, &super::events::open_asks(&pcb), live, Some(&pcb)) }; // the person's switch, and plans an agent asked about on the project's other boards (the viewer shows one board; the plan may be another's) d["on"] = json!(super::is_on(hub.setting(super::SETTING).await.as_deref().unwrap_or(""))); let top = project_top(pro); @@ -133,6 +221,7 @@ pub async fn publish(hub: &Arc, pro: &str) { if d["empty"] == true && !d["elsewhere"].as_array().map_or(true, Vec::is_empty) { d["badge"] = json!({"n": d["elsewhere"].as_array().map_or(0, Vec::len), "tone": "warn"}) } // a KiCad whose own keys in plan view are not the plan's: the panel says to approve here if let Some(n) = crate::files::kicad::embed::gui_route(pro).and_then(|r| super::keys_note(&r.caps)) { d["keys_note"] = json!(n); } + fit_info_budget(&mut d); mgmt::publish(hub, "plan", pro, d).await; } @@ -264,4 +353,31 @@ mod tests { ]}); assert_eq!(data(&partial_plan, &[], false)["status"], "partial"); } + #[test] fn plan_panel_enriches_board_geometry_and_respects_info_budget() { + let pcb = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/files/fixtures/plot/ecc83-pp.kicad_pcb"); + let plan = json!({ + "revision": 2, + "layers": [{"layer": "F.Cu", "role": "signal", "status": "proposed"}], + "groups": [{"id": "g1", "name": "SignalA", "color": "#14b8a6", "nets": ["Net-(U1A-K)", "GND"]}], + "corridors": [{"id": "c1", "group": "g1", "layer": "F.Cu", "path": [[120.0, 100.0], [150.0, 100.0]], "width": 2.0, "from": ["U1"], "to": ["P2"], "status": "proposed"}] + }); + let d = data_with_board(&plan, &[], false, Some(pcb.to_str().unwrap())); + assert!(!d["board"]["outline"].as_array().unwrap().is_empty()); + assert!(!d["board"]["parts"].as_array().unwrap().is_empty()); + assert_eq!(d["layers"][0]["title"], "L1 · F.Cu"); + assert!(d["layers"][0]["subtitle"].as_str().unwrap().contains("1510 µm")); + assert_eq!(d["draw"]["bands"][0]["name"], "SignalA"); + + // Ensure oversized payload (>58 KiB) is shrunk safely under 64 KiB + let huge_parts: Vec = (0..1200).map(|i| json!({"r": format!("R{i}"), "s": "F", "b": [1.0, 2.0, 3.0, 4.0], "o": false})).collect(); + let huge_guides: Vec = (0..1500).map(|i| json!([i as f64, 1.0, (i + 1) as f64, 2.0])).collect(); + let mut big = json!({ + "board": {"bbox": [0, 0, 100, 100], "outline": [], "parts": huge_parts}, + "draw": {"bands": [{"id": "c1", "guides": huge_guides, "path": vec![json!([0, 0]); 200]}], "regions": []} + }); + assert!(big.to_string().len() > 58 * 1024); + fit_info_budget(&mut big); + assert!(big.to_string().len() <= 58 * 1024); + assert_eq!(big["board_trimmed"], true); + } } diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index aba4ea7249..e0bb51d713 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function Bt(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function bn(e){return e==="done"||e==="failed"||e==="cancelled"}function fn(e,t){if(!e||e.id!==t.id)return!0;let n=bn(e.state),i=bn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function gn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var lt={en:{"agy.signout":"Sign out","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.verify":"Verify","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.verify":"Verificar","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.verify":"検証","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function vn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ct=Pi(),It=new Set,Rt=new Map;for(let[e,t]of Object.entries(lt.en||{}))if(typeof t==="string"&&!Rt.has(t))Rt.set(t,e);function Pi(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function wn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ct}wn();function xt(e){return It.add(e),()=>{It.delete(e)}}function yn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ct;if(ct=n,wn(),i)for(let s of It)s(ct);return i}function p(e,t,n){let s=(lt[ct]||lt.en||{})[e]??lt.en?.[e]??t??e;return vn(s,n)}function fe(e){if(!e)return"";let t=Rt.get(e);if(!t)return e;return p(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Be(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function Mi(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Bi(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class jt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Be("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=p("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",p("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(a)=>{if(a.key==="Enter"){a.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let r=J("div","bp-ap-foot");this.actBtn=Be("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",p("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(fe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=p("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",p("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Be("","bp-fb-row",()=>{this.go(Bi(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(Mi(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(fe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Dt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",p("sidebar.add.project","Add project")),s=Be("×","icon",()=>this.close());s.title=p("common.close","Close"),s.setAttribute("aria-label",p("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=p("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Be(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",p("gpui.e.open.folder","Open folder")),e("clone",p("web.clone.tab","Clone from git")))}renderFolder(){let e=new jt(this.host.hub,(t)=>p("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=p("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",p("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),r=J("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,J("span","",p("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(J("div","bp-ap-first bp-dim",p("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=J("div","bp-ap-foot");this.cloneBtn=Be(p("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),a.push(o,c),t.append(...a),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,r)=>{let a=Be("","bp-ap-sug"+(r===this.suggestIdx?" active":""));a.setAttribute("data-testid","clone-suggestion"),a.addEventListener("mousedown",(c)=>c.preventDefault()),a.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",p("web.clone.private","private")));if(a.append(o),s.description)a.append(J("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",p("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",fe(t.hint))),t.state==="signedout"){let r=Be(p("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(a)=>a.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(fe(t.error)))}else if(t){let a=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Be(p("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),a.append(o,c),n.push(a);let m=J("label","bp-ap-name");m.append(J("span","bp-ap-lbl",p("web.clone.folder.name","Folder name")));let l=J("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),m.append(l),n.push(m),!t.ok&&t.error)n.push(this.errLine(fe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",p("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Be(p("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new jt(this.host.hub,(i)=>p("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Bt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=fe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Bt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let a=fe(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(a)}}apply(e){if(!e||e.id!==this.jobId)return;if(!fn(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&gn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?p("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?p("web.clone.stopped","Stopped cloning {repo}",{repo:i}):p("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let a=J("div","bp-ap-phase",fe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(r.push(a,o),t.detail)r.push(J("div","bp-ap-detail bp-dim",t.detail));let m=J("div","bp-ap-foot"),l=Be(p("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),m.append(l),r.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=J("div","bp-ap-err",fe(t.error));m.setAttribute("data-testid","clone-error"),r.push(m)}let a=J("div","bp-ap-foot"),o=Be(p("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(a.append(o),t.signin){let m=Be(p("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),a.append(m)}let c=Be(p("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),a.append(c),r.push(a)}else if(t.state==="done"){let a=t.notes??[];if(a.length>0){let l=J("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let h of a)l.appendChild(J("li","",fe(h)));r.push(l)}let o=J("div","bp-ap-foot"),c=t.thread?p("web.clone.open.thread","Open the thread"):p("web.clone.open.project","Open the project"),m=Be(c,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),r.push(o)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",p("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",p("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=Be(this.copied?p("web.clone.copied","Copied"):p("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=J("a","bp-ap-link",t.url);a.href=t.url,a.target="_blank",a.rel="noopener noreferrer",a.setAttribute("data-testid","clone-signin-url"),n.push(a)}}else if(t.state==="done")n.push(J("div","bp-ok",p("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",fe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function Ii(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function dt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.className="bp-code-inline",a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("**")&&r.endsWith("**")){let a=document.createElement("strong");a.textContent=r.slice(2,-2),e.appendChild(a)}else if(r.startsWith("*")&&r.endsWith("*")){let a=document.createElement("em");a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("[")){let a=s[2]??"",o=Ii(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,e.appendChild(c)}else e.appendChild(document.createTextNode(a))}i=n.lastIndex}if(i=(e.ended??0)}function Ln(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Pn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ht=Qi(),Gt=new Set,Ut=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function Qi(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Nn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ht}Nn();function Lt(e){return Gt.add(e),()=>{Gt.delete(e)}}function Mn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ht;if(ht=n,Nn(),i)for(let s of Gt)s(ht);return i}function h(e,t,n){let s=(mt[ht]||mt.en||{})[e]??mt.en?.[e]??t??e;return Pn(s,n)}function Ee(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return h(t,e)}function K(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=K("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function es(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ts(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Ot{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=K("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=K("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=K("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=K("div","bp-fb-list"),this.errEl=K("div","bp-ap-err bp-hidden");let a=K("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(K("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(Ee(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(K("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(ts(this.path,n))});i.append(K("span","bp-fb-icon","▸"),K("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(es(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(Ee(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Vt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=K("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=K("div","bp-modal bp-ap"),n=K("div","bp-modal-head"),i=K("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=K("div","bp-ap-tabs"),this.bodyEl=K("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Ot(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=K("div","bp-ap-form"),n=K("div","bp-ap-repo"),i=K("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=K("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=K("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=K("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=K("label","bp-ap-check"),a=K("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,K("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(K("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=K("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=K("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),r.push(o,c),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(c)=>c.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=K("div","bp-ap-sug-top");if(o.append(K("span","bp-ap-sug-name",s.name)),s.private)o.append(K("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(K("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(K("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=K("div","bp-ap-sug-note");if(s.append(K("span","",Ee(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(Ee(t.error)))}else if(t){let r=K("div","bp-ap-where"),o=K("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),r.append(o,c),n.push(r);let m=K("label","bp-ap-name");m.append(K("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let l=K("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(l),n.push(m),!t.ok&&t.error)n.push(this.errLine(Ee(t.error)));else if(t.same)n.push(K("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=K("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Ot(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=$t();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=Ee(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=$t(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=Ee(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Ln(e))this.goTo(e)}renderJobView(){this.jobEl=K("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=K("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[K("div","bp-ap-job-title",s)];if(t.state==="running"){let r=K("div","bp-ap-phase",Ee(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=K("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=K("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(K("div","bp-ap-detail bp-dim",t.detail));let m=K("div","bp-ap-foot"),l=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),m.append(l),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=K("div","bp-ap-err",Ee(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=K("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let c=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),r.append(c),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let l=K("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let u of r)l.appendChild(K("li","",Ee(u)));a.push(l)}let o=K("div","bp-ap-foot"),c=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=Fe(c,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=K("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(K("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(K("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=K("div","bp-ap-code-row"),s=K("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=K("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(K("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(K("div","bp-ap-err",Ee(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ns(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ut(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ns(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,e.appendChild(c)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{E.textContent="✓",window.setTimeout(()=>{E.textContent=w},1200)}).catch(()=>{})}),d.append(b,E);let g=document.createElement("pre"),v=document.createElement("code");v.textContent=l,g.appendChild(v),h.append(d,g),t.appendChild(h);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let c=document.createElement(`h${Math.min(4,r[1].length+1)}`);c.className="bp-md-h",dt(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;dt(c,m.join(` -`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))a.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));dt(o,a[c])}t.appendChild(o)}return t}var En="http://www.w3.org/2000/svg";function ht(e){let t=document.createElementNS(En,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(En,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ft(e){return e<10000000000?e*1000:e}function Ri(e){if(!e)return"";return new Date(Ft(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ji(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Ht(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class $t{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=p("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=p("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=p("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=p("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!Ht(r)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((r)=>r.id)),s=e.filter((r)=>!Ht(r)&&!i.has(r.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Ht(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((a)=>a.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let r=this.liveNodes.get(e);if(r){if(r.replaceChildren(pt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||p("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(pt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=p("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(ht(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),a),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{a.textContent="✓",window.setTimeout(()=>{a.textContent=r},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=p("reply.action","Reply"),o.append(ht(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let h=Ri(e.at);if(t)l.textContent=h,i.append(s,...m?[o]:[],l);else{let d=n&&e.at?ji(Ft(e.at)-Ft(n)):"",b=h?d?p("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:d}):p("web.chat.finished","Finished {time}",{time:h}):"";l.textContent=e.live?p("web.chat.streaming","Streaming…"):b,i.append(l,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=p("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=p("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let a=document.createElement("article");if(a.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),a.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let h=document.createElement("span");if(h.className="bp-tool-name",h.textContent=r.tool.name,l.appendChild(h),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}a.appendChild(l),i.appendChild(a);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){a.appendChild(this.renderPlanAsk(l)),i.appendChild(a);continue}let h=document.createElement("div");h.className="bp-ask-card",h.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,h.appendChild(d),l.state==="open"){let b=document.createElement("div");if(b.className="bp-ask-opts",l.options&&l.options.length>0)for(let E of l.options){let w=document.createElement("button");w.type="button",w.textContent=E.label,w.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,E.id)),b.appendChild(w)}else{let E=document.createElement("input");E.type="text",E.className="bp-input",E.placeholder=p("web.chat.answer.placeholder","Type answer…");let w=document.createElement("button");w.type="button",w.className="primary",w.textContent=p("web.chat.answer.btn","Answer"),w.addEventListener("click",()=>{if(E.value.trim())this.cb.onAnswerAsk(l.id,E.value.trim())}),b.append(E,w)}h.appendChild(b)}else{let b=document.createElement("div");b.className="bp-ask-answered",b.textContent=p("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),h.appendChild(b)}a.appendChild(h),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),m=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!m&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=p("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let h=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(h);else this.goTo(h)};l.addEventListener("click",d),l.addEventListener("keydown",(b)=>{if(b.key==="Enter"||b.key===" ")b.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.textContent=r.text;else l.appendChild(pt(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(m&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.attachments)if(h.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=h.previewUrl,d.alt=h.name||"attachment",l.appendChild(d)}else if(h.path||h.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=h.name||h.path||"image",l.appendChild(d)}if(l.childElementCount>0)a.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=h;let b=`${r.id}|${h}`,E=this.imageCache.get(b);if(E)d.src=E;else this.cb.onLoadImage(r.id,h).then((w)=>{if(!w)return;let g=w.url??(w.mime&&w.data?`data:${w.mime};base64,${w.data}`:"");if(!g)return;this.imageCache.set(b,g),d.src=g});l.appendChild(d)}a.appendChild(l)}a.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(a)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let r=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(r){if(r.focus({preventScroll:!0}),t.start!==null&&t.end!==null)r.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let r=ht(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);r.classList.add("bp-plan-head-ic");let a=document.createElement("span");if(a.className="bp-plan-title",a.textContent=!e.head||e.head==="Proposed plan"?p("ask.plan","Proposed plan"):fe(e.head),s.append(r,a),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=p("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let h=p("common.copy","Copy"),d=document.createElement("span");d.textContent=h,l.append(ht(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=p("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=h},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?p("gpui.c.term.collapse","Collapse"):p("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(pt(e.question||"")),i.appendChild(m),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let h=e.options?.find((w)=>w.id==="implement"||w.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=h?.label&&h.label!=="Implement"?fe(h.label):p("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"implement")}),l.appendChild(d),e.revise!==!1){let w=document.createElement("button");w.type="button",w.className="bp-plan-revise-btn"+(n?" active":""),w.setAttribute("data-testid","plan-revise"),w.append(ht(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(p("gpui.ask.plan.revise","Revise"))),w.addEventListener("click",()=>{let g=this.planRevisingId!==e.id;this.planRevisingId=g?e.id:"";let v=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=v,g)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(w)}let b=e.options?.find((w)=>w.id==="dismiss"||w.id.endsWith("|dismiss")),E=document.createElement("button");if(E.type="button",E.className="bp-plan-dismiss-btn",E.setAttribute("data-testid","plan-dismiss"),E.textContent=b?.label&&b.label!=="Dismiss"?fe(b.label):p("approval.dismiss","Dismiss"),E.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,b?.id??"dismiss")}),l.appendChild(E),i.appendChild(l),n){let w=document.createElement("div");w.className="bp-plan-revise",w.setAttribute("data-testid","plan-revise-drawer");let g=document.createElement("textarea");g.rows=2,g.className="bp-input bp-plan-revise-input",g.placeholder=p("gpui.ask.plan.reviseph","What should change in the plan?"),g.value=this.planReviseDrafts.get(e.id)??"";let v=document.createElement("button");v.type="button",v.className="bp-plan-revise-send",v.setAttribute("data-testid","plan-revise-send"),v.textContent=p("gpui.ask.plan.sendrev","Send revision"),v.disabled=g.value.trim().length===0;let y=()=>{let L=g.value.trim();if(!L)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${L}`)},x=()=>{this.closePlanRevise()};w.addEventListener("keydown",(L)=>{if(L.key==="Escape")L.preventDefault(),L.stopPropagation(),x()}),g.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,g.value),v.disabled=g.value.trim().length===0}),g.addEventListener("keydown",(L)=>{if(L.key==="Enter"&&!L.shiftKey)L.preventDefault(),y()}),v.addEventListener("click",y);let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost",S.textContent=p("common.cancel","Cancel"),S.addEventListener("click",x),w.append(g,v,S),i.appendChild(w)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=p("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var xn="http://www.w3.org/2000/svg",Cn=4,kn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Ct(e){let t=document.createElementNS(xn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(xn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ut(){return Ct(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Sn(){return Ct(["M6 4l14 8-14 8z"])}function Di(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Gt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=p("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("div");r.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Ut()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=p("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let a=document.createElement("div");a.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",a.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(a,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=p("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",p("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Ct(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=p("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",p("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Ct(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=p("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=p("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let m=c.clipboardData?.items;if(!m)return;let l=[];for(let h=0;h0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Di(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=p("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${p("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?Sn():Ut()),this.planChipLbl.textContent=s?p("gpui.planmode.chip.building","Building"):t==="pending"?p("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?p("gpui.planmode.chip.once","Plan · 1t"):p("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?p("gpui.mgmt.plan.tab","Plan"):p("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?Sn():Ut());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?p("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?p("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?p("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?p("gpui.planmode.bar.pending","Proposed plan awaits review below"):p("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let l=(h,d,b,E)=>{let w=document.createElement("button");return w.type="button",w.className="bp-plan-scope-btn"+(d?" active":""),w.textContent=h,w.disabled=!this.enabled,w.setAttribute("data-testid",E),w.addEventListener("click",()=>this.cb.onSetPlanMode?.(b)),w};m.append(l(p("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(p("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(p("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(m)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=p("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=p("reply.cancel","Cancel reply");if(a.title=o,a.setAttribute("aria-label",o),a.setAttribute("data-testid","composer-reply-drop"),n)a.addEventListener("click",n);this.replyEl.replaceChildren(i,a),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} -${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=p("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=p("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",p("web.composer.attach","Attach image")),this.voiceBtn.title=p("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",p("web.composer.voice","Voice dictation")),this.sendBtn.textContent=p("composer.send","Send"),this.stopBtn.textContent=p("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!kn.has(t.type)){this.showError(p("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Cn){this.showError(p("web.composer.maximages","At most {max} images per message.",{max:Cn}));break}let n=await new Promise((s,r)=>{let a=new FileReader;a.onload=()=>s(String(a.result||"")),a.onerror=()=>r(Error("read failed")),a.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=p("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function An(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var Hi=new Set(["bom","checks","life","plan","fab"]);function kt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Hi.has(t.id))}function Ln(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function St(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=a}return i}function nt(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function it(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var Fi=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),$i=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Nn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(Fi.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if($i.has(r)){let a=s.split("-");if(a.length>=2&&/^\d+$/.test(a[1]))return`${a[0]}-${a[1]}`;return a[0]}return i.slice(0,2).join("_")}function Tn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${nt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${nt(n)}`,tone:"warn"};return{text:nt(n),tone:"ok"}}function Pn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function Mn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Ot(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function At(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function Bn(e){return e.state==="routed"||e.state==="verified"}function In(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Rn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function jn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,r=0;if(typeof e.total!=="number"){for(let a of e.layers??[])for(let o of a.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")r+=1;else if(o.state==="approved")n+=1}else if(e.routing)r=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:r,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Dn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Hn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Vt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Fn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Wt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}class _t{hostEl;panelEl;stripEl;cb;infos=new Map;digest="";project="";askedProject="";watchGen=0;openPanel="";errorMsg="";bomFilter="";bomSelectedId="";bomEditingId="";bomEditGen=0;bomEditDraft="";bomEditStatus="";bomLastUndo=null;checksSource="";checksSelectedId="";checksStatus="";lifeSelectedKey="";lifePartSamples=null;lifePartLoading=!1;planHideDone=!1;planStatus="";planSelectedId="";planStackupOpen=!1;fabStatus="";constructor(e,t,n){this.cb=n,this.hostEl=t,this.panelEl=document.createElement("aside"),this.panelEl.className="bp-mgmt-panel bp-hidden",this.panelEl.setAttribute("aria-label","Project management panel"),this.stripEl=document.createElement("div"),this.stripEl.className="bp-mgmt-strip bp-hidden",this.stripEl.setAttribute("data-testid","mgmt-strip"),this.stripEl.setAttribute("aria-label","Project management tabs"),e.appendChild(this.panelEl),t.appendChild(this.stripEl)}openTab(e){let t=this.getStateInfo();if(!kt(t).some((n)=>n.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return kt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,r]of Object.entries(n.data))if(r&&typeof r==="object")this.infos.set(`mgmt.${s}.${i}`,r)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=kt(e);if(!this.digest||t.length===0){this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let a=document.createElement("button");a.type="button";let o=this.openPanel===r.id;a.className="bp-mgmt-tab"+(o?" active":""),a.setAttribute("data-testid",`mgmt-tab-${r.id}`),a.setAttribute("aria-pressed",o?"true":"false");let c=document.createElement("span");c.textContent=fe(r.label),a.appendChild(c);let m=this.getPanelData(r.id),l=Ln(m);if(l){let h=document.createElement("span");h.className=`bp-mgmt-badge bp-tone-${l.tone}`,h.textContent=l.text,a.appendChild(h)}a.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(a)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=p("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",p("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,s.appendChild(r)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let r=document.createElement("span"),a=t.source==="kicad";if(r.className="bp-mgmt-pill"+(a?" accent":""),r.textContent=a?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${it(t.cost)}/board`:`${it(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=fe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),m.appendChild(l),e.appendChild(m)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Pn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=St(a,24),c.appendChild(m),r.dnp){let w=document.createElement("span");w.className="bp-mgmt-pill",w.textContent=p("gpui.mgmt.bom.dnp","DNP"),c.appendChild(w)}else{let w=Tn(r.stock);if(w){let g=document.createElement("span");g.className=`bp-tone-${w.tone}`,g.textContent=w.text,c.appendChild(g)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(w)=>{w.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Nn(r.footprint??"")].filter(Boolean).join(" · "),b=document.createElement("span");b.className="bp-dim",b.textContent=d;let E=document.createElement("span");if(E.className="bp-mgmt-flex1",r.mpn)E.textContent=r.mpn;else if(i&&!r.dnp)E.className+=" bp-tone-warn",E.textContent=p("gpui.mgmt.bom.nompn","no MPN");if(h.append(b,E),!r.dnp&&typeof r.stock?.price==="number"){let w=document.createElement("span");w.className="bp-dim",w.textContent=it(r.stock.price),h.appendChild(w)}if(!r.dnp&&r.stock?.class){let w=document.createElement("span");w.className="bp-mgmt-faint",w.textContent=fe(r.stock.class),h.appendChild(w)}o.append(c,h),o.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=St(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let a=document.createElement("input");a.type="text",a.className="bp-mgmt-filter",a.placeholder="MPN",a.value=this.bomEditDraft,a.addEventListener("input",()=>{this.bomEditDraft=a.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,b=!1)=>{let E=o();this.bomEditStatus="Writing…",this.render();try{let w=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Vt(E,o()))return;this.bomLastUndo=!b&&(w.changed??0)>0?{project:d.project,editId:E.editId,refs:d.refs.slice(),field:d.field,was:typeof w.was==="string"?w.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=b?"Restored":(w.changed??0)===0?"No change":w.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(w){if(!Vt(E,o()))return;this.bomEditStatus=w instanceof Error?w.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(l,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn",b.textContent="Undo",b.addEventListener("click",()=>{c(Fn(d),!0)}),m.appendChild(b)}if(t.append(i,a,m),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,a=document.createElement("div");a.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=p("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),b.textContent=s(d)+(r(d)?" · judged":""),b.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(b)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=p("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let d=this.watchGen,b=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:b}).then(()=>{if(d!==this.watchGen||b!==this.project)return;this.checksStatus="",this.render()}).catch((E)=>{if(d!==this.watchGen||b!==this.project)return;this.checksStatus=E instanceof Error?E.message:"Could not run checks",this.render()})}),a.append(c,m),e.appendChild(a),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let h=Mn(n,this.checksSource);if(h.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of h){let b=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",E=document.createElement("div");E.className="bp-mgmt-group-head";let w=document.createElement("span");w.className=`bp-mgmt-dot bp-tone-bg-${b}`;let g=document.createElement("span");g.className="bp-mgmt-flex1",g.textContent=`${s(d.source)} · ${d.rule}`;let v=document.createElement("span");v.className=`bp-tone-${b}`,v.textContent=String(d.n),E.append(w,g,v),l.appendChild(E);for(let y of d.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===y.id?" active":"");let S=document.createElement("div");if(S.textContent=fe(y.title??""),x.appendChild(S),y.names||this.checksSelectedId===y.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let T=document.createElement("span");if(T.className="bp-dim bp-mgmt-flex1",T.textContent=y.names??"",L.appendChild(T),this.checksSelectedId===y.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=p("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(F)=>{F.stopPropagation();let z={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:z.project,id:y.id}).then((V)=>{let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Wt(z,R))return;if(V.text)this.cb.onSendText(V.text),this.checksStatus="Sent to agent",this.render()}).catch((V)=>{let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Wt(z,R))return;this.checksStatus=V instanceof Error?V.message:"Could not send finding",this.render()})}),L.appendChild(M)}x.appendChild(L)}x.addEventListener("click",()=>{this.checksSelectedId=y.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:y.id}).catch(()=>{}),this.render()}),l.appendChild(x)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let m=i[c]??0,l=Ot(c),h=document.createElement("span");h.className=m>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",h.textContent=`${l.label} ${m}`,n.appendChild(h)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${At(t.since)} (${t.samples??0})`,n.append(c,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],a=t.bom?.instock??[],o=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=r[r.length-1],m=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${it(c[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${At(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,l=Ot(c.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(m?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let b=document.createElement("span");b.className="bp-mgmt-strong",b.textContent=St(c.refs??[],14);let E=document.createElement("span");E.className="bp-mgmt-flex1 bp-dim",E.textContent=c.mpn||c.key;let w=document.createElement("span");if(w.className=`bp-tone-${l.tone}`,w.textContent=l.label,d.append(b,E,w),typeof c.stock==="number"){let g=document.createElement("span");g.className="bp-dim",g.textContent=nt(c.stock),d.appendChild(g)}if(h.appendChild(d),m){let g=document.createElement("div");if(g.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)g.textContent=p("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let v=this.lifePartSamples[this.lifePartSamples.length-1];g.textContent=`${this.lifePartSamples.length} samples · latest ${v.at?At(v.at):""}`+(typeof v.stock==="number"?` · stock ${nt(v.stock)}`:"")+(typeof v.price==="number"?` · ${it(v.price)}`:"")}else g.textContent=p("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(g)}h.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((g)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(g.samples)?g.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(p("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(N,_)=>{let q=this.watchGen,ie=this.project;this.planStatus="",this.cb.hub.rpc(N,{pro:ie,..._}).catch((ae)=>{if(q!==this.watchGen||ie!==this.project)return;this.planStatus=ae instanceof Error?ae.message:p("gpui.mgmt.plan.refused","KiCad refused"),this.render()})},i=document.createElement("div");i.className="bp-plan-toggle";let s=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=p("gpui.mgmt.plan.before","Plan before routing"),r.title=s?p("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):p("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),a.setAttribute("data-testid","mgmt-plan-on"),a.setAttribute("aria-pressed",s?"true":"false"),a.textContent=p("gpui.bots.recall.on","On"),a.addEventListener("click",()=>n("plan.enable",{on:!0}));let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),o.setAttribute("data-testid","mgmt-plan-off"),o.setAttribute("aria-pressed",!s?"true":"false"),o.textContent=p("gpui.bots.recall.off","Off"),o.addEventListener("click",()=>n("plan.enable",{on:!1})),i.append(r,a,o),e.appendChild(i);for(let N of t.elsewhere??[]){let _=document.createElement("div");_.className="bp-plan-elsewhere";let q=document.createElement("span");q.className="bp-tone-warn bp-mgmt-flex1",q.textContent=p("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:N.name||N.rel||""}),_.appendChild(q),e.appendChild(_)}if(t.empty){let N=document.createElement("div");N.className="bp-mgmt-note";let _=document.createElement("div");_.className="bp-dim",_.textContent=p("gpui.mgmt.plan.noboard","No routing plan for this board.");let q=document.createElement("div");return q.className="bp-mgmt-faint",q.textContent=p("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),N.append(_,q),e.appendChild(N),e}let c=t.awaiting??0,m=t.blocked??0,l=t.done??0,h=t.total??0,d=t.revision??0,b=Rn(t),E=jn(t),w=E.reduce((N,_)=>N+_.count,0),g=document.createElement("div");g.className="bp-plan-status";let v=document.createElement("div");v.className="bp-plan-status-top";let y=document.createElement("span");if(y.className=`bp-plan-status-badge tone-${b.tone}`,y.textContent=p(b.key,b.label),v.appendChild(y),d>0){let N=document.createElement("span");N.className="bp-dim",N.textContent=`v${d}`,v.appendChild(N)}let x=document.createElement("span");if(x.className="bp-mgmt-flex1 "+(c>0?"bp-tone-warn":m>0?"bp-tone-bad":"bp-dim"),x.textContent=h>0?`${l}/${h} ${p("gpui.mgmt.plan.done","done")}`:c>0?p("web.plan.awaiting","{n} awaiting approval",{n:c}):p("gpui.mgmt.plan.nothing","Nothing awaits your approval"),v.appendChild(x),!t.live){let N=document.createElement("span");N.className="bp-mgmt-pill",N.textContent=p("gpui.mgmt.plan.saved","saved plan"),v.appendChild(N)}if(g.appendChild(v),w>0){let N=document.createElement("div");N.className="bp-plan-segbar";for(let _ of E){if(_.count<=0)continue;let q=document.createElement("div");q.className=`bp-plan-seg bp-tone-bg-${_.tone}`,q.style.flexGrow=String(_.count),N.appendChild(q)}g.appendChild(N)}e.appendChild(g);let S=document.createElement("div");if(S.className="bp-mgmt-head",c>0){let N=document.createElement("button");N.type="button",N.className="primary bp-mgmt-btn",N.setAttribute("data-testid","mgmt-plan-approve-all"),N.textContent=p("gpui.mgmt.plan.all","Approve all"),N.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),S.appendChild(N)}if(t.routing){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.setAttribute("data-testid","mgmt-plan-stop"),N.textContent=p("gpui.mgmt.plan.stop","Stop routing"),N.addEventListener("click",()=>n("plan.stop",{})),S.appendChild(N)}if(t.live&&l>0){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.setAttribute("data-testid","mgmt-plan-verify"),N.textContent=p("gpui.mgmt.plan.verify","Verify"),N.addEventListener("click",()=>n("plan.verify",{})),S.appendChild(N)}let L=document.createElement("span");L.className="bp-mgmt-flex1";let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.setAttribute("data-testid","mgmt-plan-hide"),T.textContent=this.planHideDone?p("gpui.mgmt.plan.show","Show done"):p("gpui.mgmt.plan.hide","Hide done"),T.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),S.append(L,T),e.appendChild(S);let M=Array.isArray(t.asks)?t.asks:[];if(M.length>0){let N=M.map((le)=>le.what||"").filter(Boolean).join(", "),_=M[0]?.note||"",q=document.createElement("div");q.className="bp-plan-elsewhere";let ie=document.createElement("div");ie.className="bp-plan-ask-col";let ae=document.createElement("div");if(ae.className="bp-tone-warn",ae.textContent=N?p("gpui.mgmt.plan.requested","Approval requested: {what}",{what:N}):p("gpui.mgmt.plan.reqplain","Approval requested"),ie.appendChild(ae),_){let le=document.createElement("div");le.className="bp-dim",le.textContent=_,ie.appendChild(le)}q.appendChild(ie),e.appendChild(q)}if(this.planStatus){let N=document.createElement("div");N.className="bp-mgmt-note bp-plan-err bp-tone-bad";let _=document.createElement("span");_.className="bp-mgmt-flex1",_.textContent=this.planStatus==="KiCad refused"?p("gpui.mgmt.plan.refused","KiCad refused"):fe(this.planStatus);let q=document.createElement("button");q.type="button",q.className="icon",q.textContent="×",q.title=p("common.close","Close"),q.addEventListener("click",()=>{this.planStatus="",this.render()}),N.append(_,q),e.appendChild(N)}if(t.keys_note){let N=document.createElement("div");N.className="bp-mgmt-note bp-dim";let _="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";N.textContent=t.keys_note===_?p("gpui.mgmt.plan.keysnote",_):fe(t.keys_note),e.appendChild(N)}let F=t.stackup_summary??"",z=Array.isArray(t.impedances)?t.impedances:[];if(F||z.length>0){let N=document.createElement("div");N.className="bp-plan-stackup";let _=document.createElement("button");_.type="button",_.className="bp-plan-stackup-head",_.setAttribute("data-testid","mgmt-plan-stackup-toggle"),_.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let q=document.createElement("span");q.className="bp-plan-chev",q.textContent=this.planStackupOpen?"▾":"▸";let ie=document.createElement("span");if(ie.textContent=p("gpui.mgmt.plan.stackup","Stackup & impedances"),_.append(q,ie),_.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),N.appendChild(_),this.planStackupOpen){let ae=document.createElement("div");if(ae.className="bp-plan-stackup-body",ae.setAttribute("data-testid","mgmt-plan-stackup-body"),F){let le=document.createElement("div");le.className="bp-dim",le.textContent=F,ae.appendChild(le)}for(let le of z){let I=document.createElement("div");I.className="bp-mgmt-faint",I.textContent=`· ${le}`,ae.appendChild(I)}N.appendChild(ae)}e.appendChild(N)}let V=document.createElement("div");V.className="bp-mgmt-rows",V.setAttribute("data-testid","mgmt-plan-rows");let R=p("gpui.mgmt.plan.done","done");for(let N of t.layers??[]){let _=N.items??[],q=document.createElement("div");q.className="bp-mgmt-group-head bp-plan-layer-head";let ie=document.createElement("div");ie.className="bp-mgmt-row-line";let ae=document.createElement("span");ae.className="bp-mgmt-strong",ae.textContent=N.layer;let le=document.createElement("span");if(le.className="bp-dim bp-mgmt-flex1",le.textContent=`${N.role?`${N.role} · `:""}${N.done??0}/${_.length} ${R}`,ie.append(ae,le),N.status!=="approved"&&_.length>0){let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn",I.textContent=p("gpui.mgmt.plan.layer","Approve layer"),I.addEventListener("click",()=>n("plan.approve",{layer:N.layer,ids:[],approve:!0}));let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn",ve.textContent=p("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",()=>n("plan.approve",{layer:N.layer,ids:[],approve:!1})),ie.append(I,ve)}if(q.appendChild(ie),N.stackup){let I=document.createElement("div");I.className="bp-plan-layer-stackup",I.textContent=N.stackup,q.appendChild(I)}V.appendChild(q);for(let I of _){if(this.planHideDone&&Bn(I))continue;let ve=this.planSelectedId===I.id,A=document.createElement("div");A.className="bp-mgmt-row bp-plan-row"+(ve?" active":""),A.setAttribute("data-testid",`mgmt-plan-row-${I.id}`);let de=document.createElement("div");de.className="bp-mgmt-row-line";let se=document.createElement("span");se.className=`bp-plan-swatch bp-plan-st-${I.state||"proposed"}`,se.style.setProperty("--swatch-color",I.color||"#8a8a8a");let Y=document.createElement("span");Y.className="bp-mgmt-flex1"+(I.state==="blocked"||I.state==="failed"?" bp-tone-bad":I.state==="edited"?" bp-tone-warn":I.state==="rejected"||I.state==="routed"||I.state==="verified"?" bp-dim":""),Y.textContent=`${I.name||I.id}${I.locked?" \uD83D\uDD12":""}`;let oe=[];if(I.kind==="plane"){if(I.reference)oe.push(p("gpui.mgmt.plan.reference","over {layer}",{layer:I.reference}))}else{let X=I.nets??0;oe.push(X===1?p("web.plan.net.one","1 net"):p("web.plan.nets","{n} nets",{n:X}))}if(typeof I.width==="number"&&Number.isFinite(I.width))oe.push(`${I.width.toFixed(2)}mm`);if(I.impedance)oe.push(I.impedance);let B=oe.join(" · "),W=document.createElement("span");if(W.className="bp-plan-mark "+(I.state==="blocked"||I.state==="failed"?"bp-tone-bad":I.state==="verified"||I.state==="routed"?"bp-tone-ok":I.state==="approved"?"bp-tone-accent":"bp-dim"),W.textContent=In(I),de.append(se,Y,W),I.state==="proposed"||I.state==="edited"){let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn",X.textContent="✓",X.title=p("gpui.mgmt.plan.layer","Approve layer"),X.addEventListener("click",(Ee)=>{Ee.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!0})});let ce=document.createElement("button");ce.type="button",ce.className="bp-mgmt-btn",ce.textContent="✗",ce.title=p("gpui.mgmt.plan.reject","Reject"),ce.addEventListener("click",(Ee)=>{Ee.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!1})}),de.append(X,ce)}if(A.appendChild(de),B){let X=document.createElement("div");X.className="bp-mgmt-row-sub bp-plan-detail bp-dim",X.textContent=B,A.appendChild(X)}if(I.state==="routing"&&typeof I.total==="number"&&I.total>0){let X=document.createElement("div");X.className="bp-plan-microbar";let ce=document.createElement("div");ce.className="bp-plan-microbar-fill";let Ee=Math.max(0,Math.min(100,Math.round((I.routed??0)/I.total*100)));ce.style.width=`${Ee}%`,X.appendChild(ce),A.appendChild(X)}if(I.problem_text){let X=document.createElement("div");X.className="bp-plan-problem",X.textContent=I.problem_text,A.appendChild(X)}A.addEventListener("click",()=>{this.planSelectedId=I.id,n("plan.focus",{id:I.id}),this.render()}),V.appendChild(A)}}if(e.appendChild(V),(t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let N=document.createElement("div");N.className="bp-plan-footer",N.textContent=p("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(N)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let y=document.createElement("div");return y.className="bp-mgmt-note bp-tone-warn",y.textContent=t.error,e.appendChild(y),e}let n=(y,x={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:y,...x}).catch((T)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=T instanceof Error?T.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=p("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Hn(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=p("gpui.mgmt.fab.refresh","Refresh"),a.addEventListener("click",()=>n("refresh")),i.append(s,r,a),e.appendChild(i),this.fabStatus){let y=document.createElement("div");y.className="bp-mgmt-note bp-tone-bad",y.textContent=this.fabStatus,e.appendChild(y)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span"),d=(c?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),h.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(h),c?.at!=null){let y=document.createElement("button");y.type="button",y.className="bp-mgmt-btn",y.textContent=p("gpui.mgmt.fab.findings","Findings"),y.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(y)}if(!c?.running){let y=document.createElement("button");y.type="button",y.className="bp-mgmt-btn",y.textContent=p("gpui.mgmt.fab.reviewbtn","Review"),y.addEventListener("click",()=>n("review")),l.appendChild(y)}if(c?.judge){let y=document.createElement("button");y.type="button",y.className="bp-mgmt-btn",y.textContent=p("gpui.mgmt.fab.judge","Datasheets"),y.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(y)}m.appendChild(l),o.appendChild(m);let b=Dn(t.drc?.state??""),E=document.createElement("div");E.className="bp-mgmt-row";let w=document.createElement("div");w.className="bp-mgmt-row-line";let g=document.createElement("span");if(g.className="bp-mgmt-flex1 "+(b.button?"bp-tone-warn":"bp-dim"),g.textContent=b.text,w.appendChild(g),b.button){let y=document.createElement("button");y.type="button",y.className="bp-mgmt-btn",y.textContent=b.button,y.addEventListener("click",()=>n("drc")),w.appendChild(y)}E.appendChild(w),o.appendChild(E);for(let y of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=y,o.appendChild(x)}for(let y of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${y.label||y.key}: board ${y.project??"?"} mm, fab ${y.fab??"?"} mm`;let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=p("gpui.mgmt.fab.apply","Apply"),T.addEventListener("click",()=>n("apply",{key:y.key})),S.append(L,T),x.appendChild(S),o.appendChild(x)}if(t.stackup?.chosen){let y=document.createElement("div");y.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(L),S){let T=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=p("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:T})),x.appendChild(M)}y.appendChild(x),o.appendChild(y)}if(Array.isArray(t.changed)&&t.changed.length>0){let y=document.createElement("div");y.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=p("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=p("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),x.append(S,L),y.appendChild(x);for(let T of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=T,y.appendChild(M)}o.appendChild(y)}let v=Array.isArray(t.limits)?t.limits:[];if(v.length>0){let y=document.createElement("div");y.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=p("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=p("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=p("gpui.mgmt.fab.extra","Costs more");let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read",T.textContent=p("gpui.mgmt.fab.readcol","Read"),y.append(x,S,L,T),o.appendChild(y);for(let F of v){let z=document.createElement("div");z.className="bp-mgmt-row";let V=document.createElement("div");V.className="bp-mgmt-row-line";let R=document.createElement("span");R.className="bp-mgmt-flex1"+(F.changed?" bp-tone-warn":F.inherited?" bp-dim":""),R.textContent=`${F.changed?"• ":""}${F.label??""}`;let N=document.createElement("span");N.className="bp-mgmt-col",N.textContent=F.free?.text||"—";let _=document.createElement("span");_.className="bp-mgmt-col bp-dim",_.textContent=F.extra?.text||"—";let q=F.free&&typeof F.free==="object"?F.free:F.extra,ie=q?.fetched??"",ae=Boolean(ie)&&q?.confidence!=="published",le=ie?ae?`${ie}*`:ie:"—",I=q?.source??"",ve;if(I.startsWith("https://")&&ie){let A=document.createElement("a");A.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",A.href=I,A.target="_blank",A.rel="noopener noreferrer",A.textContent=le,ve=A}else{let A=document.createElement("span");A.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",A.textContent=le,ve=A}V.append(R,N,_,ve),z.appendChild(V),o.appendChild(z)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=p("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Ui={trs:(e)=>e,t:(e,t)=>t},Gi=new Set(["/settle"]);function $n(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((a)=>a.startsWith(n)))return 2;let r=0;for(let a=0;a0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function Gn(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function On(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function Vn(e,t=Ui){let{t:n,trs:i}=t,s=[],r=new Map;for(let o of e.projects)r.set(o.id,o.title||o.id);let a=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!a&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(a)s.push({label:a.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:a.pinned?"unpin":"pin"}}),s.push({label:a.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:a.settled?"unsettle":"settle"}}),s.push({label:a.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:a.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(a)for(let o of e.commands){if(!o.word)continue;let c=Gi.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:m}=Un(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:Gn(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function Wn(e,t,n,i=[],s=10,r=14){let a=t.trim(),o=a.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let E of i)d.set(E.id,E.title||E.id);let b=new Set;for(let E of c)if(E.action.type==="thread")b.add(E.action.id);for(let E of n.threads){if(!E.id||b.has(E.id))continue;b.add(E.id);let{urgency:w,want:g}=Un(E);c.push({label:E.title||"Untitled thread",place:E.project?d.get(E.project)??"":"",kind:"thread",urgency:w,want:g,dotClass:Gn(E),action:{type:"thread",id:E.id}})}}let m=[];for(let d=0;d0)m.push({score:g,index:d,item:b})}m.sort((d,b)=>{if(o){let g=(b.item.urgency??0)-(d.item.urgency??0);if(g!==0)return g}if(b.score!==d.score)return b.score-d.score;let E=d.item.kind==="thread"?0:1,w=b.item.kind==="thread"?0:1;if(E!==w)return E-w;return d.index-b.index});let l=new Set,h=[];for(let d of m){let b=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(b))continue;if(l.add(b),h.push(d.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(a.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(a)=>{if(a.key==="Escape")a.preventDefault(),a.stopPropagation(),this.close();else if(a.key==="ArrowDown"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(a.key==="ArrowUp"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(a.key==="Enter")a.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Vn(t,{t:p,trs:fe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Wn(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let a=document.createElement("div");a.className="bp-palette-empty",a.textContent=p("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)m.appendChild(document.createTextNode(o.label.slice(0,d)));let E=document.createElement("strong");if(E.className="bp-palette-mark",E.textContent=o.label.slice(d,b),m.appendChild(E),b{if(this.activeIdx!==a)this.activeIdx=a,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(a)),a===this.activeIdx)r=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((a)=>a.group!=="tools"),t=this.items.filter((a)=>a.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let a of e){if(i!==void 0&&a.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=a.group,n.appendChild(this.renderButton(a))}let s=()=>{let a=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let a=document.createElement("div");a.className="bp-rail-tools";for(let o of t)a.appendChild(this.renderButton(o));r.appendChild(a)}this.el.replaceChildren(r)}}var Vi=new Set(["resume","raise","retry","move","signin"]);function zn(e){if(!e||typeof e!=="object")return null;let t=e,n=(r)=>typeof r==="string"?r:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((r)=>Boolean(r)&&typeof r==="object").map((r)=>({label:n(r.label),act:n(r.act),room:n(r.room),thread:n(r.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Lt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Vi.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function Kn(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class Kt{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${p("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",p("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${p("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",p("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=p("home.machine","Home machine");let h=document.createElement("div");h.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let b=document.createElement("div"),E=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";b.textContent=E,d.appendChild(b);let w=document.createElement("div");if(w.className="bp-dim",t.moving?.state==="moving")w.textContent=t.moving.step?p("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):p("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")w.textContent=t.moving.note?p("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):p("home.move.failed","Home move failed");else if(!t.online)w.textContent=t.queuedCount>0?p("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):p("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else w.textContent="Online";if(d.appendChild(w),h.appendChild(d),t.canMoveHere&&this.cb.onMoveHomeHere){let g=document.createElement("button");g.type="button",g.className="primary",g.textContent=p("home.move.here","Make this machine the home"),g.setAttribute("data-testid","home-move-here-btn"),g.addEventListener("click",()=>{g.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),h.appendChild(g)}m.append(l,h),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let r=document.createElement("span");r.className="bp-dim",r.textContent="Sign out and revoke this browser's session cookie.";let a=document.createElement("button");a.type="button",a.className="primary stop",a.textContent=p("agy.signout","Sign out"),a.setAttribute("data-testid","logout-btn"),a.addEventListener("click",()=>{a.disabled=!0,this.cb.onLogout().catch(()=>{r.setAttribute("role","alert"),r.textContent=p("web.logout.failed","Could not confirm sign-out. Try again."),a.disabled=!1})}),s.append(r,a),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let c=document.createElement("div");c.className="bp-set-head",c.textContent="Paired devices",o.appendChild(c);try{let m=await this.cb.onLoadDevices();if(m.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",o.appendChild(l)}else for(let l of m){let h=document.createElement("div");h.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let b=document.createElement("div");if(b.textContent=l.title||l.head||"",d.appendChild(b),l.text||l.detail){let E=document.createElement("div");E.className="bp-dim",E.textContent=l.text||l.detail||"",d.appendChild(E)}if(h.appendChild(d),l.buttons?.length){let E=document.createElement("div");E.className="bp-set-btns";for(let w of l.buttons){let g=document.createElement("button");if(g.type="button",w.primary)g.className="primary";if(w.danger)g.className="primary stop";g.textContent=w.label||p("common.remove","Remove"),g.addEventListener("click",()=>{g.disabled=!0,this.cb.onDevicesAct(w.action,w.value).finally(()=>{this.refresh()})}),E.appendChild(g)}h.appendChild(E)}o.appendChild(h)}}catch(m){let l=document.createElement("div");l.className="bp-dim";let h=m instanceof Error&&m.message?m.message:"Not available from a browser";l.textContent=`${h} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(l)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function ge(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function mt(e,t,n=!1){let i=ge("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function Jt(e){return ge("pre","bp-context-code",e)}function Wi(e){return ge("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,fe(e))}function Nt(e,t){let n=ge("div","bp-context-row");return n.append(ge("strong",void 0,e),Wi(t)),n}class Yt{fetchContext;dialog=ge("dialog","bp-context");title=ge("h2");cwd=ge("div","bp-context-path");tabs=ge("div","bp-context-tabs");body=ge("div","bp-context-body");notice=ge("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=ge("div","bp-context-head"),i=ge("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,mt(p("common.refresh","Refresh"),()=>{this.load()}),mt(p("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=p("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=p("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[p("thread.context.instructions","Instructions"),p("thread.context.system","System Prompt"),p("thread.context.skills","Skills"),p("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=mt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(ge("p","bp-dim",p("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=ge("details","bp-context-card"),i=ge("summary");if(i.append(Nt(t.path,t.status),ge("small","bp-dim",p("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,Jt(t.preview)),t.note)n.append(ge("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=ge("div","bp-context-row"),n=mt(p("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=p("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(ge("p","bp-dim",p("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[p("thread.context.base","Backplane"),e.sections.base],[p("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[p("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(ge("h3",void 0,i),Jt(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(ge("h3",void 0,fe(t)));for(let i of n){let s=ge("article","bp-context-card");s.append(Nt(i.name,i.status),ge("p",void 0,i.description),ge("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),ge("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(ge("p","bp-dim",p("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=ge("article","bp-context-card");n.append(Nt(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((a)=>JSON.stringify(a)).join(" ");if(n.append(Nt(s.name,s.status),Jt(r)),s.cwd)n.append(ge("small","bp-context-path",s.cwd))}if(t.error)n.append(ge("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?p("thread.context.trust","Trust and enable"):i==="disable"?p("thread.context.disable","Disable"):p("thread.context.enable","Enable"),r=mt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=ge("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}var Jn="http://www.w3.org/2000/svg";function Yn(){let e=document.createElementNS(Jn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Jn,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function _i(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Xn(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class Xt{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=p("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=p("thread.new","New thread"),c.setAttribute("aria-label",p("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),a.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?p("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):p("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?p("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):p("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=p("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=p("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=p("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=p("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=p("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=p("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),n.appendChild(h)}let i=document.createElement("span");i.className=`bp-dot ${_i(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let h=document.createElement("span");if(h.className="bp-badge-need",h.textContent=e.want==="approval"?"!":"•",e.say)h.title=e.say;n.appendChild(h)}else if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=p("tools.pinned","Pinned");n.appendChild(h)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let a=e.kind==="swarm"?zn(e.need):null;if(!a)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=a.line,m.title=a.line,c.appendChild(m);for(let h of a.actions){if(!Lt(h,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=h.label,d.setAttribute("data-testid",`need-${h.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(b)=>{b.stopPropagation();let E=this.cb.onNeedAct;if(!E)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),E(h).catch((w)=>{this.needErr.set(e.id,w instanceof Error?w.message:String(w))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=l,o.appendChild(h)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id);else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&a.rows.length>0)r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",a.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=a.title.toUpperCase(),c.appendChild(m);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(a.kind==="projects"){let o=a.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(a.fold&&a.toggle);if(t&&o.length===0)continue;if(!c&&a.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",a.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=a.count??o.length,d=a.open?"▾":"▸";if(l.textContent=`${a.title.toUpperCase()} (${h}) ${d}`,a.hint)l.title=a.hint;l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),m.appendChild(l)}else m.appendChild(this.projectsHead(a.title.toUpperCase()));if(!c||a.open||Boolean(t)){if(a.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",m.appendChild(l)}for(let l of o){let h=document.createElement("div");if(h.className="bp-proj-group"+(l.off?" bp-dim":""),h.setAttribute("data-project-id",l.id),l.nav||l.key)h.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let E=Yn();if(l.css)E.style.color=l.css;let w=document.createElement("span");if(w.className="bp-proj-name",w.textContent=l.title||l.id,b.append(E,w),l.fold==="project-fold"&&l.nav)b.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let g=document.createElement("button");if(g.type="button",g.className="icon bp-proj-add",g.title=p("thread.new","New thread"),g.textContent="+",g.setAttribute("data-testid",`new-thread-${l.id}`),l.off)g.disabled=!0;if(g.addEventListener("click",(v)=>{v.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(b,g),h.appendChild(d),!l.folded||Boolean(t)){let v=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let y of l.swarms??[]){if(t&&!v&&!y.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(y,!0))}for(let y of l.threads??[]){if(t&&!v&&!y.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(y,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||v||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Xn(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(h)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,m=Yn();if(i.css)m.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(m,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=p("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${i.id}`),h.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,h),r.appendChild(a),!c)for(let d of s)r.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:Xn(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=p("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let h=document.createElement("div");h.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let b=document.createElement("div");b.className="bp-thread-title",b.textContent=`@${l.name}`,h.append(d,b),h.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(h)}e.appendChild(n);let a=document.createElement("section");a.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=p("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(c,m),a.appendChild(o);for(let l of this.rooms){let h=document.createElement("div");h.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,h.appendChild(d),a.appendChild(h)}e.appendChild(a)}this.listEl.replaceChildren(e)}}function qi(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function ut(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function zi(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/m:0));s[r]=l<0?l*32768:l*32767}return s}class Qt{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){ut(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(ut(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(ut(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?qi(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(ut(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let r=this.stopDrain.then(async()=>{if(t&&i){let a=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(a.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),r=String(e.ins??""),a=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,a-s),c=i.slice(0,o)+r+i.slice(a);this.mark=o+r.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(a)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=zi(a.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;ut(this.stream),this.stream=null}}var Qn=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Zn=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ei=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ti=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ki=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function bt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let o=1;o<=15;o++)s[o]=r,r+=n[o];let a=new Int32Array(r);for(let o=0;o0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var Ji=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),bt(e,288)})(),Yi=(()=>{let e=new Uint8Array(32);return e.fill(5),bt(e,32)})();class Zt{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,d},a=(h)=>{let d=0,b=0,E=0;for(let w=1;w<=h.maxBits;w++){d|=r(1);let g=h.counts[w];if(d-g{let d=c+h;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let b=o.length;while(b{m(1),o[c++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let b=e[n]|e[n+1]<<8,E=e[n+2]|e[n+3]<<8;if(n+=4,(b^65535)!==E)throw Error("invalid stored block length");if(n+b>e.length)throw Error("truncated stored payload");m(b);for(let w=0;w=e.length)break}else if(d===1||d===2){let b=Ji,E=Yi;if(d===2){let w=r(5)+257,g=r(5)+1,v=r(4)+4,y=new Uint8Array(19);for(let M=0;MS)throw Error("code length overflow");for(let V=0;VS)throw Error("code length overflow");T+=F}else if(M===18){let F=r(7)+11;if(T+F>S)throw Error("code length overflow");T+=F}else throw Error("invalid code length symbol")}b=bt(L,w),E=bt(L.subarray(w),g)}while(!0){let w=a(b);if(w<256)l(w);else if(w===256)break;else{let g=w-257;if(g>=Qn.length)throw Error("invalid length symbol");let v=Qn[g]+(Zn[g]?r(Zn[g]):0),y=a(E);if(y>=ei.length)throw Error("invalid distance symbol");let x=ei[y]+(ti[y]?r(ti[y]):0);m(v);let S=this.winPos-x&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new Zt:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";a.reject(Error(c))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Xi=new TextDecoder;function ni(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function ii(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let l=e.subarray(t,t+m);return t+=m,l}case 3:{if(t+m>e.length)return null;let l=Xi.decode(e.subarray(t,t+m));return t+=m,l}case 4:{if(m>e.length)return null;let l=Array(m);for(let h=0;h=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function ri(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[w]==="number"?e[w]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new si(m),h=[],d=[],b=0,E=0;while(l.more()){let w=l.nextU32(),g=h.length,v=1/0,y=1/0,x=-1/0,S=-1/0;if(r===2)b=b+l.nextI32()|0,E=E+l.nextI32()|0,h.push(b,E),v=x=b,y=S=E;else{let T=Math.min(l.nextU32(),1048576);for(let M=0;Mx)x=b;if(ES)S=E}}let L=(h.length-g)/2;if(L>0){let T=r===2||L===1?2:r===0?0:1,M=r===0?0:o;d.push({info:w,x0:v-M,y0:y-M,x1:x+M,y1:S+M,at:g,n:L,kind:T})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(h),pieces:d}}function ai(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function oi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,m=(e-o)/r,l=(t-c)/a;if(m<0||m>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var li=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ci(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class tn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function di(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,m=-1,l=null,h=new tn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let b=document.createElement("div");b.className="bp-pane-bar bp-browser-nav";function E(Y,oe,B){let W=document.createElement("button");if(W.type="button",W.className="bp-v-btn",W.textContent=Y,W.setAttribute("data-testid",oe),B)W.title=B;return W}let w=E("←","browser-back","Back"),g=E("→","browser-forward","Forward"),v=E("↻","browser-reload","Reload"),y=document.createElement("form");y.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let S=E("Go","browser-go","Navigate");S.type="submit",y.append(x,S);let L=E("Take over","browser-takeover");L.classList.add("is-primary"),b.append(w,g,v,y,L);let T=document.createElement("div");T.className="bp-browser-drive-bar",T.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let F=document.createElement("input");F.type="text",F.className="bp-browser-input",F.placeholder="Type text or press Enter/Tab/Arrows…",F.autocomplete="off",F.spellcheck=!1,F.setAttribute("data-testid","browser-keys");let z=E("Send","browser-type-send");M.append(F,z);let V=document.createElement("div");V.className="bp-browser-quick-keys";for(let[Y,oe]of li){let B=E(Y,`browser-key-${oe}`);B.addEventListener("click",()=>I("press",{key:oe})),V.append(B)}T.append(M,V);let R=document.createElement("div");R.className="bp-browser-err",R.setAttribute("data-testid","browser-error"),R.hidden=!0;let N=document.createElement("div");N.className="bp-browser-stage",N.setAttribute("data-testid","browser-stage");let _=document.createElement("img");_.className="bp-browser-img",_.alt="Hub browser screen",_.draggable=!1,_.hidden=!0,_.setAttribute("data-testid","browser-frame");let q=document.createElement("div");q.className="bp-pane-empty",q.setAttribute("data-testid","browser-empty"),q.textContent="Loading browser screen…",N.append(_,q);let ie=document.createElement("div");ie.className="bp-browser-hint",ie.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ie.hidden=!0,d.append(b,T,R,N,ie),e.replaceChildren(d);function ae(Y){R.textContent=Y,R.hidden=!Y}function le(){T.hidden=!s,ie.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),_.classList.toggle("is-driving",s)}function I(Y,oe={},B){h.enqueue(async()=>{if(!i)return;ae("");try{if(await t.hub.rpc("browser",{thread:n,op:Y,...oe}),!i)return;B?.(),de()}catch(W){if(!i)return;ae(W instanceof Error?W.message:String(W))}})}function ve(Y){I("toolbar",{command:Y},()=>{s=!0,le()})}w.addEventListener("click",()=>ve("back")),g.addEventListener("click",()=>ve("forward")),v.addEventListener("click",()=>ve("reload")),y.addEventListener("submit",(Y)=>{Y.preventDefault();let oe=ci(x.value);if(!oe)return;if(x.value=oe,!s)I("takeover",{},()=>{s=!0,le()});I("navigate",{url:oe},()=>{s=!0,le()})}),L.addEventListener("click",()=>{if(s)I("handback",{},()=>{s=!1,le()});else I("takeover",{},()=>{s=!0,le(),F.focus()})});function A(){let Y=F.value;if(!Y)return;F.value="",I("type",{text:Y})}z.addEventListener("click",A),F.addEventListener("keydown",(Y)=>{if(!s)return;if(Y.key==="Enter"){if(Y.preventDefault(),F.value)A();I("press",{key:"Enter"});return}if(Y.key==="Tab"||Y.key==="Escape"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="ArrowLeft"||Y.key==="ArrowRight"||Y.key==="Backspace"&&F.value==="")Y.preventDefault(),I("press",{key:Y.key})}),_.addEventListener("click",(Y)=>{if(!s||!r)return;let oe=_.getBoundingClientRect(),B=oi(Y.clientX,Y.clientY,{left:oe.left,top:oe.top,width:oe.width,height:oe.height,naturalWidth:_.naturalWidth,naturalHeight:_.naturalHeight});if(!B)return;I("click",B)}),_.addEventListener("wheel",(Y)=>{if(!s||!r)return;Y.preventDefault();let oe=Math.round(Y.deltaX),B=Math.round(Y.deltaY);if(oe===0&&B===0)return;I("scroll",{dx:oe,dy:B})},{passive:!1});async function de(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let Y=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(Y.ok){let oe=await Y.blob();if(!i)return;let B=URL.createObjectURL(oe),W=a;if(a=B,_.src=B,_.hidden=!1,q.hidden=!0,r=!0,W)URL.revokeObjectURL(W)}else if(!r)_.hidden=!0,q.hidden=!1,q.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)_.hidden=!0,q.hidden=!1,q.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let se=t.hub.onFrame((Y)=>{if(!i)return;if(Y.t==="shot"&&Y.bot===n){if(typeof Y.n==="number"){if(Y.n===m)return;m=Y.n}de()}});return de(),{destroy(){if(i=!1,se(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function U(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Tt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function hi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Zi(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function pi(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function es(e){let t=hi(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function mi(e,t,n,i){let s=!0,r="",a="",o=U("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=U("div","bp-pane-bar"),m=U("div","bp-files-crumbs"),l=U("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void g(r)),c.append(m,l);let h=U("div","bp-files-split"),d=U("div","bp-files-list");d.setAttribute("data-testid","files-list");let b=U("div","bp-files-preview");b.setAttribute("data-testid","files-preview"),b.append(U("div","bp-pane-empty","Select a file to preview")),h.append(d,b),o.append(c,h),e.replaceChildren(o);function E(){m.replaceChildren();let v=U("button","bp-crumb-btn","project");if(v.type="button",v.addEventListener("click",()=>void g("")),m.append(v),!r)return;let y=r.split("/").filter(Boolean),x="";for(let S of y){x=x?`${x}/${S}`:S;let L=x;m.append(U("span","bp-vh-sep","/"));let T=U("button","bp-crumb-btn",S);T.type="button",T.addEventListener("click",()=>void g(L)),m.append(T)}}async function w(v,y,x){a=v,b.replaceChildren();let S=U("div","bp-files-prev-head");S.append(U("span","bp-files-prev-name",v));let L=U("div","bp-files-prev-acts"),T=es(y);if(T){let V=U("button","bp-v-btn is-primary",`Open in ${T}`);V.type="button",V.setAttribute("data-testid","files-open-viewer"),V.addEventListener("click",()=>i(T,v)),L.append(V)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(v)}`,F=U("a","bp-v-btn","Download");F.href=M,F.download=y,L.append(F),S.append(L),b.append(S);let z=hi(y);if(Zi(z)){let V=U("div","bp-files-img-wrap"),R=document.createElement("img");R.className="bp-files-img",R.alt=y,R.src=M,V.append(R),b.append(V);return}if(x>524288&&!pi(z)){b.append(U("div","bp-pane-empty",`Binary file (${Tt(x)}). Use Download to save.`));return}if(pi(z)||x<=65536){let V=U("div","bp-pane-empty","Loading…");b.append(V);try{let R=await fetch(M,{credentials:"same-origin"});if(!s||a!==v)return;if(!R.ok){V.textContent=`Could not load file (${R.status})`;return}if((R.headers.get("content-type")||"").startsWith("image/")){V.remove();let se=document.createElement("img");se.className="bp-files-img",se.alt=y,se.src=M,b.append(se);return}let _=262144,q=[],ie=0,ae=!1;if(R.body){let se=R.body.getReader();try{while(!0){let{done:Y,value:oe}=await se.read();if(Y||!oe)break;if(ie+oe.byteLength>_){let B=_-ie;if(B>0)q.push(oe.subarray(0,B)),ie+=B;ae=!0,await se.cancel();break}q.push(oe),ie+=oe.byteLength}}finally{se.releaseLock()}}if(!s||a!==v)return;let le=new Uint8Array(ie),I=0;for(let se of q)le.set(se,I),I+=se.byteLength;let ve=!1;for(let se=0;seS.dir===L.dir?S.name.localeCompare(L.name):S.dir?-1:1),d.replaceChildren(),v){let S=U("button","bp-file-row is-dir");S.type="button",S.append(U("span","bp-file-icon","↰"),U("span","bp-file-name",".."));let L=v.includes("/")?v.slice(0,v.lastIndexOf("/")):"";S.addEventListener("click",()=>void g(L)),d.append(S)}if(x.length===0){d.append(U("div","bp-pane-empty","Empty folder"));return}for(let S of x){let L=v?`${v}/${S.name}`:S.name,T=U("button","bp-file-row"+(S.dir?" is-dir":"")+(L===a?" is-sel":""));T.type="button",T.setAttribute("data-testid",`file-row-${S.name}`),T.append(U("span","bp-file-icon",S.dir?"▸":"·"),U("span","bp-file-name",S.name),U("span","bp-file-size",S.dir?"":Tt(S.size))),T.addEventListener("click",()=>{if(S.dir)g(L);else d.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),T.classList.add("is-sel"),w(L,S.name,S.size)}),d.append(T)}}catch(y){if(!s)return;d.replaceChildren(U("div","bp-pane-empty",y instanceof Error?y.message:String(y)))}}return g(""),{destroy(){s=!1}}}function ui(e,t,n){let i=!0,s=U("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=U("div","bp-pane-bar"),a=U("span","bp-diff-summary","Loading diff…"),o=U("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),r.append(a,o);let c=U("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function m(){a.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){a.textContent="Not a git repository",c.append(U("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof l?.diff==="string"?l.diff:"";if(!h.trim()){a.textContent="Clean working tree",c.append(U("div","bp-pane-empty","No uncommitted changes."));return}let d=h.split(` -`),b=0,E=0,w=0,g=document.createDocumentFragment(),v=U("div","bp-diff-file");for(let y of d){if(y.startsWith("diff --git ")){if(v.childNodes.length>0)g.append(v);v=U("div","bp-diff-file"),b++;let x=y.match(/ b\/(.+)$/);v.append(U("div","bp-diff-file-head",x?x[1]:y));continue}if(y.startsWith("index ")||y.startsWith("--- ")||y.startsWith("+++ "))v.append(U("div","bp-diff-line is-meta",y));else if(y.startsWith("@@"))v.append(U("div","bp-diff-line is-hunk",y));else if(y.startsWith("+"))E++,v.append(U("div","bp-diff-line is-add",y));else if(y.startsWith("-"))w++,v.append(U("div","bp-diff-line is-del",y));else v.append(U("div","bp-diff-line",y))}if(v.childNodes.length>0)g.append(v);a.textContent=`${b||1} file${b===1?"":"s"} · +${E} -${w}`,c.append(g)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(U("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return m(),{destroy(){i=!1}}}function bi(e,t,n){let i=!0,s="checks",r=U("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=U("div","bp-pane-bar"),o=U("div","bp-review-tabs"),c=U("button","bp-v-btn is-on","Checks"),m=U("button","bp-v-btn","BOM"),l=U("button","bp-v-btn","Comments");c.type=m.type=l.type="button",o.append(c,m,l);let h=U("button","bp-v-btn","Refresh");h.type="button",h.addEventListener("click",()=>void w()),a.append(o,h);let d=U("div","bp-review-body");d.setAttribute("data-testid","review-body"),r.append(a,d),e.replaceChildren(r);function b(g){s=g,c.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),w()}c.addEventListener("click",()=>b("checks")),m.addEventListener("click",()=>b("bom")),l.addEventListener("click",()=>b("comments"));function E(g){let v=U("div","bp-review-md"),y=g.split(` -`),x=0;while(x{M.preventDefault();let F=L.value.trim();if(!F)return;T.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:F}).then(()=>{L.value="",T.disabled=!1,w()},()=>{T.disabled=!1})}),d.append(S),x.length===0){d.append(U("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let F=U("div","bp-review-comment"+(M.resolved?" is-resolved":"")),z=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");F.append(U("div","bp-review-comment-meta",z),U("div","bp-review-comment-text",M.text)),d.append(F)}return}let g=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let v=g?.report||{};if(d.replaceChildren(),v.line||v.gate){let y=U("div","bp-review-gate",[v.gate,v.line].filter(Boolean).join(" · "));d.append(y)}if(v.err)d.append(U("div","bp-review-err",v.err));if(Array.isArray(v.tasks)&&v.tasks.length>0){let y=U("div","bp-review-tasks");v.tasks.forEach((x,S)=>{let L=U("label","bp-review-task"),T=document.createElement("input");T.type="checkbox",T.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:S;T.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void w(),()=>{})}),L.append(T,U("span",void 0,x.text||x.label||`Item ${S+1}`)),y.append(L)}),d.append(y)}if(v.md&&v.md.trim())d.append(E(v.md));else if(!v.err&&(!v.tasks||v.tasks.length===0))d.append(U("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(g){if(!i)return;d.replaceChildren(U("div","bp-pane-empty",g instanceof Error?g.message:String(g)))}}return w(),{destroy(){i=!1}}}function fi(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class nn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,m/a)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,m=n*0.5,l=this.scale,h=this.cx,d=this.cy,b=h-c/l,E=h+c/l,w=d-m/l,g=d+m/l,{off:v,dim:y,lift:x}=this.masks,S=[],L=[];for(let M=0;M>>F&1)===1)continue;if(F===x)L.push(M);else S.push(M)}let T=S.concat(L);a.lineCap="round",a.lineJoin="round";for(let M=0;M>>z.layer&1)===1,R=z.alpha*(V?0.25:1);if(R<=0.01)continue;this.drawChunk(a,z,R,b,w,E,g,h,d,l,c,m)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let F=0;Fr||g.y1a)continue;if(g.n<3)continue;let v=(d[g.at]-o)*m+l,y=(d[g.at+1]-c)*m+h;e.moveTo(v,y);for(let x=1;x0)e.fill()}else if(t.mode===2){let E=Math.max(0.75,t.r*m);e.fillStyle=b,e.beginPath();let w=0;for(let g=0;gr||v.y1a)continue;let y=(d[v.at]-o)*m+l,x=(d[v.at+1]-c)*m+h;e.moveTo(y+E,x),e.arc(y,x,E,0,Math.PI*2),w++}if(w>0)e.fill()}else{e.strokeStyle=b,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let E=0;for(let w=0;wr||g.y1a)continue;let v=(d[g.at]-o)*m+l,y=(d[g.at+1]-c)*m+h;if(g.n===1)e.moveTo(v,y),e.lineTo(v+0.01,y);else{e.moveTo(v,y);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,m,l,h,d){let b=t.pts,E=fi(t.color,t.alpha);for(let w=0;wa||g.y1o)continue;let v=(b[g.at]-c)*l+h,y=(b[g.at+1]-m)*l+d;if(g.kind===2){let x=Math.max(1.5,t.r*l);e.fillStyle=E,e.beginPath(),e.arc(v,y,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(g.kind===0&&g.n>=3){e.fillStyle=E,e.beginPath(),e.moveTo(v,y);for(let x=1;x=0;l--){let h=n.chunks[l];if(h.layer<32&&(m>>>h.layer&1)===1)continue;for(let d=0;db.x1+a||rb.y1+a)continue;let E=(b.x1-b.x0+1)*(b.y1-b.y0+1);if(E{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,h=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-h/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var gi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function vi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function sn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class rn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var ts=`#version 300 es +`),u=document.createElement("div");u.className="bp-code-block";let d=document.createElement("div");d.className="bp-code-head";let p=document.createElement("span");p.className="bp-code-lang",p.textContent=c||"code";let b=document.createElement("button");b.type="button",b.className="bp-btn-ghost bp-code-copy";let y=h("common.copy","Copy");b.textContent=y,b.addEventListener("click",()=>{navigator.clipboard?.writeText(l).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),d.append(p,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=l,f.appendChild(g),u.append(d,f),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let c=document.createElement(`h${Math.min(4,a[1].length+1)}`);c.className="bp-md-h",ut(c,a[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ut(c,m.join(` +`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));ut(o,r[c])}t.appendChild(o)}return t}var Tn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Tn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Tn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function _t(e){return e<10000000000?e*1000:e}function is(e){if(!e)return"";return new Date(_t(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ss(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Wt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class qt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!Wt(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!Wt(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Wt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=h("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let u=is(e.at);if(t)l.textContent=u,i.append(s,...m?[o]:[],l);else{let d=n&&e.at?ss(_t(e.at)-_t(n)):"",p=u?d?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:d}):h("web.chat.finished","Finished {time}",{time:u}):"";l.textContent=e.live?h("web.chat.streaming","Streaming…"):p,i.append(l,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,l.appendChild(u),a.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=a.tool.summary,l.appendChild(d)}r.appendChild(l),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let l=a.ask;if(l.kind==="plan"){r.appendChild(this.renderPlanAsk(l)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,u.appendChild(d),l.state==="open"){let p=document.createElement("div");if(p.className="bp-ask-opts",l.options&&l.options.length>0)for(let b of l.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,b.id)),p.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=h("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=h("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(l.id,b.value.trim())}),p.append(b,y)}u.appendChild(p)}else{let p=document.createElement("div");p.className="bp-ask-answered",p.textContent=h("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),u.appendChild(p)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),c=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!c&&!m&&!a.live)continue;if(a.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};l.addEventListener("click",d),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"||p.key===" ")p.preventDefault(),d()}),r.appendChild(l)}if(o||a.live){let l=document.createElement("div");if(l.className="bp-entry-body",a.kind==="user")l.textContent=a.text;else l.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,l);r.appendChild(l)}if(m&&a.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=u.previewUrl,d.alt=u.name||"attachment",l.appendChild(d)}else if(u.path||u.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=u.name||u.path||"image",l.appendChild(d)}if(l.childElementCount>0)r.appendChild(l)}if(a.images&&a.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let u of a.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=u;let p=`${a.id}|${u}`,b=this.imageCache.get(p);if(b)d.src=b;else this.cb.onLoadImage(a.id,u).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(p,f),d.src=f});l.appendChild(d)}r.appendChild(l)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):Ee(e.head),s.append(a,r),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let u=h("common.copy","Copy"),d=document.createElement("span");d.textContent=u,l.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=u},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let u=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=u?.label&&u.label!=="Implement"?Ee(u.label):h("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),l.appendChild(d),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(y)}let p=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=p?.label&&p.label!=="Dismiss"?Ee(p.label):h("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"dismiss")}),l.appendChild(b),i.appendChild(l),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=h("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let w=()=>{let L=f.value.trim();if(!L)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${L}`)},k=()=>{this.closePlanRevise()};y.addEventListener("keydown",(L)=>{if(L.key==="Escape")L.preventDefault(),L.stopPropagation(),k()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(L)=>{if(L.key==="Enter"&&!L.shiftKey)L.preventDefault(),w()}),g.addEventListener("click",w);let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost",S.textContent=h("common.cancel","Cancel"),S.addEventListener("click",k),y.append(f,g,S),i.appendChild(y)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Bn="http://www.w3.org/2000/svg",In=4,Rn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Kt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function jn(){return Pt(["M6 4l14 8-14 8z"])}function as(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class zt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Kt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let m=c.clipboardData?.items;if(!m)return;let l=[];for(let u=0;u0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=as(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?jn():Kt()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?jn():Kt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let c=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let l=(u,d,p,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(d?" active":""),y.textContent=u,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(p)),y};m.append(l(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(m)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Rn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=In){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:In}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Hn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var rs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&rs.has(t.id))}function Gn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var os=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ls=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Un(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(os.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ls.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function On(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Vn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function Wn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Jt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function _n(e){return e.state==="routed"||e.state==="verified"}function qn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Kn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function zn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Jn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Yn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Yt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Xn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Xt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Dn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Fn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Zn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Dn[Zn(i)%Dn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Fn[Zn(e)%Fn.length]}function Qn(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ke(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ei(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ti(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(r,Math.min(o,e.scale*t)),[m,l]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/c,cy:l-(i-a*0.5)/c,scale:c,touched:!0}}function ni(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function ii(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Zt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function cs(e,t,n,i,s,a){let r=s-n,o=a-i,c=r*r+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/c)),l=n+m*r,u=i+m*o;return(e-l)*(e-l)+(t-u)*(t-u)}function $n(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(c-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function Qt(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let p=d.path??[];for(let b=0;b=3)for(let b=0;b=0;d--){let p=t[d];if(p.layer!==n)continue;let b=p.outline??[];if(!$n(l,u,b))continue;if(!(p.holes??[]).some((f)=>$n(l,u,f)))return{kind:"region",id:p.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,c=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((c>0||a.role==="power"||a.role==="plane")&&(!n||c>n.count))n={count:c,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function si(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[l,u]=Ke(t,m.b[0],m.b[1],n,i),[d,p]=Ke(t,m.b[2],m.b[3],n,i),b=Math.abs(d-l),y=Math.abs(p-u);if(b<13||y<9)continue;let f=(l+d)*0.5,g=(u+p)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,l)=>l.score-m.score);let o=[],c=[];for(let m of r){let l=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((d)=>!(l[2]<=d[0]||l[0]>=d[2]||l[3]<=d[1]||l[1]>=d[3])))o.push(l),c.push({text:m.text,cx:m.cx,cy:m.cy})}return c}var ai="#111917",ds="#16201d",ps="rgba(212, 224, 219, 0.92)",ms="rgba(61, 80, 73, 0.72)",hs="rgba(82, 107, 97, 0.85)",us="rgba(143, 163, 155, 0.88)",ri="#f59e0b",bs="#eef5f2",oi="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function gs(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function fs(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function vs(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class en{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){if(e.layers.length===0)return[];if(e.gridMode==="all")return e.layers;if(e.gridMode==="single"){let i=e.shownLayers.find((a)=>e.layers.some((r)=>r.layer===a))??rt(e.layers)[0]??e.layers[0]?.layer,s=e.layers.find((a)=>a.layer===i);return s?[s]:[]}let t=e.shownLayers.length>0&&e.shownLayers.every((i)=>e.layers.some((s)=>s.layer===i))?e.shownLayers.slice(0,2):rt(e.layers),n=[];for(let i of t){let s=e.layers.find((a)=>a.layer===i);if(s)n.push(s)}return n.length>0?n:e.layers.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return Qn(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=h("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,c,m);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let p=document.createElement("div");p.className="bp-plan-hover-hud bp-hidden",u.append(d,p);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=d.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(d,e.layer);let g={layer:e.layer,el:t,canvas:d,ctx:y,legendEl:b,okBtn:c,noBtn:m,statusEl:o,titleEl:r,subtitleEl:l,hoverHudEl:p,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=vs(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let c=document.createElement("button");c.type="button";let m=this.state?.selectedId===o.id;c.className="bp-plan-legend-chip"+(m?" active":"");let l=document.createElement("span");l.className="bp-plan-legend-sw",l.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,c.append(l,u),c.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(c)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(n)=>n.preventDefault()),e.addEventListener("pointerdown",(n)=>{let i=this.state;if(!i)return;this.root.focus();let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r);if(n.button===2){if(l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane),d=Zt(u,l.idx,l.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(l.id,{[l.isPlane?"outline":"path"]:d})}return}if(n.button!==0)return;if(e.setPointerCapture(n.pointerId),this.downPos={x:n.clientX,y:n.clientY},l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane);this.selectedVertex={id:l.id,idx:l.idx},this.cb.onSelect(l.id),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:l.idx,pts:u.map((d)=>[d[0],d[1]])},this.scheduleDraw()}else if(l?.kind==="midpoint"){let u=this.getItemPts(l.id,l.isPlane),d=ii(u,l.segIdx,l.pos,l.isPlane),p=l.isPlane&&l.segIdx+1>=u.length?d.length-1:Math.min(l.segIdx+1,d.length-1);this.cb.onSelect(l.id),this.selectedVertex={id:l.id,idx:p},this.patchLocalItem(l.id,l.isPlane,d),this.cb.onOptimisticPatch(l.id,{[l.isPlane?"outline":"path"]:d}),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:p,pts:d},this.scheduleDraw()}else{if(l&&(l.kind==="band"||l.kind==="region"))this.cb.onSelect(l.id);this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:r}}}),e.addEventListener("pointermove",(n)=>{let i=this.state;if(!i)return;let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let w=this.getCam(t,o,c);this.setCam(t,ei(w,a-this.drag.lastX,r-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=r,this.scheduleDraw();return}let p=this.getCam(t,o,c),[b,y]=Bt(p,a,r,o,c),f=[Math.round(b*1000)/1000,Math.round(y*1000)/1000];this.drag.pts[this.drag.idx]=f;let g=this.drag.pts.map((w)=>[w[0],w[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,g),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:g}),this.scheduleDraw();return}let m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r),u=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=l?l.id:"";if(this.hover=l?{layer:t,hit:l}:null,e.style.cursor=l?.kind==="vertex"||l?.kind==="midpoint"?"pointer":l?"pointer":"crosshair",u!==d||l?.kind!==this.hover?.hit.kind)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerup",(n)=>{let i=this.state,s=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(n.pointerId))e.releasePointerCapture(n.pointerId);if(s&&s.kind==="vertex"&&s.layer===t){this.cb.onCommitFields(s.id,{[s.isPlane?"outline":"path"]:s.pts});return}if(n.detail>=2){this.fitAll();return}if(i&&a&&Math.hypot(n.clientX-a.x,n.clientY-a.y)<4.5){let r=e.getBoundingClientRect(),o=n.clientX-r.left,c=n.clientY-r.top,m=Math.max(1,r.width),l=Math.max(1,r.height),u=this.getCam(t,m,l),d=It(i.bands,i.regions,t,i.selectedId,u,m,l,o,c);if(d&&(d.kind==="band"||d.kind==="region"))this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);else if(!d)this.cb.onSelect("")}}),e.addEventListener("wheel",(n)=>{n.preventDefault();let i=e.getBoundingClientRect(),s=n.clientX-i.left,a=n.clientY-i.top,r=Math.max(1,i.width),o=Math.max(1,i.height),c=this.getCam(t,r,o),m=Math.max(0.65,Math.min(1.55,1-n.deltaY*0.002));this.setCam(t,ti(c,m,s,a,r,o)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),c=Zt(o,this.selectedVertex.idx,r);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),c=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(p,b)=>Ke(a,p,b,n,i);e.fillStyle=ai,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((p)=>p.length>=3);if(e.fillStyle=ds,o.length>0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let p of c){let b=p.outline??[];if(b.length<3)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=fs(p.state||"proposed",y,f),w=ft(p.net||p.id,p.color||"");e.beginPath();for(let k=0;k0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),d=[];for(let p of u){for(let b of p.from??[])d.push(b);for(let b of p.to??[])d.push(b)}e.fillStyle=us,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let p of si(l,a,n,i,d))e.fillText(p.text,p.cx,p.cy);for(let p of u){let b=p.guides??[];if(b.length===0)continue;let y=s.selectedId===p.id||m?.id===p.id,f=vt(p.name||p.id,p.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[w,k]=r(g[0],g[1]),[S,L]=r(g[2],g[3]);e.moveTo(w,k),e.lineTo(S,L)}e.stroke()}for(let p of u){let b=p.path??[];if(b.length<2)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=gs(p.state||"proposed",y,f),w=vt(p.name||p.id,p.color||""),k=Qt(p.width??1.5,a.scale),S=()=>{e.beginPath();for(let M=0;M0){let M=ni(b);if(M){let[B,H]=r(M[0],M[1]),W=String(L),_=Math.max(16,W.length*6.5+8),j=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(B-_*0.5,H-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":w,e.strokeRect(B-_*0.5,H-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,B,H+0.5)}}}if(s.selectedId){let p=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let r=document.createElement("button");r.type="button";let o=this.openPanel===a.id;r.className="bp-mgmt-tab"+(o?" active":""),r.setAttribute("data-testid",`mgmt-tab-${a.id}`),r.setAttribute("aria-pressed",o?"true":"false");let c=document.createElement("span");c.textContent=Ee(a.label),r.appendChild(c);let m=this.getPanelData(a.id),l=Gn(m);if(l){let u=document.createElement("span");u.className=`bp-mgmt-badge bp-tone-${l.tone}`,u.textContent=l.text,r.appendChild(u)}r.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(r)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=h("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,s.appendChild(a)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=Ee(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),m.appendChild(l),e.appendChild(m)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Vn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),c.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),c.appendChild(y)}else{let y=On(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,c.appendChild(f)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",Un(a.footprint??"")].filter(Boolean).join(" · "),p=document.createElement("span");p.className="bp-dim",p.textContent=d;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(p,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=Ee(a.stock.class),u.appendChild(y)}o.append(c,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,p=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Yt(b,o()))return;this.bomLastUndo=!p&&(y.changed??0)>0?{project:d.project,editId:b.editId,refs:d.refs.slice(),field:d.field,was:typeof y.was==="string"?y.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=p?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Yt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(l,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn",p.textContent="Undo",p.addEventListener("click",()=>{c(Xn(d),!0)}),m.appendChild(p)}if(t.append(i,r,m),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),p.textContent=s(d)+(a(d)?" · judged":""),p.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(p)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let d=this.watchGen,p=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:p}).then(()=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(c,m),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let u=Wn(n,this.checksSource);if(u.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let p=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${p}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(d.source)} · ${d.rule}`;let g=document.createElement("span");g.className=`bp-tone-${p}`,g.textContent=String(d.n),b.append(y,f,g),l.appendChild(b);for(let w of d.rows??[]){let k=document.createElement("div");k.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=Ee(w.title??""),k.appendChild(S),w.names||this.checksSelectedId===w.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let M=document.createElement("span");if(M.className="bp-dim bp-mgmt-flex1",M.textContent=w.names??"",L.appendChild(M),this.checksSelectedId===w.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(H)=>{H.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:w.id}).then((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),L.appendChild(B)}k.appendChild(L)}k.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(k)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let m=i[c]??0,l=Jt(c),u=document.createElement("span");u.className=m>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",u.textContent=`${l.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(c,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=a[a.length-1],m=r[r.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${at(c[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,l=Jt(c.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let p=document.createElement("span");p.className="bp-mgmt-strong",p.textContent=Mt(c.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=c.mpn||c.key;let y=document.createElement("span");if(y.className=`bp-tone-${l.tone}`,y.textContent=l.label,d.append(p,b,y),typeof c.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(c.stock),d.appendChild(f)}if(u.appendChild(d),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((f)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(x,C)=>{let I=this.watchGen,G=this.project;this.planStatus="",this.cb.hub.rpc(x,{pro:G,...C}).catch((z)=>{if(I!==this.watchGen||G!==this.project)return;this.planOptimistic.clear(),this.planStatus=z instanceof Error?z.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydratedKey!==i&&this.project){this.planHydratedKey=i;let x=this.watchGen,C=this.project;this.cb.hub.rpc("plan.get",{pro:C,board:!0}).then((I)=>{if(x!==this.watchGen||C!==this.project||!I?.panel)return;this.planHydratedBoard=I.panel.board??null,this.planHydratedDraw=I.panel.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),c.setAttribute("data-testid","mgmt-plan-off"),c.setAttribute("aria-pressed",!a?"true":"false"),c.textContent=h("gpui.bots.recall.off","Off"),c.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,c),e.appendChild(s);for(let x of t.elsewhere??[]){let C=document.createElement("div");C.className="bp-plan-elsewhere";let I=document.createElement("span");I.className="bp-tone-warn bp-mgmt-flex1",I.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:x.name||x.rel||""}),C.appendChild(I),e.appendChild(C)}if(t.empty){let x=document.createElement("div");x.className="bp-mgmt-note";let C=document.createElement("div");C.className="bp-dim",C.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let I=document.createElement("div");return I.className="bp-mgmt-faint",I.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),x.append(C,I),e.appendChild(x),e}let m=t.awaiting??0,l=t.blocked??0,u=t.done??0,d=t.total??0,p=t.revision??0,b=Kn(t),y=zn(t),f=y.reduce((x,C)=>x+C.count,0),g=document.createElement("div");g.className="bp-plan-status";let w=document.createElement("div");w.className="bp-plan-status-top";let k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${b.tone}`,k.textContent=h(b.key,b.label),w.appendChild(k),p>0){let x=document.createElement("span");x.className="bp-dim",x.textContent=`v${p}`,w.appendChild(x)}let S=document.createElement("span");if(S.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":l>0?"bp-tone-bad":"bp-dim"),S.textContent=d>0?`${u}/${d} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),w.appendChild(S),!t.live){let x=document.createElement("span");x.className="bp-mgmt-pill",x.textContent=h("gpui.mgmt.plan.saved","saved plan"),w.appendChild(x)}if(g.appendChild(w),f>0){let x=document.createElement("div");x.className="bp-plan-segbar";for(let C of y){if(C.count<=0)continue;let I=document.createElement("div");I.className=`bp-plan-seg bp-tone-bg-${C.tone}`,I.style.flexGrow=String(C.count),x.appendChild(I)}g.appendChild(x)}e.appendChild(g);let L=document.createElement("div");if(L.className="bp-mgmt-head",m>0){let x=document.createElement("button");x.type="button",x.className="primary bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-approve-all"),x.textContent=h("gpui.mgmt.plan.all","Approve all"),x.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(x)}if(t.routing){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-stop"),x.textContent=h("gpui.mgmt.plan.stop","Stop routing"),x.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(x)}if(t.live&&u>0){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-verify"),x.textContent=h("gpui.mgmt.plan.verify","Verify"),x.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(x)}let M=document.createElement("span");M.className="bp-mgmt-flex1";let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.setAttribute("data-testid","mgmt-plan-hide"),B.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),B.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.append(M,B),e.appendChild(L);let H=Array.isArray(t.asks)?t.asks:[];if(H.length>0){let x=H.map((me)=>me.what||"").filter(Boolean).join(", "),C=H[0]?.note||"",I=document.createElement("div");I.className="bp-plan-elsewhere";let G=document.createElement("div");G.className="bp-plan-ask-col";let z=document.createElement("div");if(z.className="bp-tone-warn",z.textContent=x?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:x}):h("gpui.mgmt.plan.reqplain","Approval requested"),G.appendChild(z),C){let me=document.createElement("div");me.className="bp-dim",me.textContent=C,G.appendChild(me)}I.appendChild(G),e.appendChild(I)}if(this.planStatus){let x=document.createElement("div");x.className="bp-mgmt-note bp-plan-err bp-tone-bad";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):Ee(this.planStatus);let I=document.createElement("button");I.type="button",I.className="icon",I.textContent="×",I.title=h("common.close","Close"),I.addEventListener("click",()=>{this.planStatus="",this.render()}),x.append(C,I),e.appendChild(x)}if(t.keys_note){let x=document.createElement("div");x.className="bp-mgmt-note bp-dim";let C="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";x.textContent=t.keys_note===C?h("gpui.mgmt.plan.keysnote",C):Ee(t.keys_note),e.appendChild(x)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let x=document.createElement("div");x.className="bp-plan-stackup";let C=document.createElement("button");C.type="button",C.className="bp-plan-stackup-head",C.setAttribute("data-testid","mgmt-plan-stackup-toggle"),C.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let I=document.createElement("span");I.className="bp-plan-chev",I.textContent=this.planStackupOpen?"▾":"▸";let G=document.createElement("span");if(G.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),C.append(I,G),C.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),x.appendChild(C),this.planStackupOpen){let z=document.createElement("div");if(z.className="bp-plan-stackup-body",z.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let me=document.createElement("div");me.className="bp-dim",me.textContent=W,z.appendChild(me)}for(let me of _){let N=document.createElement("div");N.className="bp-mgmt-faint",N.textContent=`· ${me}`,z.appendChild(N)}x.appendChild(z)}e.appendChild(x)}let j=(x,C,I,G)=>{let z=document.createElement("button");return z.type="button",z.className="bp-mgmt-btn bp-plan-chip-btn"+(C?" active":""),z.setAttribute("data-testid",I),z.setAttribute("aria-pressed",C?"true":"false"),z.textContent=x,z.addEventListener("click",G),z},pe=document.createElement("div");if(pe.className="bp-plan-viewbar",pe.append(j(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),j(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),j(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let x=document.createElement("span");x.className="bp-plan-sep";let C=document.createElement("span");C.className="bp-plan-sep";let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn bp-plan-mini-btn",I.setAttribute("data-testid","mgmt-plan-fit"),I.textContent=h("gpui.mgmt.plan.fit","Fit"),I.addEventListener("click",()=>this.planCanvas?.fitAll()),pe.append(x,j(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),j(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),j(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),C,j(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),I)}let le=document.createElement("span");le.className="bp-mgmt-flex1";let ie=document.createElement("button");ie.type="button",ie.className="bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-expand"),ie.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),ie.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),pe.append(le,ie),e.appendChild(pe);let ye=this.planHydratedKey===i&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ke=this.planHydratedKey===i&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Ne=(ke.bands??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),ve=(ke.regions??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),Me=[],T=(t.layers??[]).map((x)=>{let C=[];for(let I of x.items??[]){let G=this.planOptimistic.get(I.id);if(!G){C.push(I);continue}let z={...I,width:typeof G.width==="number"?G.width:I.width,locked:typeof G.locked==="boolean"?G.locked:I.locked,edited:!0,state:I.state==="proposed"?"edited":I.state};if(typeof G.layer==="string"&&G.layer!==x.layer)Me.push({target:G.layer,item:z});else C.push(z)}return{...x,items:C}});for(let x of Me){let C=T.find((I)=>I.layer===x.target);if(C)C.items=[...C.items??[],x.item]}let re=this.planGridMode==="all"?T.map((x)=>x.layer):this.planGridMode==="single"?[this.planShownLayers.find((x)=>T.some((C)=>C.layer===x))??rt(T)[0]??T[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((x)=>T.some((C)=>C.layer===x))?this.planShownLayers.slice(0,2):rt(T);if(this.planViewMode!=="list"&&T.length>1){let x=document.createElement("div");x.className="bp-plan-layerbar";for(let C of T){let I=re.includes(C.layer);x.appendChild(j(C.title||C.layer,I,`mgmt-plan-layerpill-${C.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"){if(!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}else this.planGridMode="single",this.planShownLayers=[C.layer];this.render()}))}e.appendChild(x)}let ae=(x,C)=>{let I=this.planOptimistic.get(x)??{};if(this.planOptimistic.set(x,{...I,...C}),typeof C.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"&&!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}this.render(),n("plan.update",{ops:[{op:"set",id:x,fields:C}]})};if(this.planSelectedId){let x="",C=null;for(let I of T){let G=(I.items??[]).find((z)=>z.id===this.planSelectedId);if(G){x=I.layer,C=G;break}}if(C){let I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let G=document.createElement("div");G.className="bp-plan-ins-row";let z=document.createElement("span");z.className="bp-plan-ins-sw",z.style.background=C.kind==="corridor"?vt(C.name||C.id,C.color||""):ft(C.name||C.id,C.color||"");let me=document.createElement("span");me.className="bp-mgmt-strong",me.textContent=C.name||C.id;let N=document.createElement("span");if(N.className="bp-dim",N.textContent=x,G.append(z,me,N),C.edited||C.state==="edited"){let ee=document.createElement("span");ee.className="bp-plan-ins-pill warn",ee.textContent=h("gpui.mgmt.plan.edited","Edited"),G.appendChild(ee)}if(C.locked){let ee=document.createElement("span");ee.className="bp-plan-ins-pill",ee.textContent=h("gpui.mgmt.plan.locked","Locked"),G.appendChild(ee)}let Y=document.createElement("span");Y.className="bp-mgmt-flex1",G.appendChild(Y);let Ie=document.createElement("button");if(Ie.type="button",Ie.className="bp-mgmt-btn bp-plan-mini-btn",Ie.setAttribute("data-testid","mgmt-plan-lock"),Ie.textContent=C.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),Ie.addEventListener("click",()=>ae(C.id,{locked:!C.locked})),G.appendChild(Ie),C.state==="proposed"||C.state==="edited"){let ee=document.createElement("button");ee.type="button",ee.className="primary bp-mgmt-btn bp-plan-mini-btn",ee.textContent=h("android.hub.machines.approve","Approve"),ee.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!0}));let be=document.createElement("button");be.type="button",be.className="bp-mgmt-btn bp-plan-mini-btn",be.textContent=h("gpui.mgmt.plan.reject","Reject"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!1})),G.append(ee,be)}let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-note-toggle"),Ae.textContent=h("gpui.mgmt.plan.addnote","Add note"),Ae.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let de=document.createElement("button");if(de.type="button",de.className="icon",de.textContent="×",de.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),G.append(Ae,de),I.appendChild(G),!C.locked){let ee=document.createElement("div");if(ee.className="bp-plan-ins-row",C.kind==="corridor"){let Te=typeof C.width==="number"?C.width:1.5,ue=document.createElement("span");ue.className="bp-dim",ue.textContent=h("gpui.mgmt.plan.width","Width");let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn bp-plan-mini-btn",te.setAttribute("data-testid","mgmt-plan-w-down"),te.textContent="-",te.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,Te-0.25)*100)/100;ae(C.id,{width:Ue})});let je=document.createElement("span");je.className="bp-plan-ins-val",je.textContent=`${Te.toFixed(2)}mm`;let Z=document.createElement("button");Z.type="button",Z.className="bp-mgmt-btn bp-plan-mini-btn",Z.setAttribute("data-testid","mgmt-plan-w-up"),Z.textContent="+",Z.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,Te+0.25)*100)/100;ae(C.id,{width:Ue})});let Ce=document.createElement("span");Ce.className="bp-plan-sep",ee.append(ue,te,je,Z,Ce)}let be=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((Te)=>Te.layer):T.map((Te)=>Te.layer);if(be.length>0){let Te=document.createElement("span");Te.className="bp-dim",Te.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),ee.appendChild(Te);for(let ue of be)ee.appendChild(j(ue,ue===x,`mgmt-plan-move-${ue}`,()=>{if(ue!==x)ae(C.id,{layer:ue})}))}I.appendChild(ee)}if(this.planNoteOpen){let ee=document.createElement("form");ee.className="bp-plan-note-form";let be=document.createElement("input");be.type="text",be.className="bp-plan-note-input",be.setAttribute("data-testid","mgmt-plan-note-input"),be.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let Te=document.createElement("button");Te.type="submit",Te.className="primary bp-mgmt-btn bp-plan-mini-btn",Te.setAttribute("data-testid","mgmt-plan-note-submit"),Te.textContent=h("gpui.mgmt.plan.addnote","Add note"),ee.append(be,Te),ee.addEventListener("submit",(ue)=>{ue.preventDefault();let te=be.value.trim();if(!te)return;be.value="",this.planNoteOpen=!1,this.render(),n("plan.update",{ops:[{op:"note",id:C.id,text:te}]})}),I.appendChild(ee)}if(this.planViewMode!=="list"&&!C.locked){let ee=document.createElement("div");ee.className="bp-plan-hint",ee.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(ee)}e.appendChild(I)}}let J=document.createElement("div");J.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),J.setAttribute("data-testid","mgmt-plan-rows");let ce=h("gpui.mgmt.plan.done","done");for(let x of T){let C=x.items??[],I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let G=document.createElement("div");G.className="bp-mgmt-row-line";let z=document.createElement("span");z.className="bp-mgmt-strong",z.textContent=x.layer;let me=document.createElement("span");if(me.className="bp-dim bp-mgmt-flex1",me.textContent=`${x.role?`${x.role} · `:""}${x.done??0}/${C.length} ${ce}`,G.append(z,me),x.status!=="approved"&&C.length>0){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.plan.layer","Approve layer"),N.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!0}));let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent=h("gpui.mgmt.plan.reject","Reject"),Y.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!1})),G.append(N,Y)}if(I.appendChild(G),x.stackup){let N=document.createElement("div");N.className="bp-plan-layer-stackup",N.textContent=x.stackup,I.appendChild(N)}J.appendChild(I);for(let N of C){if(this.planHideDone&&_n(N))continue;let Y=this.planSelectedId===N.id,Ie=document.createElement("div");Ie.className="bp-mgmt-row bp-plan-row"+(Y?" active":""),Ie.setAttribute("data-testid",`mgmt-plan-row-${N.id}`);let Ae=document.createElement("div");Ae.className="bp-mgmt-row-line";let de=document.createElement("span");de.className=`bp-plan-swatch bp-plan-st-${N.state||"proposed"}`,de.style.setProperty("--swatch-color",N.color||"#8a8a8a");let ee=document.createElement("span");ee.className="bp-mgmt-flex1"+(N.state==="blocked"||N.state==="failed"?" bp-tone-bad":N.state==="edited"?" bp-tone-warn":N.state==="rejected"||N.state==="routed"||N.state==="verified"?" bp-dim":""),ee.textContent=`${N.name||N.id}${N.locked?" \uD83D\uDD12":""}`;let be=[];if(N.kind==="plane"){if(N.reference)be.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:N.reference}))}else{let te=N.nets??0;be.push(te===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:te}))}if(typeof N.width==="number"&&Number.isFinite(N.width))be.push(`${N.width.toFixed(2)}mm`);if(N.impedance)be.push(N.impedance);let Te=be.join(" · "),ue=document.createElement("span");if(ue.className="bp-plan-mark "+(N.state==="blocked"||N.state==="failed"?"bp-tone-bad":N.state==="verified"||N.state==="routed"?"bp-tone-ok":N.state==="approved"?"bp-tone-accent":"bp-dim"),ue.textContent=qn(N),Ae.append(de,ee,ue),N.state==="proposed"||N.state==="edited"){let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn",te.textContent="✓",te.title=h("gpui.mgmt.plan.layer","Approve layer"),te.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!0})});let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent="✗",je.title=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!1})}),Ae.append(te,je)}if(Ie.appendChild(Ae),Te){let te=document.createElement("div");te.className="bp-mgmt-row-sub bp-plan-detail bp-dim",te.textContent=Te,Ie.appendChild(te)}if(N.state==="routing"&&typeof N.total==="number"&&N.total>0){let te=document.createElement("div");te.className="bp-plan-microbar";let je=document.createElement("div");je.className="bp-plan-microbar-fill";let Z=Math.max(0,Math.min(100,Math.round((N.routed??0)/N.total*100)));je.style.width=`${Z}%`,te.appendChild(je),Ie.appendChild(te)}if(N.problem_text){let te=document.createElement("div");te.className="bp-plan-problem",te.textContent=N.problem_text,Ie.appendChild(te)}Ie.addEventListener("click",()=>{this.planSelectedId=N.id,n("plan.focus",{id:N.id}),this.render()}),J.appendChild(Ie)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new en({onSelect:(G)=>{if(this.planSelectedId=G,!G)this.planNoteOpen=!1;this.render()},onFocusItem:(G)=>{n("plan.focus",{id:G})},onOptimisticPatch:(G,z)=>{let me=this.planOptimistic.get(G)??{};this.planOptimistic.set(G,{...me,...z})},onCommitFields:(G,z)=>{ae(G,z)},onApproveLayer:(G,z)=>{n("plan.approve",{layer:G,ids:[],approve:z})},onQuickApprove:(G,z)=>{n("plan.approve",{layer:"",ids:G,approve:z})}});let x=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,C=this.planExpanded||this.panelEl.clientWidth>=540||x;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:re,selectedId:this.planSelectedId,board:ye,bands:Ne,regions:ve,layers:T},C);let I=document.createElement("div");I.className="bp-plan-canvas-scroll",I.appendChild(this.planCanvas.root),e.appendChild(I)}if(this.planViewMode!=="canvas")e.appendChild(J);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let x=document.createElement("div");x.className="bp-plan-footer",x.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(x)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,k={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:w,...k}).catch((M)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=M instanceof Error?M.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Yn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(c?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(u),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}m.appendChild(l),o.appendChild(m);let p=Jn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(p.button?"bp-tone-warn":"bp-dim"),f.textContent=p.text,y.appendChild(f),p.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=p.button,w.addEventListener("click",()=>n("drc")),y.appendChild(w)}b.appendChild(y),o.appendChild(b);for(let w of t.conflicts??[]){let k=document.createElement("div");k.className="bp-mgmt-row bp-tone-bad",k.textContent=w,o.appendChild(k)}for(let w of t.suggestions??[]){let k=document.createElement("div");k.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.apply","Apply"),M.addEventListener("click",()=>n("apply",{key:w.key})),S.append(L,M),k.appendChild(S),o.appendChild(k)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,k.appendChild(L),S){let M=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=h("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:M})),k.appendChild(B)}w.appendChild(k),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=h("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),k.append(S,L),w.appendChild(k);for(let M of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=M,w.appendChild(B)}o.appendChild(w)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=h("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=h("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=h("gpui.mgmt.fab.extra","Costs more");let M=document.createElement("span");M.className="bp-mgmt-col bp-mgmt-col-read",M.textContent=h("gpui.mgmt.fab.readcol","Read"),w.append(k,S,L,M),o.appendChild(w);for(let H of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let j=document.createElement("span");j.className="bp-mgmt-flex1"+(H.changed?" bp-tone-warn":H.inherited?" bp-dim":""),j.textContent=`${H.changed?"• ":""}${H.label??""}`;let pe=document.createElement("span");pe.className="bp-mgmt-col",pe.textContent=H.free?.text||"—";let le=document.createElement("span");le.className="bp-mgmt-col bp-dim",le.textContent=H.extra?.text||"—";let ie=H.free&&typeof H.free==="object"?H.free:H.extra,ye=ie?.fetched??"",ke=Boolean(ye)&&ie?.confidence!=="published",Ne=ye?ke?`${ye}*`:ye:"—",ve=ie?.source??"",Me;if(ve.startsWith("https://")&&ye){let T=document.createElement("a");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",T.href=ve,T.target="_blank",T.rel="noopener noreferrer",T.textContent=Ne,Me=T}else{let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",T.textContent=Ne,Me=T}_.append(j,pe,le,Me),W.appendChild(_),o.appendChild(W)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(B)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var ys={trs:(e)=>e,t:(e,t)=>t},ws=new Set(["/settle"]);function li(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function di(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function pi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function mi(e,t=ys){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let c=ws.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:m}=ci(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:di(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function hi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let b of i)d.set(b.id,b.title||b.id);let p=new Set;for(let b of c)if(b.action.type==="thread")p.add(b.action.id);for(let b of n.threads){if(!b.id||p.has(b.id))continue;p.add(b.id);let{urgency:y,want:f}=ci(b);c.push({label:b.title||"Untitled thread",place:b.project?d.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:di(b),action:{type:"thread",id:b.id}})}}let m=[];for(let d=0;d0)m.push({score:f,index:d,item:p})}m.sort((d,p)=>{if(o){let f=(p.item.urgency??0)-(d.item.urgency??0);if(f!==0)return f}if(p.score!==d.score)return p.score-d.score;let b=d.item.kind==="thread"?0:1,y=p.item.kind==="thread"?0:1;if(b!==y)return b-y;return d.index-p.index});let l=new Set,u=[];for(let d of m){let p=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(p))continue;if(l.add(p),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=mi(t,{t:h,trs:Ee}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=hi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,d)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(d,p),m.appendChild(b),p{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var xs=new Set(["resume","raise","retry","move","signin"]);function gi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Rt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(xs.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function fi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class an{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";p.textContent=b,d.appendChild(p);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(d.appendChild(y),u.appendChild(d),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(l,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let c=document.createElement("div");c.className="bp-set-head",c.textContent="Paired devices",o.appendChild(c);try{let m=await this.cb.onLoadDevices();if(m.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",o.appendChild(l)}else for(let l of m){let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div");if(p.textContent=l.title||l.head||"",d.appendChild(p),l.text||l.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=l.text||l.detail||"",d.appendChild(b)}if(u.appendChild(d),l.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of l.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let l=document.createElement("div");l.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";l.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(l)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function rn(e){return xe("pre","bp-context-code",e)}function Cs(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,Ee(e))}function jt(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),Cs(t)),n}class on{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(jt(t.path,t.status),xe("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,rn(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),rn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,Ee(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(jt(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(jt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(jt(s.name,s.status),rn(a)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=xe("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var vi="http://www.w3.org/2000/svg";function yi(){let e=document.createElementNS(vi,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(vi,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function ks(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function wi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class ln{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=h("thread.new","New thread"),c.setAttribute("aria-label",h("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),r.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${ks(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?gi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,c.appendChild(m);for(let u of r.actions){if(!Rt(u,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=u.label,d.setAttribute("data-testid",`need-${u.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(p)=>{p.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=l,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),c.appendChild(m);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(r.kind==="projects"){let o=r.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!c&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,d=r.open?"▾":"▸";if(l.textContent=`${r.title.toUpperCase()} (${u}) ${d}`,r.hint)l.title=r.hint;l.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(l)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!c||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",m.appendChild(l)}for(let l of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(l.off?" bp-dim":""),u.setAttribute("data-project-id",l.id),l.nav||l.key)u.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let p=document.createElement("button");p.type="button",p.className="bp-proj-toggle";let b=yi();if(l.css)b.style.color=l.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=l.title||l.id,p.append(b,y),l.fold==="project-fold"&&l.nav)p.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${l.id}`),l.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(p,f),u.appendChild(d),!l.folded||Boolean(t)){let g=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:wi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,m=yi();if(i.css)m.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(m,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!c)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:wi(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let l of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`@${l.name}`,u.append(d,p),u.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(c,m),r.appendChild(o);for(let l of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,u.appendChild(d),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ss(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function As(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?c/m:0));s[a]=l<0?l*32768:l*32767}return s}class cn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ss(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),c=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=As(r.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var Ei=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],xi=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ci=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ki=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ls=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[c]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ps=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Ns=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class dn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},r=(u)=>{let d=0,p=0,b=0;for(let y=1;y<=u.maxBits;y++){d|=a(1);let f=u.counts[y];if(d-f{let d=c+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let p=o.length;while(p{m(1),o[c++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let p=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(p^65535)!==b)throw Error("invalid stored block length");if(n+p>e.length)throw Error("truncated stored payload");m(p);for(let y=0;y=e.length)break}else if(d===1||d===2){let p=Ps,b=Ns;if(d===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,w=new Uint8Array(19);for(let B=0;BS)throw Error("code length overflow");for(let _=0;_S)throw Error("code length overflow");M+=H}else if(B===18){let H=a(7)+11;if(M+H>S)throw Error("code length overflow");M+=H}else throw Error("invalid code length symbol")}p=Et(L,y),b=Et(L.subarray(y),f)}while(!0){let y=r(p);if(y<256)l(y);else if(y===256)break;else{let f=y-257;if(f>=Ei.length)throw Error("invalid length symbol");let g=Ei[f]+(xi[f]?a(xi[f]):0),w=r(b);if(w>=Ci.length)throw Error("invalid distance symbol");let k=Ci[w]+(ki[w]?a(ki[w]):0);m(g);let S=this.winPos-k&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new dn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(c))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ms=new TextDecoder;function Si(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ai(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let l=e.subarray(t,t+m);return t+=m,l}case 3:{if(t+m>e.length)return null;let l=Ms.decode(e.subarray(t,t+m));return t+=m,l}case 4:{if(m>e.length)return null;let l=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Pi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,c=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Li(m),u=[],d=[],p=0,b=0;while(l.more()){let y=l.nextU32(),f=u.length,g=1/0,w=1/0,k=-1/0,S=-1/0;if(a===2)p=p+l.nextI32()|0,b=b+l.nextI32()|0,u.push(p,b),g=k=p,w=S=b;else{let M=Math.min(l.nextU32(),1048576);for(let B=0;Bk)k=p;if(bS)S=b}}let L=(u.length-f)/2;if(L>0){let M=a===2||L===1?2:a===0?0:1,B=a===0?0:o;d.push({info:y,x0:g-B,y0:w-B,x1:k+B,y1:S+B,at:f,n:L,kind:M})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:c,pts:new Float32Array(u),pieces:d}}function Ni(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Mi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,c=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,l=(t-c)/r;if(m<0||m>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ti=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Bi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class mn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Ii(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,c=!1,m=-1,l=null,u=new mn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let p=document.createElement("div");p.className="bp-pane-bar bp-browser-nav";function b(J,ce,x){let C=document.createElement("button");if(C.type="button",C.className="bp-v-btn",C.textContent=J,C.setAttribute("data-testid",ce),x)C.title=x;return C}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let k=document.createElement("input");k.type="text",k.className="bp-browser-input",k.placeholder="https://…",k.autocomplete="off",k.spellcheck=!1,k.setAttribute("data-testid","browser-url");let S=b("Go","browser-go","Navigate");S.type="submit",w.append(k,S);let L=b("Take over","browser-takeover");L.classList.add("is-primary"),p.append(y,f,g,w,L);let M=document.createElement("div");M.className="bp-browser-drive-bar",M.hidden=!0;let B=document.createElement("div");B.className="bp-browser-keys-row";let H=document.createElement("input");H.type="text",H.className="bp-browser-input",H.placeholder="Type text or press Enter/Tab/Arrows…",H.autocomplete="off",H.spellcheck=!1,H.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");B.append(H,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[J,ce]of Ti){let x=b(J,`browser-key-${ce}`);x.addEventListener("click",()=>ve("press",{key:ce})),_.append(x)}M.append(B,_);let j=document.createElement("div");j.className="bp-browser-err",j.setAttribute("data-testid","browser-error"),j.hidden=!0;let pe=document.createElement("div");pe.className="bp-browser-stage",pe.setAttribute("data-testid","browser-stage");let le=document.createElement("img");le.className="bp-browser-img",le.alt="Hub browser screen",le.draggable=!1,le.hidden=!0,le.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",pe.append(le,ie);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,d.append(p,M,j,pe,ye),e.replaceChildren(d);function ke(J){j.textContent=J,j.hidden=!J}function Ne(){M.hidden=!s,ye.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),le.classList.toggle("is-driving",s)}function ve(J,ce={},x){u.enqueue(async()=>{if(!i)return;ke("");try{if(await t.hub.rpc("browser",{thread:n,op:J,...ce}),!i)return;x?.(),re()}catch(C){if(!i)return;ke(C instanceof Error?C.message:String(C))}})}function Me(J){ve("toolbar",{command:J},()=>{s=!0,Ne()})}y.addEventListener("click",()=>Me("back")),f.addEventListener("click",()=>Me("forward")),g.addEventListener("click",()=>Me("reload")),w.addEventListener("submit",(J)=>{J.preventDefault();let ce=Bi(k.value);if(!ce)return;if(k.value=ce,!s)ve("takeover",{},()=>{s=!0,Ne()});ve("navigate",{url:ce},()=>{s=!0,Ne()})}),L.addEventListener("click",()=>{if(s)ve("handback",{},()=>{s=!1,Ne()});else ve("takeover",{},()=>{s=!0,Ne(),H.focus()})});function T(){let J=H.value;if(!J)return;H.value="",ve("type",{text:J})}W.addEventListener("click",T),H.addEventListener("keydown",(J)=>{if(!s)return;if(J.key==="Enter"){if(J.preventDefault(),H.value)T();ve("press",{key:"Enter"});return}if(J.key==="Tab"||J.key==="Escape"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="ArrowLeft"||J.key==="ArrowRight"||J.key==="Backspace"&&H.value==="")J.preventDefault(),ve("press",{key:J.key})}),le.addEventListener("click",(J)=>{if(!s||!a)return;let ce=le.getBoundingClientRect(),x=Mi(J.clientX,J.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:le.naturalWidth,naturalHeight:le.naturalHeight});if(!x)return;ve("click",x)}),le.addEventListener("wheel",(J)=>{if(!s||!a)return;J.preventDefault();let ce=Math.round(J.deltaX),x=Math.round(J.deltaY);if(ce===0&&x===0)return;ve("scroll",{dx:ce,dy:x})},{passive:!1});async function re(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let J=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(J.ok){let ce=await J.blob();if(!i)return;let x=URL.createObjectURL(ce),C=r;if(r=x,le.src=x,le.hidden=!1,ie.hidden=!0,a=!0,C)URL.revokeObjectURL(C)}else if(!a)le.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!a)le.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let ae=t.hub.onFrame((J)=>{if(!i)return;if(J.t==="shot"&&J.bot===n){if(typeof J.n==="number"){if(J.n===m)return;m=J.n}re()}});return re(),{destroy(){if(i=!1,ae(),l?.abort(),r)URL.revokeObjectURL(r),r=""}}}function O(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ht(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function ji(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Bs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ri(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Is(e){let t=ji(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Hi(e,t,n,i){let s=!0,a="",r="",o=O("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=O("div","bp-pane-bar"),m=O("div","bp-files-crumbs"),l=O("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void f(a)),c.append(m,l);let u=O("div","bp-files-split"),d=O("div","bp-files-list");d.setAttribute("data-testid","files-list");let p=O("div","bp-files-preview");p.setAttribute("data-testid","files-preview"),p.append(O("div","bp-pane-empty","Select a file to preview")),u.append(d,p),o.append(c,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=O("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let w=a.split("/").filter(Boolean),k="";for(let S of w){k=k?`${k}/${S}`:S;let L=k;m.append(O("span","bp-vh-sep","/"));let M=O("button","bp-crumb-btn",S);M.type="button",M.addEventListener("click",()=>void f(L)),m.append(M)}}async function y(g,w,k){r=g,p.replaceChildren();let S=O("div","bp-files-prev-head");S.append(O("span","bp-files-prev-name",g));let L=O("div","bp-files-prev-acts"),M=Is(w);if(M){let _=O("button","bp-v-btn is-primary",`Open in ${M}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(M,g)),L.append(_)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,H=O("a","bp-v-btn","Download");H.href=B,H.download=w,L.append(H),S.append(L),p.append(S);let W=ji(w);if(Bs(W)){let _=O("div","bp-files-img-wrap"),j=document.createElement("img");j.className="bp-files-img",j.alt=w,j.src=B,_.append(j),p.append(_);return}if(k>524288&&!Ri(W)){p.append(O("div","bp-pane-empty",`Binary file (${Ht(k)}). Use Download to save.`));return}if(Ri(W)||k<=65536){let _=O("div","bp-pane-empty","Loading…");p.append(_);try{let j=await fetch(B,{credentials:"same-origin"});if(!s||r!==g)return;if(!j.ok){_.textContent=`Could not load file (${j.status})`;return}if((j.headers.get("content-type")||"").startsWith("image/")){_.remove();let ae=document.createElement("img");ae.className="bp-files-img",ae.alt=w,ae.src=B,p.append(ae);return}let le=262144,ie=[],ye=0,ke=!1;if(j.body){let ae=j.body.getReader();try{while(!0){let{done:J,value:ce}=await ae.read();if(J||!ce)break;if(ye+ce.byteLength>le){let x=le-ye;if(x>0)ie.push(ce.subarray(0,x)),ye+=x;ke=!0,await ae.cancel();break}ie.push(ce),ye+=ce.byteLength}}finally{ae.releaseLock()}}if(!s||r!==g)return;let Ne=new Uint8Array(ye),ve=0;for(let ae of ie)Ne.set(ae,ve),ve+=ae.byteLength;let Me=!1;for(let ae=0;aeS.dir===L.dir?S.name.localeCompare(L.name):S.dir?-1:1),d.replaceChildren(),g){let S=O("button","bp-file-row is-dir");S.type="button",S.append(O("span","bp-file-icon","↰"),O("span","bp-file-name",".."));let L=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";S.addEventListener("click",()=>void f(L)),d.append(S)}if(k.length===0){d.append(O("div","bp-pane-empty","Empty folder"));return}for(let S of k){let L=g?`${g}/${S.name}`:S.name,M=O("button","bp-file-row"+(S.dir?" is-dir":"")+(L===r?" is-sel":""));M.type="button",M.setAttribute("data-testid",`file-row-${S.name}`),M.append(O("span","bp-file-icon",S.dir?"▸":"·"),O("span","bp-file-name",S.name),O("span","bp-file-size",S.dir?"":Ht(S.size))),M.addEventListener("click",()=>{if(S.dir)f(L);else d.querySelectorAll(".bp-file-row.is-sel").forEach((B)=>B.classList.remove("is-sel")),M.classList.add("is-sel"),y(L,S.name,S.size)}),d.append(M)}}catch(w){if(!s)return;d.replaceChildren(O("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return f(""),{destroy(){s=!1}}}function Di(e,t,n){let i=!0,s=O("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=O("div","bp-pane-bar"),r=O("span","bp-diff-summary","Loading diff…"),o=O("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let c=O("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(a,c),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){r.textContent="Not a git repository",c.append(O("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof l?.diff==="string"?l.diff:"";if(!u.trim()){r.textContent="Clean working tree",c.append(O("div","bp-pane-empty","No uncommitted changes."));return}let d=u.split(` +`),p=0,b=0,y=0,f=document.createDocumentFragment(),g=O("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=O("div","bp-diff-file"),p++;let k=w.match(/ b\/(.+)$/);g.append(O("div","bp-diff-file-head",k?k[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))g.append(O("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))g.append(O("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))b++,g.append(O("div","bp-diff-line is-add",w));else if(w.startsWith("-"))y++,g.append(O("div","bp-diff-line is-del",w));else g.append(O("div","bp-diff-line",w))}if(g.childNodes.length>0)f.append(g);r.textContent=`${p||1} file${p===1?"":"s"} · +${b} -${y}`,c.append(f)}catch(l){if(!i)return;r.textContent="Diff unavailable",c.append(O("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return m(),{destroy(){i=!1}}}function Fi(e,t,n){let i=!0,s="checks",a=O("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=O("div","bp-pane-bar"),o=O("div","bp-review-tabs"),c=O("button","bp-v-btn is-on","Checks"),m=O("button","bp-v-btn","BOM"),l=O("button","bp-v-btn","Comments");c.type=m.type=l.type="button",o.append(c,m,l);let u=O("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void y()),r.append(o,u);let d=O("div","bp-review-body");d.setAttribute("data-testid","review-body"),a.append(r,d),e.replaceChildren(a);function p(f){s=f,c.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),y()}c.addEventListener("click",()=>p("checks")),m.addEventListener("click",()=>p("bom")),l.addEventListener("click",()=>p("comments"));function b(f){let g=O("div","bp-review-md"),w=f.split(` +`),k=0;while(k{B.preventDefault();let H=L.value.trim();if(!H)return;M.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:H}).then(()=>{L.value="",M.disabled=!1,y()},()=>{M.disabled=!1})}),d.append(S),k.length===0){d.append(O("div","bp-pane-empty","No review comments yet."));return}for(let B of k){let H=O("div","bp-review-comment"+(B.resolved?" is-resolved":"")),W=[B.by||"review",B.file,B.layer,B.item].filter(Boolean).join(" · ");H.append(O("div","bp-review-comment-meta",W),O("div","bp-review-comment-text",B.text)),d.append(H)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(d.replaceChildren(),g.line||g.gate){let w=O("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));d.append(w)}if(g.err)d.append(O("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let w=O("div","bp-review-tasks");g.tasks.forEach((k,S)=>{let L=O("label","bp-review-task"),M=document.createElement("input");M.type="checkbox",M.checked=!!(k.done??k.checked);let B=typeof k.index==="number"?k.index:S;M.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:B}).then(()=>void y(),()=>{})}),L.append(M,O("span",void 0,k.text||k.label||`Item ${S+1}`)),w.append(L)}),d.append(w)}if(g.md&&g.md.trim())d.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))d.append(O("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;d.replaceChildren(O("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function $i(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class hn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,m=n*0.5,l=this.scale,u=this.cx,d=this.cy,p=u-c/l,b=u+c/l,y=d-m/l,f=d+m/l,{off:g,dim:w,lift:k}=this.masks,S=[],L=[];for(let B=0;B>>H&1)===1)continue;if(H===k)L.push(B);else S.push(B)}let M=S.concat(L);r.lineCap="round",r.lineJoin="round";for(let B=0;B>>W.layer&1)===1,j=W.alpha*(_?0.25:1);if(j<=0.01)continue;this.drawChunk(r,W,j,p,y,b,f,u,d,l,c,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let B=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let H=0;Ha||f.y1r)continue;if(f.n<3)continue;let g=(d[f.at]-o)*m+l,w=(d[f.at+1]-c)*m+u;e.moveTo(g,w);for(let k=1;k0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=p,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let w=(d[g.at]-o)*m+l,k=(d[g.at+1]-c)*m+u;e.moveTo(w+b,k),e.arc(w,k,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=p,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(d[f.at]-o)*m+l,w=(d[f.at+1]-c)*m+u;if(f.n===1)e.moveTo(g,w),e.lineTo(g+0.01,w);else{e.moveTo(g,w);for(let k=1;k0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,c,m,l,u,d){let p=t.pts,b=$i(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(p[f.at]-c)*l+u,w=(p[f.at+1]-m)*l+d;if(f.kind===2){let k=Math.max(1.5,t.r*l);e.fillStyle=b,e.beginPath(),e.arc(g,w,k,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,w);for(let k=1;k=0;l--){let u=n.chunks[l];if(u.layer<32&&(m>>>u.layer&1)===1)continue;for(let d=0;dp.x1+r||ap.y1+r)continue;let b=(p.x1-p.x0+1)*(p.y1-p.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),c=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,u=s-c.left-c.width*0.5,d=a-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Gi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Ui(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function un(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class bn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Rs=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,ns=`#version 300 es +`,js=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,is=`#version 300 es +`,Hs=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,ss=`#version 300 es +`,Ds=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function Ue(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var rs=[Ue(77),Ue(83),Ue(94)],as=[Ue(53),Ue(58),Ue(67)],os=[Ue(245),Ue(246),Ue(248)],ls=[Ue(225),Ue(228),Ue(233)];function wi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function yi(e,t,n){let i=wi(e,e.VERTEX_SHADER,t),s=wi(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function cs(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function ds(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function Ei(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function xi(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function an(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class on{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=yi(n,ts,ns),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=yi(n,is,ss),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=ri(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,m=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,h=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,b=0,E=0;for(let v=0;v>>24&255,S=1-x/255,L=(y>>>16&255)/255,T=(y>>>8&255)/255,M=(y&255)/255,F=v*9;if(x===0&&o&&c&&m){let z=b*9;for(let R=0;R<9;R++)o[z+R]=e[F+R],c[z+R]=t[F+R];let V=b*12;for(let R=0;R<3;R++)m[V+R*4]=L,m[V+R*4+1]=T,m[V+R*4+2]=M,m[V+R*4+3]=1;b++}else if(l&&h&&d){let z=E*9;for(let R=0;R<9;R++)l[z+R]=e[F+R],h[z+R]=t[F+R];let V=E*12;for(let R=0;R<3;R++)d[V+R*4]=L,d[V+R*4+1]=T,d[V+R*4+2]=M,d[V+R*4+3]=S;E++}}let w=o&&c&&m?this.createSubBatch(o,c,m,r*3):null,g=l&&h&&d?this.createSubBatch(l,h,d,a*3):null;if(!w&&!g)return null;return{opaque:w,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=vi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let z=this.lightTheme?os:rs,V=this.lightTheme?ls:as;t.uniform3f(this.uBgTop,z[0],z[1],z[2]),t.uniform3f(this.uBgBot,V[0],V[1],V[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),l=Math.cos(this.yaw),h=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*h,this.target[1]-this.dist*c*l,this.target[2]+this.dist*m],b=Ei([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),E=Math.abs(b[2])>0.99?[0,1,0]:[0,0,1],w=Ei(xi(b,E)),g=xi(w,b),v=new Float32Array([w[0],g[0],-b[0],0,w[1],g[1],-b[1],0,w[2],g[2],-b[2],0,-an(w,d),-an(g,d),an(b,d),1]),y=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),S=ds(35*Math.PI/180,a/o,y,x),L=cs(S,v);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,w[0],w[1],w[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,b[0],b[1],b[2]);let T=!1,M=[],F=[];for(let z of this.partBatches){let V=e-z.fadeStartMs,R=z.fadeStartMs===0?1:Math.min(1,Math.max(0,V/300));if(R<1){if(T=!0,R>0)F.push({batch:z,fade:R})}else M.push(z)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let z of M)this.drawSubBatch(z.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let z of M)this.drawSubBatch(z.translucent);for(let{batch:z,fade:V}of F)t.uniform1f(this.uFade,V),this.drawSubBatch(z.opaque),this.drawSubBatch(z.translucent);return t.depthMask(!0),t.bindVertexArray(null),T}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var Ci=64,ps=16777216;function hs(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function ft(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ki(e){switch(e){case"board":return p("viewer.board","Board");case"schematic":return p("viewer.schematic","Schematic");case"3d":return p("viewer.solid","3D");case"gerbers":return p("gpui.gerbers","Gerbers");case"mech":return p("viewer.mech","Mech");case"files":return p("viewer.files","Files");case"diff":return p("viewer.diff","Diff");case"review":return p("viewer.review","Review");case"browser":return p("bots.tab.browser","Browser");case"terminal":return p("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function ln(e){return e==="board"||e==="schematic"||e==="gerbers"}function ms(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function cn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let b=document.createElement("div");b.className="bp-v-layers",b.hidden=!0;let E=document.createElement("div");E.className="bp-v-info",E.hidden=!0,l.append(h,d,b,E);let w=document.createElement("div");w.className="bp-history-bar",w.setAttribute("data-testid","viewer-history-bar"),w.hidden=!0,e.replaceChildren(n,c,m,l,w);let g="",v="",y=0,x=!1,S=new Set,L=[],T=0,M=new Map,F=new Map,z={},V=[],R="",N="",_=!1,q=!1,ie=0,ae=!1,le=0,I="",ve=0,A=null,de=null,se=null,Y=null,oe=null,B=new rn,W=0,X=!1,ce="",Ee="",Ie="",K="";document.addEventListener("click",(P)=>{if(!X)return;if(P.target instanceof Node&&w.contains(P.target))return;X=!1,we()}),document.addEventListener("keydown",(P)=>{if(X&&P.key==="Escape")X=!1,we()});function te(){if(W)window.clearInterval(W),W=0;B.playing=!1}function Je(){let P=v==="3d"||v==="mech";if(c.hidden=!P,!P)return;if(c.childElementCount>0)return;for(let H of gi){let D=document.createElement("button");D.type="button",D.className="bp-v-btn",D.textContent=H.label,D.setAttribute("data-testid",`solid-view-${H.id}`),D.addEventListener("click",()=>{se?.setView(H.id)}),c.append(D)}let j=document.createElement("button");j.type="button",j.className="bp-v-btn",j.textContent="Snap view",j.setAttribute("data-testid","solid-snap"),j.addEventListener("click",()=>{if(!se)return;se.snapPng().then((H)=>{if(!H)return;let D=URL.createObjectURL(H),O=document.createElement("a");O.href=D;let Q=(tt()||v||"view").replace(/[^a-zA-Z0-9._-]/g,"_");O.download=`${Q}-snap.png`,O.click(),setTimeout(()=>URL.revokeObjectURL(D),1000)})}),c.append(j)}async function Re(){if(!g||v!=="board"&&v!=="schematic")return;we();let P=B.compareRequest();if(!P){ce="",Ee="",Ie="",K="",await je(!1);return}let j=`${v}|${P.commit}|${P.bits}|${N}`;if(j===K&&S.size>0){Te(B.highlightEdits?`Comparing against ${B.activeRef()?.label||P.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${B.activeRef()?.label||P.commit.slice(0,7)}`,!1);return}let H=++y;S.clear(),M.clear(),qe(),x=!0,ce="",Ee=P.commit,Ie="",K=j;try{let D=N||(v==="schematic"?z.sch:z.pcb)||"";if(!D){let me=await t.hub.rpc("viewer.files",{thread:g});if(H!==y)return;z=me||{},pe(),D=(v==="schematic"?z.sch:z.pcb)||""}if(!D)throw Error(`Unable to resolve ${v} file path for compare`);let O=await t.hub.rpc("viewer.compare",{thread:g,kind:v,commit:P.commit,bits:P.bits,...N?{path:N}:{}});if(H!==y)return;let Q=typeof O?.root==="string"?O.root:"",Z=v==="schematic"?"1":"0";ce=Q?`${Z}|${Q}|diff -`:`${Z}|`,Ee=P.commit,Ie=D.startsWith("/")||/^[A-Za-z]:[\\/]/.test(D)||!Q?D:`${Q.replace(/\/+$/,"")}/${D.replace(/^\/+/,"")}`,x=!1;let he=L;qe();for(let me of he)if(me.kind==="bin")De(me.buf);else He(me.key,me.none,me.retryable);Te(B.highlightEdits?`Comparing against ${B.activeRef()?.label||P.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${B.activeRef()?.label||P.commit.slice(0,7)}`,!1)}catch(D){if(H!==y)return;x=!1,ce="",Ee="",Ie="",K="",qe(),Te(D instanceof Error?D.message:String(D),!0)}}function we(){let P=v==="board"||v==="schematic";if(w.hidden=!P,!P)return;let j=document.createElement("div");j.className="bp-history-group";let H=document.createElement("button");H.type="button",H.className="bp-v-btn",H.textContent="<",H.title="Older snapshot",H.disabled=B.refs.length===0||B.index>=B.refs.length-1,H.setAttribute("data-testid","history-prev"),H.addEventListener("click",()=>{if(te(),B.step(1))Re()});let D=document.createElement("button");D.type="button",D.className="bp-v-btn"+(B.playing?" is-on":""),D.textContent=B.playing?"⏸":"▶",D.title=B.playing?"Pause history":"Play history",D.disabled=B.refs.length===0,D.setAttribute("data-testid","history-play"),D.addEventListener("click",()=>{if(B.playing){te(),we();return}if(B.refs.length===0)return;if(B.playing=!0,B.isLive())B.index=B.refs.length-1,Re();else we();W=window.setInterval(()=>{if(!B.playing||v!=="board"&&v!=="schematic"){te(),we();return}if(B.step(-1))Re();else te(),we()},1400)});let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent=">",O.title="Newer snapshot",O.disabled=B.isLive(),O.setAttribute("data-testid","history-next"),O.addEventListener("click",()=>{if(te(),B.step(-1))Re()});let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn"+(B.isLive()?" is-on":""),Q.textContent="Live",Q.setAttribute("data-testid","history-live"),Q.addEventListener("click",()=>{if(te(),B.goLive())Te("",!1),Re()});let Z=document.createElement("span");Z.className="bp-history-label",Z.setAttribute("data-testid","history-label");let he=B.activeRef();Z.textContent=he?he.label||he.commit.slice(0,7):B.refs.length>0?`Live (${B.refs.length} saved)`:"Live",j.append(H,D,O,Q,Z);let me=document.createElement("div");me.className="bp-history-group";let Ce=document.createElement("button");Ce.type="button",Ce.className="bp-v-btn"+(B.highlightEdits?" is-on":""),Ce.textContent="Highlight edits",Ce.disabled=B.refs.length===0,Ce.setAttribute("data-testid","history-highlight"),Ce.addEventListener("click",()=>{te(),B.toggleHighlight(),Re()});let be=document.createElement("div");be.className="bp-history-menu-wrap";let Se=document.createElement("button");if(Se.type="button",Se.className="bp-v-btn"+(X||!B.isLive()?" is-on":""),Se.disabled=B.refs.length===0,Se.setAttribute("data-testid","history-compare"),Se.setAttribute("aria-haspopup","menu"),Se.setAttribute("aria-expanded",String(X)),Se.textContent=he?`Compare: ${he.label||he.commit.slice(0,7)} ▾`:"Compare ▾",Se.addEventListener("click",(Ae)=>{Ae.stopPropagation(),X=!X,we()}),be.append(Se),X&&B.refs.length>0){let Ae=document.createElement("div");Ae.className="bp-history-menu",Ae.setAttribute("role","menu"),Ae.setAttribute("data-testid","history-compare-menu");let $e=(Me,ze,yt)=>{let Fe=document.createElement("button");Fe.type="button",Fe.className="bp-history-menu-item"+(yt?" is-active":""),Fe.setAttribute("role","menuitem"),Fe.setAttribute("data-commit",ze),Fe.textContent=Me,Fe.addEventListener("click",()=>{if(X=!1,te(),B.selectCommit(ze)){if(B.isLive())Te("",!1);Re()}else we()}),Ae.append(Fe)};$e("Live (working tree)","",B.isLive());for(let Me of B.refs)$e(Me.label||Me.commit.slice(0,7),Me.commit,he?.commit===Me.commit);be.append(Ae)}me.append(Ce,be),w.replaceChildren(j,me)}async function Pe(P){if(!P)return;try{let j=await t.hub.rpc("viewer.refs",{thread:P});if(P!==g)return;B.setRefs(Array.isArray(j?.refs)?j.refs:[]),we()}catch{if(P!==g)return;B.setRefs([]),we()}}function Ge(){return document.documentElement.classList.contains("light")}let vt=new MutationObserver(()=>{let P=Ge();de?.setTheme(P),se?.setTheme(P),oe?.setTheme(P)});vt.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function Le(P,j="",H=!1){if(P==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${P}`;let D=document.createElement("div");D.className="bp-v-state-card";let O=document.createElement("div");if(O.className="bp-v-state-msg",O.textContent=j,D.append(O),H){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn is-primary",Q.textContent=p("tools.retry","Retry"),Q.addEventListener("click",()=>void je(!0)),D.append(Q)}d.replaceChildren(D)}function Te(P,j){m.textContent=P,m.hidden=!P,m.classList.toggle("is-warn",j)}function tt(){if(N)return ft(N);if(v==="board"||v==="3d")return ft(z.pcb);if(v==="schematic")return ft(z.sch);if(v==="mech")return ft(R);return""}function pe(){s.textContent=ki(v);let P=tt();if(r.hidden=!P,a.hidden=!P,a.textContent=P,o.replaceChildren(),v==="mech"&&V.length>1){let H=document.createElement("select");H.className="bp-v-select",H.setAttribute("aria-label",p("viewer.mech","Mech"));for(let D of V){let O=document.createElement("option");O.value=D,O.textContent=ft(D),O.selected=D===R,H.append(O)}H.addEventListener("change",()=>{R=H.value,pe(),je(!1)}),o.append(H)}if(ln(v)){let H=document.createElement("button");H.type="button",H.className="bp-v-btn"+(ae?" is-on":""),H.textContent=A?.layerHead||"Layers",H.setAttribute("data-testid","viewer-layers-btn"),H.addEventListener("click",()=>{if(ae=!ae,b.hidden=!ae,H.classList.toggle("is-on",ae),ae)Ve("","")}),o.append(H)}if(v==="board"||v==="schematic"||v==="3d"||v==="mech"||v==="gerbers"){let H=document.createElement("button");H.type="button",H.className="bp-v-btn",H.textContent="Fit",H.setAttribute("data-testid","viewer-fit-btn"),H.addEventListener("click",()=>{de?.fit(),se?.fit()}),o.append(H)}if((v==="board"||v==="schematic")&&t.hub.hasFeature("follow")){let H=document.createElement("button");H.type="button",H.className="bp-v-btn"+(_&&!q?" is-on":""),H.textContent=_?q?p("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",H.setAttribute("data-testid","viewer-follow-btn"),H.addEventListener("click",()=>void Ze()),o.append(H)}let j=document.createElement("button");j.type="button",j.className="bp-v-btn bp-v-close",j.textContent="✕",j.title=p("common.close","Close"),j.setAttribute("aria-label",p("common.close","Close")),j.setAttribute("data-testid","viewer-close-btn"),j.addEventListener("click",()=>t.closeViewer()),o.append(j)}function xe(){if(!A){b.replaceChildren();return}let P=document.createDocumentFragment(),j=document.createElement("div");j.className="bp-v-layers-head";let H=document.createElement("span");if(H.textContent=A.layerHead||"Layers",j.append(H),A.layerReset){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn",Z.textContent="Reset",Z.addEventListener("click",()=>void Ve("reset","")),j.append(Z)}if(P.append(j),A.layerModes){let Z=document.createElement("div");Z.className="bp-v-layers-modes",["All","Dim","Only"].forEach((he,me)=>{let Ce=document.createElement("button");Ce.type="button",Ce.className="bp-v-btn"+(A?.layerMode===me?" is-on":""),Ce.textContent=he,Ce.addEventListener("click",()=>void Ve("mode",String(me))),Z.append(Ce)}),P.append(Z)}let D=de?.presentColors()??new Map,O=(A.layerList||[]).concat(A.layerMarks||[]),Q=document.createElement("div");Q.className="bp-v-layers-list";for(let Z of O){let he=D.get(Z.layer);if(he===void 0)continue;let me=document.createElement("div");me.className="bp-v-layer-row"+(Z.active?" is-focus":"");let Ce=document.createElement("input");Ce.type="checkbox",Ce.checked=Z.on!==!1,Ce.addEventListener("change",()=>void Ve("toggle",String(Z.layer)));let be=document.createElement("span");be.className="bp-v-layer-swatch";let Se=he>>>16&255,Ae=he>>>8&255,$e=he&255;be.style.background=Z.on!==!1?`rgb(${Se},${Ae},${$e})`:`rgba(${Se},${Ae},${$e},0.2)`;let Me=document.createElement("button");Me.type="button",Me.className="bp-v-layer-name",Me.textContent=Z.name,Me.addEventListener("click",()=>void Ve("pick",String(Z.layer))),me.append(Ce,be,Me),Q.append(me)}P.append(Q),b.replaceChildren(P)}async function Ve(P,j){if(!ln(v))return;let H=y;try{let D=await t.hub.rpc("viewer.layers",{kind:v,present:ve,off:le,focus:I,...P?{action:P,value:j}:{}});if(H!==y||!D)return;le=Number(D.own)||0,I=typeof D.focus==="string"?D.focus:"",A=D;let O={off:Number(D.off)||0,dim:Number(D.dim)||0,lift:typeof D.lift==="number"?D.lift:255};if(de?.setLayers(O),pe(),ae)xe()}catch{}}async function We(){if(!_||q||!g||!t.hub.hasFeature("follow"))return;q=!0,pe();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function Ze(){if(!g||!t.hub.hasFeature("follow"))return;let P=!_?"on":q?"resume":"off";try{let j=await t.hub.rpc("viewer.follow",{thread:g,action:P});if(_=!!j.on,q=!!j.paused,pe(),j.on&&!j.paused&&j.focus&&Array.isArray(j.focus.box)&&j.focus.box.length===4&&(j.seq||0)>ie)ie=j.seq||ie,de?.zoomToBoxMm([j.focus.box[0],j.focus.box[1],j.focus.box[2],j.focus.box[3]])}catch{}}function re(){E.hidden=!0,E.replaceChildren(),de?.setHighlights([])}function st(P){let j=P.split(";").filter(Boolean),H=j.shift()||P,D=[],O="",Q="";for(let be of j){if(be.startsWith("g="))continue;let Se=be.indexOf("=");if(Se>0){let Ae=be.slice(0,Se),$e=be.slice(Se+1);if((Ae==="ref"||Ae==="symbol")&&!O)O=$e;if(Ae==="net"&&!Q)Q=$e;D.push([Ae,$e])}else D.push([be,""])}let Z=document.createElement("div");Z.className="bp-v-info-head";let he=document.createElement("span");he.className="bp-v-info-title",he.textContent=H;let me=document.createElement("button");me.type="button",me.className="bp-v-info-x",me.textContent="×",me.setAttribute("aria-label","Clear selection"),me.addEventListener("click",re),Z.append(he,me);let Ce=document.createElement("div");Ce.className="bp-v-info-rows";for(let[be,Se]of D){let Ae=document.createElement("span");Ae.className="bp-v-info-chip",Ae.textContent=Se?`${be}: ${Se}`:be,Ce.append(Ae)}return E.replaceChildren(Z,...D.length>0?[Ce]:[]),E.hidden=!1,{ref:O||void 0,net:Q||void 0}}async function _e(P){if(!P){re();return}let j=Array.from(S)[0]||"";if(!j)return;let H=y;try{let D=await t.hub.rpc("viewer.info",{key:j,at:P.at,idx:P.idx});if(H!==y)return;let O=typeof D.info==="string"?D.info:"";if(!O){re();return}let{ref:Q,net:Z}=st(O),he=[];if(Q)he.push(["ref",Q]);if(Z)he.push(["net",Z]);let me=[[P.at,P.idx]];for(let[Ce,be]of he){let Se=await t.hub.rpc("viewer.probe",{key:j,name:Ce,value:be});if(H!==y)return;if(Array.isArray(Se.matches))for(let Ae of Se.matches)me.push(Ae)}de?.setHighlights(me)}catch{re()}}function rt(){Y?.destroy(),Y=null,oe?.destroy(),oe=null,de?.destroy(),de=null,se?.destroy(),se=null,h.replaceChildren(),ae=!1,b.hidden=!0,E.hidden=!0,E.replaceChildren(),Te("",!1),Le("none")}function qe(){L=[],T=0}async function je(P){if(!g||!v)return;let j=++y;if(S.clear(),x=!1,qe(),rt(),pe(),Je(),we(),(v==="board"||v==="schematic")&&g)Pe(g);if(ms(v)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),v==="files")Y=mi(h,t,g,(O,Q)=>{if(v=O,N=Q,O==="mech")R=Q;je(!1)});else if(v==="diff")Y=ui(h,t,g);else if(v==="review")Y=bi(h,t,g);else if(v==="browser")Y=di(h,t,g);else if(v==="terminal")Le("loading","Loading terminal…"),import("/assets/terminal.js").then((Q)=>{if(j!==y)return;if(Le("none"),Q?.mountTerminalPane)oe=Q.mountTerminalPane(h,t,g,Ge());else Le("error","Terminal chunk missing",!0)},(Q)=>{if(j!==y)return;Le("error",Q instanceof Error?Q.message:String(Q),!0)});return}if(Le("loading","Loading…"),!z.root)try{let O=await t.hub.rpc("viewer.files",{thread:g});if(j!==y)return;z=O||{},pe()}catch{}if(v==="gerbers"&&z.hasGerbers===!1){Le("empty","No Gerbers in this project",!1);return}let H=Ge();if(v==="3d"||v==="mech")se=new on(h,{onStatus:(O,Q)=>{if(Q)Le("none"),Te(O,!1);else if(O)Le("loading",O);else Le("none"),Te("",!1)},onUserMove:()=>void We()}),se.setTheme(H);else if(v==="board"||v==="schematic"||v==="gerbers")de=new nn(h,{onPick:(O)=>void _e(O),onUserMove:()=>void We()}),de.setTheme(H);else{Le("empty",`${ki(v)} is not available in this viewer`,!1);return}let D={thread:g};if(P)D.force=!0;if(v==="mech"){if(V.length===0)try{let O=await t.hub.rpc("mech.list",{thread:g});if(j!==y)return;if(V=Array.isArray(O.parts)?O.parts:[],!R)R=O.primary||V[0]||"";pe()}catch(O){if(j!==y)return;Le("error",O instanceof Error?O.message:String(O),!0);return}if(!R){Le("empty",p("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}D.kind="3d",D.path=R}else{if(D.kind=v,N&&(v==="board"||v==="schematic"))D.path=N;if(v==="3d"&&!P&&se){let O=se.keptToken();if(O)D.kept=O}if((v==="board"||v==="schematic"||v==="gerbers")&&!P&&t.hub.hasFeature("keptChunks"))D.keptChunks=Array.from(F.keys())}x=!0,ce="",Ee="",Ie="",K="";try{let O=await t.hub.rpc("viewer.watch",D);if(j!==y)return;S=new Set(Array.isArray(O.keys)?O.keys:[]),x=!1;let Q=L;qe();for(let Z of Q)if(Z.kind==="bin")De(Z.buf);else He(Z.key,Z.none,Z.retryable)}catch(O){if(j!==y)return;x=!1,S.clear(),qe();let Q=O instanceof Error?O.message:String(O),Z=/no gerbers|not in this project|another machine/i.test(Q);Le(Z?"empty":"error",Q,!Z)}}function He(P,j,H){if(x){if(L.length{if(P.t==="plot"&&typeof P.none==="string"&&typeof P.key==="string")He(P.key,P.none,P.retryable===!0)}),Pt=xt(()=>{if(v)pe()}),wt=(P)=>{if(P.key==="Escape"&&v&&!E.hidden)re()};return window.addEventListener("keydown",wt),{open(P,j){if(j!==g){if(g=j,z={},V=[],R="",M.clear(),_=!1,q=!1,ie=0,le=0,I="",ve=0,A=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:j}).then((H)=>{if(j!==g)return;if(_=!!H.on,q=!!H.paused,ie=Number(H.seq)||0,v)pe()}).catch(()=>{})}if(P!==v)te(),B.goLive(),le=0,I="",ve=0,A=null;v=P,N="",je(!1)},reconcileHas(P){if(v&&!hs(v,P))t.closeViewer()},close(){if(y++,x=!1,te(),X=!1,ce="",Ee="",Ie="",K="",B.goLive(),c.hidden=!0,w.hidden=!0,qe(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});v="",S.clear(),rt()}}}var Si="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Si,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Si,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function us(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ai(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Li(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function bs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ni(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,m,l);let h=document.createElement("div");h.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let b=document.createElement("span");b.className="bp-dot bp-dot-idle";let E=document.createElement("span");E.className="bp-top-state-word",h.append(d,b,E);let w=document.createElement("div");w.className="bp-top-acts bp-hide-phone bp-hidden";let g=document.createElement("button");g.type="button",g.className="bp-btn-ghost bp-top-act";let v=document.createElement("span");v.textContent=p("menu.pin","Pin"),g.append(gt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),v);let y=document.createElement("button");y.type="button",y.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=p("menu.settle","Settle"),y.append(gt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let S=document.createElement("div");S.className="bp-menu-wrap";let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost bp-top-act",L.textContent="▾",L.title="Thread menu",L.setAttribute("aria-label","Thread menu"),L.setAttribute("data-testid","thread-menu-btn");let T=document.createElement("div");T.className="bp-popover bp-hidden",T.setAttribute("data-testid","thread-menu"),S.append(L,T),w.append(g,y,S);let M=document.createElement("div");M.className="bp-top-right";let F=document.createElement("button");F.type="button",F.className="bp-btn-ghost bp-top-act bp-hide-tablet",F.setAttribute("data-testid","improvements-btn");let z=document.createElement("span");z.textContent=p("gpui.improvements","Improvements"),F.append(gt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),z);let V=document.createElement("button");V.type="button",V.className="bp-cmd-box bp-hide-tablet",V.textContent="> Jump or run a command";let R=document.createElement("button");R.type="button",R.className="icon bp-top-icon",R.title="Search",R.setAttribute("aria-label","Search"),R.appendChild(gt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let N=document.createElement("button");N.type="button",N.className="icon bp-top-icon",N.title=p("palette.settings","Settings"),N.setAttribute("aria-label",p("palette.settings","Settings")),N.setAttribute("data-testid","settings-btn"),N.appendChild(gt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(F,V,R,N),t.append(n,i,h,w,M);let _=document.createElement("div");_.className="bp-body";let q=document.createElement("aside");q.className="bp-sidebar",q.setAttribute("data-testid","sidebar");let ie=document.createElement("main");ie.className="bp-center";let ae=document.createElement("div");ae.className="bp-right-area bp-hidden",ae.setAttribute("data-testid","right-area");let le=document.createElement("div");le.className="bp-right-top";let I=document.createElement("section");I.className="bp-viewer-pane bp-hidden",I.setAttribute("data-testid","viewer-pane"),le.appendChild(I),ae.appendChild(le);let ve=document.createElement("nav");ve.className="bp-rail",ve.setAttribute("aria-label","Viewer rail"),ve.setAttribute("data-testid","viewer-rail"),_.append(q,ie,ae,ve),e.append(t,_);let A=new en,de=null,se=new Set,Y=0,oe=null,B=[],W=[],X=[],ce=[],Ee=[],Ie=[],K="",te=0,Je=0,Re=null,we=null,Pe="",Ge=null,vt=20,Le={},Te=new Map;function tt(u,f){Te.delete(u),Te.set(u,f);while(Te.size>vt){let C=Te.keys().next().value;if(C!==void 0)Te.delete(C);else break}}let pe=new Xt(q,{onSelectThread:(u)=>{if(u===K&&Re!==null){q.classList.remove("bp-sidebar-open");return}be(u)},onNewThread:(u)=>{Me(u)},onSelectBot:(u)=>{be(u.thread)},onThreadAct:(u,f)=>{Ye(u,f)},onToggleSection:(u)=>{if(se.has(u))se.delete(u);else se.add(u);he()},onToggleProjectFold:(u)=>{A.rpc("sidebar.act",{action:"project-fold",value:u}).then(()=>he()).catch(()=>{})},onCollapseSidebar:()=>{q.classList.remove("bp-sidebar-open"),q.classList.add("bp-sidebar-collapsed")},onNeedAct:async(u)=>{let f=Lt(u,!1);if(!f)return;if(f.kind==="thread"){be(f.id);return}if(f.kind!=="call")return;let C=Kn(await A.rpc(f.method,f.params));if(C?.kind==="thread")be(C.id);he()},hasRoomView:!1,onAddProject:()=>He.open({mode:"folder"})}),xe=new $t(ie,{onLoadOlder:()=>{$e()},onGoToEntry:(u)=>{Ae(u)},onAnswerAsk:(u,f)=>{A.rpc("ask.answer",{ask:u,answer:f}).catch((C)=>{re.showError(C instanceof Error?C.message:"Could not send answer")})},onToggleReview:(u)=>{if(!K)return;let f=te;A.rpc("thread.review",{thread:K,on:u}).then((C)=>{if(f===te)xe.setReview(C.review??null)}).catch(()=>{})},onUnansweredAction:(u,f)=>{if(!K)return;if(u==="again"||u==="thread-again")A.rpc("thread.again",{thread:K,value:f}).catch(()=>{});else A.rpc("thread.act",{thread:K,action:u,value:f}).catch(()=>{})},onReplyEntry:(u)=>{if(!A.hasFeature("reply")){let f=(u.text||"").split(` -`)[0]?.slice(0,100)??"";if(f)re.prependDraft(`> ${f} -`);return}if(!u.text||!u.text.trim()||u.live||u.id.startsWith("local-"))return;Fe({id:u.id,text:u.text,role:u.kind==="user"?"user":"assistant"})},onLoadImage:async(u,f)=>{try{let C={entry:u,path:f};if(A.hasFeature("blobs"))C.metaOnly=!0;let k=await A.rpc("message.image",C);if(k.blob&&k.blob.startsWith("/blob/"))return{url:k.blob};if(k.mime&&k.data)return{mime:k.mime,data:k.data}}catch{}return null}});function Ve(u){if(!u)return null;if(u.planMode)return u.planMode;if(u.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function We(u,f){if(!K)return;let C=te,k=K;A.rpc(u,f).then((G)=>{if(C!==te||K!==k)return;if(G.thread){let ee=W.findIndex((ue)=>ue.id===G.thread.id);if(ee>=0)W[ee]=G.thread;else W.unshift(G.thread);pe.setData(B,W,X,ce),xe.updateThreadMeta(G.thread),P(),re.setState(!0,G.thread.state==="working")}}).catch((G)=>{if(C===te&&K===k)re.showError(G instanceof Error?G.message:"Could not change Plan mode")})}let Ze,re=new Gt(ie,{onSend:(u,f)=>{dn(u,f)},onRunCommand:(u)=>{pn(u)},onInterrupt:()=>{if(K)A.rpc("turn.interrupt",{thread:K}).catch(()=>{})},onQueryMentions:async(u,f)=>{try{return(await A.rpc("mentions.list",{q:u,kind:f,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Ze.toggle()},onCyclePlanMode:()=>{let u=W.find((C)=>C.id===K)??null,f=Ve(u);if(!f||!K)return;if(f.interaction!=="plan")We("thread.planonce",{thread:K,on:!0});else if(f.once)We("thread.pick",{thread:K,action:"interaction",value:"plan"});else We("thread.pick",{thread:K,action:"interaction",value:"default"})},onSetPlanMode:(u)=>{if(!K)return;if(u==="once")We("thread.planonce",{thread:K,on:!0});else if(u==="always")We("thread.pick",{thread:K,action:"interaction",value:"plan"});else We("thread.pick",{thread:K,action:"interaction",value:"default"})}});Ze=new Qt(A,{getThreadId:()=>K,getDraft:()=>re.getDraft(),getCaret:()=>re.getCaret(),setDraft:(u)=>re.setDraft(u),setRecording:(u)=>re.setVoiceRecording(u),setLevel:(u)=>re.setVoiceLevel(u),showError:(u)=>re.showError(u)});function st(){let u=Pe!=="",f=_e.isOpen();ae.classList.toggle("bp-hidden",!u&&!f),ae.classList.toggle("bp-has-viewer",u),ae.classList.toggle("bp-has-mgmt",f)}let _e=new _t(le,ae,{hub:A,getThreadId:()=>K,getThreadGen:()=>te,onSendText:(u)=>{dn(u)},onOpenChange:()=>st()});function rt(u){let f=window.prompt("Rename thread",u.title||"");if(!f||!f.trim())return;A.rpc("thread.act",{thread:u.id,action:"rename",title:f.trim()}).then((C)=>{if(C.thread)W=W.map((k)=>k.id===C.thread.id?C.thread:k),P(),he()}).catch((C)=>{re.showError(C instanceof Error?C.message:"Could not rename thread")})}function qe(u){switch(u.type){case"thread":be(u.id);break;case"rail":if(!K&&u.id!=="terminal")break;if(Pe===u.id)j();else H(u.id);break;case"thread-act":if(K)Ye(K,u.action);break;case"new-thread":Me(u.projectId);break;case"rename":{let f=W.find((C)=>C.id===K);if(f)rt(f);break}case"prev-thread":case"next-thread":{let f=W.filter((ee)=>!ee.archived&&!ee.swarm);if(f.length<2)break;let C=f.findIndex((ee)=>ee.id===K),k=u.type==="next-thread"?1:-1,G=f[(C<0?0:C+k+f.length)%f.length];if(G)be(G.id);break}case"command":if(u.runDirectly)pn(u.word);else re.setDraft(`${u.word} `),re.focus();break;case"improvements":wt();break;case"settings":Oe.open();break;case"sidebar":q.classList.toggle("bp-sidebar-open"),q.classList.toggle("bp-sidebar-collapsed");break}}let je=new qt(e,{getState:()=>({selectedThreadId:K,threads:W,projects:B,bots:X,railItems:Ee,commands:Ie}),onSearch:async(u)=>{if(!A.hasFeature("search"))return{threads:[],projects:[],messages:[]};return A.rpc("search",{q:u,limit:20})},onExecute:qe}),He=new Dt(e,{hub:A,onProjectAdded:(u)=>{if(he(),u.id)Me(u.id)},onCloneDone:(u)=>{if(he(),u.thread)be(u.thread)}}),De=new zt(ve,(u)=>{if(u==="commands"){je.open();return}if(!K)return;if(Pe===u)j();else H(u)}),et=null,Oe=new Kt(e,{onLoadDevices:async()=>(await A.rpc("devices.page",{})).rows??[],onDevicesAct:async(u,f)=>{await A.rpc("devices.page.act",{action:u,value:f})},onGetHome:()=>et,onMoveHomeHere:async()=>{await A.rpc("home.move",{to:"back"})},onLogout:()=>An(()=>{A.disconnect(),window.location.replace("/")})});g.addEventListener("click",()=>{let u=W.find((f)=>f.id===K);if(u)Ye(u.id,u.pinned?"unpin":"pin")}),y.addEventListener("click",()=>{let u=W.find((f)=>f.id===K);if(u)Ye(u.id,u.settled?"unsettle":"settle")});let Pt=new Yt(e,(u,f)=>f?A.rpc("thread.context.mcp",{thread:u,...f}):A.rpc("thread.context",{thread:u}));L.addEventListener("click",(u)=>{u.stopPropagation();let f=W.find((G)=>G.id===K);if(!f)return;if(!T.classList.contains("bp-hidden")){T.classList.add("bp-hidden");return}let C=[{label:"Rename…",run:()=>rt(f)},{label:f.pinned?p("menu.unpin","Unpin"):p("menu.pin","Pin"),run:()=>{Ye(f.id,f.pinned?"unpin":"pin")}},{label:f.settled?p("phone.unsettle","Unsettle"):p("menu.settle","Settle"),run:()=>{Ye(f.id,f.settled?"unsettle":"settle")}},{label:f.archived?"Unarchive":"Archive",run:()=>{Ye(f.id,f.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ye(f.id,"delete")}}];if(A.hasFeature("threadContext"))C.unshift({label:p("thread.context.title","Context & Prompt"),run:()=>Pt.open(f.id)});let k=document.createDocumentFragment();for(let G of C){let ee=document.createElement("button");ee.type="button",ee.className="bp-popover-item"+(G.danger?" danger":""),ee.textContent=G.label,ee.addEventListener("click",()=>{T.classList.add("bp-hidden"),G.run()}),k.appendChild(ee)}T.replaceChildren(k),T.classList.remove("bp-hidden")}),document.addEventListener("click",()=>T.classList.add("bp-hidden"));async function wt(){let u=document.createElement("div");u.className="bp-modal-backdrop",u.setAttribute("data-testid","improvements-modal");let f=document.createElement("div");f.className="bp-modal";let C=document.createElement("div");C.className="bp-modal-head";let k=document.createElement("h2");k.textContent=p("gpui.improvements","Improvements");let G=document.createElement("button");G.type="button",G.className="icon",G.textContent="×",G.addEventListener("click",()=>u.remove()),C.append(k,G);let ee=document.createElement("div");ee.className="bp-modal-body",ee.textContent="Loading…",f.append(C,ee),u.appendChild(f),u.addEventListener("click",(ue)=>{if(ue.target===u)u.remove()}),e.appendChild(u);try{let ue=await A.rpc("improvements.projects",{}),Ne=ue.projects??[];if(Ne.length===0){ee.textContent="No projects available for Improvements.";return}let Xe=document.createDocumentFragment();for(let ye of Ne){let ne=document.createElement("div");ne.className="bp-set-row";let Ke=document.createElement("div");Ke.className="bp-set-info",Ke.textContent=ye.title||ye.name||ye.id;let Qe=document.createElement("button");Qe.type="button",Qe.className=ye.id===ue.project?"primary":"",Qe.textContent=ye.id===ue.project?"Active":"Select",Qe.addEventListener("click",()=>{A.rpc("improvements.project",{project:ye.id}).then(()=>u.remove()).catch(()=>{})}),ne.append(Ke,Qe),Xe.appendChild(ne)}ee.replaceChildren(Xe)}catch(ue){ee.textContent=ue instanceof Error?ue.message:"Could not load Improvements."}}F.addEventListener("click",()=>{wt()}),V.addEventListener("click",()=>je.open()),R.addEventListener("click",()=>je.open()),N.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{q.classList.toggle("bp-sidebar-open"),q.classList.toggle("bp-sidebar-collapsed")});function P(){let u=W.find((k)=>k.id===K)??null,f=u?B.find((k)=>k.id===u.project):void 0;o.textContent=f?.title??"",a.classList.toggle("bp-hidden",!f),c.classList.toggle("bp-hidden",!u),m.textContent=u?u.title||"Untitled thread":"";let C=Ve(u);if(re.setPlanMode(C),!C||C.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",C.phase==="executing"),l.title=p("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=C.phase==="armed"&&C.once?p("gpui.planmode.top.once","Plan (1 turn)"):C.phase==="armed"?p("gpui.mgmt.plan.tab","Plan"):C.phase==="planning"?p("gpui.planmode.top.planning","Planning"):C.phase==="pending"?p("gpui.planmode.top.pending","Review plan"):p("gpui.planmode.top.executing","Building plan");if(h.classList.toggle("bp-hidden",!u),w.classList.toggle("bp-hidden",!u),u){b.className=`bp-dot ${us(u)}`,E.textContent=u.status||u.state||"idle",v.textContent=u.pinned?p("menu.unpin","Unpin"):p("menu.pin","Pin"),x.textContent=u.settled?p("phone.unsettle","Unsettle"):p("menu.settle","Settle");let k=u;re.setModelChip(u.chip||u.model||"default",u.provider,k.ctxPct??k.contextPct),re.setMemory(u.memory)}else re.setModelChip("default"),re.setMemory(null)}function j(u=!0){if(Je++,Pe="",De.setActive(""),I.classList.add("bp-hidden"),Ge?.close(),st(),u&&K&&A.getState()==="connected")A.rpc("viewer.watch",{thread:K,kind:""}).catch(()=>{})}function H(u){if(Je++,Pe=u,De.setActive(u),I.classList.remove("bp-hidden"),st(),!Ge&&typeof cn==="function")Ge=cn(I,{hub:A,getThreadId:()=>K,closeViewer:()=>j(!0)});if(Ge)Ge.open(u,K);else{let f=document.createElement("div");f.className="bp-viewer-placeholder";let C=document.createElement("div");C.className="bp-viewer-bar";let k=document.createElement("span");k.textContent=u.toUpperCase();let G=document.createElement("button");G.type="button",G.className="icon",G.textContent="×",G.addEventListener("click",()=>j(!0)),C.append(k,G);let ee=document.createElement("div");ee.className="bp-dim bp-viewer-msg",ee.textContent=`Viewer pane (${u}).`,f.append(C,ee),I.replaceChildren(f)}}async function D(u,f){if(!u||!A.hasFeature("rail")){if(f===te)Ee=[],De.setItems([]);return}let C=++Je;try{let k=await A.rpc("viewer.rail",{thread:u,page:Pe});if(f!==te||C!==Je)return;let G=Array.isArray(k.rail)?k.rail:Array.isArray(k.items)?k.items:[];if(Ee=G,De.setItems(G),k.has){if(Ge?.reconcileHas?.(k.has),Pe&&!Ai(k.has,Pe))j(!0)}}catch{if(f===te&&C===Je)Ee=[],De.setItems([])}}function O(u){for(let f of u)if(f.kind==="threads"){for(let C of f.rows)if(!C.off&&(C.nav||C.id)&&!(C.nav||"").startsWith("@room:"))return C.nav||C.id}else if(f.kind==="projects"){for(let C of f.rows)for(let k of C.threads??[])if(!k.off&&(k.nav||k.id)&&!(k.nav||"").startsWith("@room:"))return k.nav||k.id}return""}function Q(u,f){for(let C of u)if(C.kind==="threads"){if(C.rows.some((k)=>(k.nav||k.id)===f))return!0}else if(C.kind==="projects"){for(let k of C.rows)if((k.threads??[]).some((G)=>(G.nav||G.id)===f))return!0}return!1}function Z(u){let f=[];for(let C of u){if(C.kind!=="projects")continue;for(let k of C.rows)f.push({id:k.id,title:k.title,css:k.css,color:k.color})}if(f.length>0)B=f}async function he(){if(!A.hasFeature("sections"))return!1;let u=++Y;try{let f=await A.rpc("sidebar.sections",{open:Array.from(se)});if(u!==Y)return!0;let C=Array.isArray(f.sections)?f.sections:[];return de=C,Z(C),pe.setData(B,W,X,ce),pe.setSections(C,X,ce),P(),!0}catch{return!1}}function me(){if(!A.hasFeature("sections"))return;if(oe!==null)window.clearTimeout(oe);oe=window.setTimeout(()=>{oe=null,he()},150)}async function Ce(){if(Re=null,A.hasFeature("bots"))try{let f=await A.rpc("bots.list",{});X=f.bots??[],ce=f.rooms??[]}catch{}if(A.hasFeature("shell")){let f=await A.rpc("shell.sync",{have:Le,settled:25}),C=new Set(f.removed??[]),k=new Set((f.projects??[]).map((G)=>G.id));if(C.size>0||k.size>0)B=[...B.filter((G)=>!C.has(G.id)&&!k.has(G.id)),...f.projects??[]],W=[...W.filter((G)=>!C.has(G.project)&&!k.has(G.project)),...f.threads??[]];else if(Array.isArray(f.threads)&&f.threads.length>0){let G=new Map(W.map((ee)=>[ee.id,ee]));for(let ee of f.threads)G.set(ee.id,ee);W=Array.from(G.values())}if(f.sections!==void 0){let G=Array.isArray(f.sections)?f.sections:Array.isArray(f.sections?.sections)?f.sections.sections:null;if(G)de=G,Z(G)}if(f.h)Le=f.h;pe.setData(B,W,X,ce),pe.setSections(de,X,ce)}else if(A.hasFeature("sections")){let[f,C]=await Promise.all([A.rpc("sidebar.sections",{open:Array.from(se)}).catch(()=>null),A.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(W=C.threads??[],f&&Array.isArray(f.sections)){let k=f.sections;if(!k.some((ee)=>ee.kind==="projects"&&ee.rows.length>0)){let ee=k.find((ue)=>ue.kind==="projects"&&ue.fold&&ue.toggle&&(ue.count??0)>0);if(ee?.toggle&&!se.has(ee.toggle)){se.add(ee.toggle);let ue=await A.rpc("sidebar.sections",{open:Array.from(se)}).catch(()=>null);if(ue&&Array.isArray(ue.sections))k=ue.sections}}de=k,Z(k),pe.setData(B,W,X,ce),pe.setSections(k,X,ce)}else de=null,B=(await A.rpc("projects.list",{limit:100})).projects??[],pe.setSections(null,X,ce),pe.setData(B,W,X,ce);await A.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{de=null;let[f,C]=await Promise.all([A.rpc("projects.list",{limit:100}),A.rpc("threads.list",{limit:200,archived:!1})]);B=f.projects??[],W=C.threads??[],pe.setSections(null,X,ce),pe.setData(B,W,X,ce),await A.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let u=K;if(!u){let f="";try{f=localStorage.getItem("bp.lastThread")||""}catch{}if(f&&(de&&Q(de,f)||W.some((C)=>C.id===f)))u=f;else if(de)u=O(de);if(!u)u=(W.find((k)=>!k.archived&&!k.swarm&&!k.settled)??W.find((k)=>!k.archived&&!k.swarm))?.id??""}if(u&&(de&&Q(de,u)||W.some((f)=>f.id===u)))await be(u);else K="",Ee=[],De.setItems([]),re.setState(!1,!1),P()}async function be(u){if(K&&K!==u){Ze.cancel();let ye=xe.getEntries();if(ye.length>0){let ne=Te.get(K);tt(K,{entries:ye,ids:ne?.ids??ye.map((Ke)=>Ke.id),olderCursor:we,review:ne?.review??null,unanswered:ne?.unanswered??null,rail:ne?.rail??Ee,hashes:ne?.hashes??{}})}}let f=++te;Je++,Fe(null);let C=Re;if(Re=null,C!==null)A.rpc("unsubscribe",{sub:C}).catch(()=>{});K=u;let k=Te.get(u);we=k?.olderCursor??null;try{localStorage.setItem("bp.lastThread",u)}catch{}pe.setSelected(u),q.classList.remove("bp-sidebar-open"),P();let G=W.find((ye)=>ye.id===u)??null;if(k)xe.setThread(G,k.entries,Boolean(k.olderCursor),k.review,k.unanswered),Ee=k.rail,De.setItems(k.rail);else xe.setLoading(G),Ee=[],De.setItems([]);if(re.setState(!0,G?.state==="working"),A.hasFeature("open")){let ye={};if(k){for(let[ke,ot]of Object.entries(k.hashes))ye[ke]=ot;for(let ke of k.entries)if(ke.h)ye[ke.id]=ke.h}let ne;try{ne=await A.rpc("thread.open",{thread:u,limit:40,have:ye})}catch(ke){if(f===te){let ot=ke instanceof Error&&ke.message?ke.message:"Could not load messages.";xe.setError(G,ot,()=>{be(u)})}return}if(f!==te){if(ne.sub!==void 0&&ne.sub!==null)A.rpc("unsubscribe",{sub:ne.sub}).catch(()=>{});return}if(Re=ne.sub??null,ne.thread){G=ne.thread;let ke=W.findIndex((ot)=>ot.id===ne.thread.id);if(ke>=0)W[ke]=ne.thread;else W.unshift(ne.thread);P(),re.setState(!0,G.state==="working")}if("next"in ne)we=ne.next??null;let Ke=new Map;if(k)for(let ke of k.entries)Ke.set(ke.id,ke);for(let ke of ne.entries??[])Ke.set(ke.id,ke);let Qe=ne.ids??k?.ids??(ne.entries??[]).map((ke)=>ke.id),mn=Qe.map((ke)=>Ke.get(ke)).filter((ke)=>Boolean(ke)),at=k?.rail??[];if(ne.rail!==void 0){if(Array.isArray(ne.rail))at=ne.rail;else if(at=Array.isArray(ne.rail?.rail)?ne.rail.rail:Array.isArray(ne.rail?.items)?ne.rail.items:[],ne.rail?.has){if(Ge?.reconcileHas?.(ne.rail.has),Pe&&!Ai(ne.rail.has,Pe))j(!0)}}Ee=at,De.setItems(at);let Mt=k?.review??null;if(A.hasFeature("reviewmode"))try{let ke=await A.rpc("thread.review",{thread:u});if(f!==te)return;Mt=ke.review??null}catch{}if(f!==te)return;let un="unanswered"in ne?ne.unanswered??null:k?.unanswered??null,Ti=ne.h??k?.hashes??{};if(tt(u,{entries:mn,ids:Qe,olderCursor:we,review:Mt,unanswered:un,rail:at,hashes:Ti}),xe.setThread(G,mn,Boolean(we),Mt,un),Se(u,f),Pe)H(Pe);return}let ee;try{ee=await A.rpc("thread.entries",{thread:u,limit:40})}catch(ye){if(f===te){let ne=ye instanceof Error&&ye.message?ye.message:"Could not load messages.";xe.setError(G,ne,()=>{be(u)})}return}if(f!==te)return;if(ee.thread){let ye=W.findIndex((ne)=>ne.id===ee.thread.id);if(ye>=0)W[ye]=ee.thread;else W.unshift(ee.thread);P()}we=ee.next??null;let ue=null;if(A.hasFeature("reviewmode"))try{let ye=await A.rpc("thread.review",{thread:u});if(f!==te)return;ue=ye.review??null}catch{}if(f!==te)return;let Ne=ee.entries??[],Xe=ee.unanswered??null;tt(u,{entries:Ne,ids:Ne.map((ye)=>ye.id),olderCursor:we,review:ue,unanswered:Xe,rail:k?.rail??[],hashes:k?.hashes??{}}),xe.setThread(G,Ne,Boolean(we),ue,Xe);try{let ne=(await A.rpc("subscribe",{topic:"thread",thread:u})).sub??null;if(ne!==null){if(f!==te){A.rpc("unsubscribe",{sub:ne}).catch(()=>{});return}Re=ne}}catch{}if(f!==te)return;if(D(u,f),Se(u,f),Pe)H(Pe)}async function Se(u,f){if(!u||!A.hasFeature("mgmt")){if(f===te)_e.clear();return}let C=W.find((G)=>G.id===u),k=C?.project?B.find((G)=>G.id===C.project)?.root??"":"";if(!k&&A.hasFeature("viewers"))try{let G=await A.rpc("viewer.files",{thread:u});if(f!==te)return;k=G.pcb||G.sch||G.root||""}catch{}if(f!==te)return;if(k)await _e.watchProject(k);else _e.clear()}async function Ae(u){let f=te;for(let C=0;C<25&&f===te;C++){if(xe.goTo(u))return;if(!we)return;let k=we;if(await $e(),we===k)return}}async function $e(){if(!K||!we){xe.clearLoadingOlder();return}let u=te,f=K,C=we;try{let k=await A.rpc("thread.entries",{thread:f,limit:40,before:C});if(u!==te||K!==f)return;we=k.next??null,xe.prependEntries(k.entries??[],Boolean(we))}catch{if(u===te)xe.clearLoadingOlder()}}async function Me(u){try{let f=await A.rpc("thread.create",{project:u});if(f.thread)W=[f.thread,...W.filter((C)=>C.id!==f.thread.id)],pe.setData(B,W,X,ce),he(),await be(f.thread.id),re.focus()}catch(f){re.showError(f instanceof Error?f.message:"Could not create thread")}}let ze=null;function yt(u){return(u.split(` -`).map((f)=>f.trim()).find((f)=>f.length>0)??"").slice(0,200)}function Fe(u){ze=u,re.setReply(u?{who:u.role==="user"?p("secret.you","You"):p("model.col.agent","Agent"),line:yt(u.text)}:null,()=>{if(ze)Ae(ze.id)},()=>Fe(null))}async function dn(u,f=[]){if(!K)return;let C=te,k=K,G=bs(),ee=`local-${G}`,ue=ze&&u.trim()&&A.hasFeature("reply")?ze:null;if(ue)Fe(null);xe.upsertEntry({id:ee,kind:"user",text:u,at:Date.now(),clientId:G,...ue?{replyTo:{id:ue.id,quote:yt(ue.text)}}:{},attachments:f.map((Ne)=>({name:Ne.name,mime:Ne.mime,previewUrl:`data:${Ne.mime};base64,${Ne.data}`}))});try{let Ne={thread:k,text:u,clientId:G};if(f.length>0)Ne.attachments=f;if(ue)Ne.replyTo={id:ue.id,text:ue.text};let Xe=await A.rpc("message.send",Ne);if(C!==te||K!==k)return;if(Xe.entry)xe.upsertEntry(Xe.entry)}catch(Ne){if(C===te&&K===k){if(xe.removeEntry(ee),re.setDraft(u),ue&&!ze)Fe(ue);re.showError(Ne instanceof Error?Ne.message:"Failed to send message")}}}async function pn(u){if(!K)return;let f=te,C=K;try{let k=await A.rpc("composer.run",{thread:C,text:u});if(f!==te||K!==C)return;if(k.error)re.setDraft(u),re.showError(k.error);else if(k.kind==="edit"&&typeof k.text==="string")re.setDraft(k.text);else if(k.kind==="project")He.open({mode:"folder"});else if(k.kind==="clone")He.open({mode:"clone",repo:k.repo??"",text:k.text??""})}catch(k){if(f===te&&K===C)re.setDraft(u),re.showError(k instanceof Error?k.message:"Command refused")}}async function Ye(u,f){try{let C=await A.rpc("thread.act",{thread:u,action:f});if(C.thread){if(W=W.map((k)=>k.id===C.thread.id?C.thread:k),pe.setData(B,W,X,ce),C.thread.id===K)xe.updateThreadMeta(C.thread),P()}he()}catch(C){re.showError(C instanceof Error?C.message:`Action "${f}" not allowed`)}}function hn(u,f){if(!u||!u.text||f-u.at>=300000)return"";let C=u.build.split("-").pop()??"";if(u.reason==="build"&&C)return p("hub.restarting.build",u.text,{build:C});if(u.reason==="stop")return p("hub.stopped",u.text);return p("hub.restarting",u.text)}function Et(u){if(u==="connected")pe.setConnStatus(p("gpui.acct.connected","Connected"),"bp-ok");else if(u==="reconnecting"&&hn(A.restarting,Date.now()))pe.setConnStatus(hn(A.restarting,Date.now()),"");else if(u==="reconnecting")pe.setConnStatus("Reconnecting…","bp-warn");else if(u==="revoked")pe.setConnStatus(p("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else pe.setConnStatus("Connecting…","")}xt(()=>{Et(A.getState()),z.textContent=p("gpui.improvements","Improvements"),N.title=p("palette.settings","Settings"),N.setAttribute("aria-label",p("palette.settings","Settings")),P(),pe.refreshLocale(),xe.refreshLocale(),re.refreshLocale(),De.render(),Oe.refreshLocale(),He.refreshLocale()}),A.onState((u,f)=>{if(u==="connected"&&f){if(f.locale)yn(f.locale);if(f.theme)Li(f.theme);if(f.name)pe.setHostName(f.name);if(et=f.home??null,pe.setHome(et),Oe.isOpen())Oe.refresh();Et(u);let C=typeof f.hubBack==="string"?String(f.hubBack):"";if(C)try{let k=JSON.parse(C);if(k.reason==="crash")pe.setConnStatus(p("hub.back.crash",k.text??""),"bp-warn"),window.setTimeout(()=>Et(A.getState()),6000)}catch{}if(re.setFeatures(A.hasFeature("images"),A.hasFeature("voice")),Array.isArray(f.commands))Ie=f.commands,re.setCommands(Ie);else Ie=[];Ce(),He.reconcile()}else Ze.cancel(),Et(u)}),A.onFrame((u)=>{if(u.t==="voice"){Ze.handleFrame(u);return}if(u.t==="info"&&u.info&&typeof u.info==="object"){_e.handleInfo(u.info);return}if(u.t!=="d")return;let f=u;if(f.k==="clone"||f.k==="clone.repos"||f.k==="clone.signin"){He.handleFrame(f);return}switch(f.k){case"project":{let C=f.project;if(!C)break;let k=B.findIndex((G)=>G.id===C.id);if(k>=0)B[k]=C;else B.unshift(C);pe.setData(B,W,X,ce),P(),me();break}case"thread":{let C=f.thread;if(!C)break;let k=W.findIndex((G)=>G.id===C.id);if(k>=0)W[k]=C;else W.unshift(C);if(pe.setData(B,W,X,ce),C.id===K)xe.updateThreadMeta(C),P(),re.setState(!0,C.state==="working");me();break}case"thread.removed":{let C=String(f.id??"");W=W.filter((k)=>k.id!==C),pe.setData(B,W,X,ce),me();break}case"entry":{if(f.thread===K&&f.entry)xe.upsertEntry(f.entry);break}case"text":{if(f.thread===K)xe.appendLiveText(String(f.entry??""),String(f.append??""),Number(f.at??Date.now()));break}case"turn":{if(f.thread===K){let C=String(f.state??"idle");re.setState(!0,C==="working"),D(K,te)}me();break}case"btw":{if(f.thread===K)xe.showBtw(String(f.q??""),String(f.a??""));break}case"unanswered":{if(f.thread===K)xe.setUnanswered(f.unanswered??null);break}case"theme":{if(typeof f.theme==="string")Li(f.theme);break}case"home":{if(et=f.home??null,pe.setHome(et),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(u)=>{let f=u.key.toLowerCase();if((u.ctrlKey||u.metaKey)&&(f==="k"||u.shiftKey&&f==="p"))if(u.preventDefault(),je.isOpen())je.close();else je.open();else if(u.key==="Escape"){if(je.isOpen())je.close();else if(He.isOpen())He.escape();else if(Oe.isOpen())Oe.close();else if(xe.closePlanRevise());else if(_e.isOpen())_e.closePanel()}}),A.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Ni);else Ni(); +`;function _e(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Fs=[_e(77),_e(83),_e(94)],$s=[_e(53),_e(58),_e(67)],Gs=[_e(245),_e(246),_e(248)],Us=[_e(225),_e(228),_e(233)];function Oi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function Vi(e,t,n){let i=Oi(e,e.VERTEX_SHADER,t),s=Oi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Os(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Vs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Wi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function _i(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function gn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class fn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=Vi(n,Rs,js),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=Vi(n,Hs,Ds),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Pi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,c=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,l=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,p=0,b=0;for(let g=0;g>>24&255,S=1-k/255,L=(w>>>16&255)/255,M=(w>>>8&255)/255,B=(w&255)/255,H=g*9;if(k===0&&o&&c&&m){let W=p*9;for(let j=0;j<9;j++)o[W+j]=e[H+j],c[W+j]=t[H+j];let _=p*12;for(let j=0;j<3;j++)m[_+j*4]=L,m[_+j*4+1]=M,m[_+j*4+2]=B,m[_+j*4+3]=1;p++}else if(l&&u&&d){let W=b*9;for(let j=0;j<9;j++)l[W+j]=e[H+j],u[W+j]=t[H+j];let _=b*12;for(let j=0;j<3;j++)d[_+j*4]=L,d[_+j*4+1]=M,d[_+j*4+2]=B,d[_+j*4+3]=S;b++}}let y=o&&c&&m?this.createSubBatch(o,c,m,a*3):null,f=l&&u&&d?this.createSubBatch(l,u,d,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Ui(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Gs:Fs,_=this.lightTheme?Us:$s;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),l=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*u,this.target[1]-this.dist*c*l,this.target[2]+this.dist*m],p=Wi([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),b=Math.abs(p[2])>0.99?[0,1,0]:[0,0,1],y=Wi(_i(p,b)),f=_i(y,p),g=new Float32Array([y[0],f[0],-p[0],0,y[1],f[1],-p[1],0,y[2],f[2],-p[2],0,-gn(y,d),-gn(f,d),gn(p,d),1]),w=Math.max(0.05,this.dist*0.01),k=Math.max(this.dist*10,this.radius*20),S=Vs(35*Math.PI/180,r/o,w,k),L=Os(S,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,p[0],p[1],p[2]);let M=!1,B=[],H=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,j=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(j<1){if(M=!0,j>0)H.push({batch:W,fade:j})}else B.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of B)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of B)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of H)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),M}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var qi=64,Ws=16777216;function _s(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ki(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function vn(e){return e==="board"||e==="schematic"||e==="gerbers"}function qs(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function yn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let p=document.createElement("div");p.className="bp-v-layers",p.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,l.append(u,d,p,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,c,m,l,y);let f="",g="",w=0,k=!1,S=new Set,L=[],M=0,B=new Map,H=new Map,W={},_=[],j="",pe="",le=!1,ie=!1,ye=0,ke=!1,Ne=0,ve="",Me=0,T=null,re=null,ae=null,J=null,ce=null,x=new bn,C=0,I=!1,G="",z="",me="",N="";document.addEventListener("click",(R)=>{if(!I)return;if(R.target instanceof Node&&y.contains(R.target))return;I=!1,de()}),document.addEventListener("keydown",(R)=>{if(I&&R.key==="Escape")I=!1,de()});function Y(){if(C)window.clearInterval(C),C=0;x.playing=!1}function Ie(){let R=g==="3d"||g==="mech";if(c.hidden=!R,!R)return;if(c.childElementCount>0)return;for(let U of Gi){let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent=U.label,F.setAttribute("data-testid",`solid-view-${U.id}`),F.addEventListener("click",()=>{ae?.setView(U.id)}),c.append(F)}let D=document.createElement("button");D.type="button",D.className="bp-v-btn",D.textContent="Snap view",D.setAttribute("data-testid","solid-snap"),D.addEventListener("click",()=>{if(!ae)return;ae.snapPng().then((U)=>{if(!U)return;let F=URL.createObjectURL(U),q=document.createElement("a");q.href=F;let X=(je()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");q.download=`${X}-snap.png`,q.click(),setTimeout(()=>URL.revokeObjectURL(F),1000)})}),c.append(D)}async function Ae(){if(!f||g!=="board"&&g!=="schematic")return;de();let R=x.compareRequest();if(!R){G="",z="",me="",N="",await $e(!1);return}let D=`${g}|${R.commit}|${R.bits}|${pe}`;if(D===N&&S.size>0){te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1);return}let U=++w;S.clear(),B.clear(),Ye(),k=!0,G="",z=R.commit,me="",N=D;try{let F=pe||(g==="schematic"?W.sch:W.pcb)||"";if(!F){let ge=await t.hub.rpc("viewer.files",{thread:f});if(U!==w)return;W=ge||{},Z(),F=(g==="schematic"?W.sch:W.pcb)||""}if(!F)throw Error(`Unable to resolve ${g} file path for compare`);let q=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:R.commit,bits:R.bits,...pe?{path:pe}:{}});if(U!==w)return;let X=typeof q?.root==="string"?q.root:"",Q=g==="schematic"?"1":"0";G=X?`${Q}|${X}|diff +`:`${Q}|`,z=R.commit,me=F.startsWith("/")||/^[A-Za-z]:[\\/]/.test(F)||!X?F:`${X.replace(/\/+$/,"")}/${F.replace(/^\/+/,"")}`,k=!1;let he=L;Ye();for(let ge of he)if(ge.kind==="bin")Ge(ge.buf);else Oe(ge.key,ge.none,ge.retryable);te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1)}catch(F){if(U!==w)return;k=!1,G="",z="",me="",N="",Ye(),te(F instanceof Error?F.message:String(F),!0)}}function de(){let R=g==="board"||g==="schematic";if(y.hidden=!R,!R)return;let D=document.createElement("div");D.className="bp-history-group";let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="<",U.title="Older snapshot",U.disabled=x.refs.length===0||x.index>=x.refs.length-1,U.setAttribute("data-testid","history-prev"),U.addEventListener("click",()=>{if(Y(),x.step(1))Ae()});let F=document.createElement("button");F.type="button",F.className="bp-v-btn"+(x.playing?" is-on":""),F.textContent=x.playing?"⏸":"▶",F.title=x.playing?"Pause history":"Play history",F.disabled=x.refs.length===0,F.setAttribute("data-testid","history-play"),F.addEventListener("click",()=>{if(x.playing){Y(),de();return}if(x.refs.length===0)return;if(x.playing=!0,x.isLive())x.index=x.refs.length-1,Ae();else de();C=window.setInterval(()=>{if(!x.playing||g!=="board"&&g!=="schematic"){Y(),de();return}if(x.step(-1))Ae();else Y(),de()},1400)});let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent=">",q.title="Newer snapshot",q.disabled=x.isLive(),q.setAttribute("data-testid","history-next"),q.addEventListener("click",()=>{if(Y(),x.step(-1))Ae()});let X=document.createElement("button");X.type="button",X.className="bp-v-btn"+(x.isLive()?" is-on":""),X.textContent="Live",X.setAttribute("data-testid","history-live"),X.addEventListener("click",()=>{if(Y(),x.goLive())te("",!1),Ae()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let he=x.activeRef();Q.textContent=he?he.label||he.commit.slice(0,7):x.refs.length>0?`Live (${x.refs.length} saved)`:"Live",D.append(U,F,q,X,Q);let ge=document.createElement("div");ge.className="bp-history-group";let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(x.highlightEdits?" is-on":""),Le.textContent="Highlight edits",Le.disabled=x.refs.length===0,Le.setAttribute("data-testid","history-highlight"),Le.addEventListener("click",()=>{Y(),x.toggleHighlight(),Ae()});let we=document.createElement("div");we.className="bp-history-menu-wrap";let Be=document.createElement("button");if(Be.type="button",Be.className="bp-v-btn"+(I||!x.isLive()?" is-on":""),Be.disabled=x.refs.length===0,Be.setAttribute("data-testid","history-compare"),Be.setAttribute("aria-haspopup","menu"),Be.setAttribute("aria-expanded",String(I)),Be.textContent=he?`Compare: ${he.label||he.commit.slice(0,7)} ▾`:"Compare ▾",Be.addEventListener("click",(Re)=>{Re.stopPropagation(),I=!I,de()}),we.append(Be),I&&x.refs.length>0){let Re=document.createElement("div");Re.className="bp-history-menu",Re.setAttribute("role","menu"),Re.setAttribute("data-testid","history-compare-menu");let We=(De,Xe,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Xe),Ve.textContent=De,Ve.addEventListener("click",()=>{if(I=!1,Y(),x.selectCommit(Xe)){if(x.isLive())te("",!1);Ae()}else de()}),Re.append(Ve)};We("Live (working tree)","",x.isLive());for(let De of x.refs)We(De.label||De.commit.slice(0,7),De.commit,he?.commit===De.commit);we.append(Re)}ge.append(Le,we),y.replaceChildren(D,ge)}async function ee(R){if(!R)return;try{let D=await t.hub.rpc("viewer.refs",{thread:R});if(R!==f)return;x.setRefs(Array.isArray(D?.refs)?D.refs:[]),de()}catch{if(R!==f)return;x.setRefs([]),de()}}function be(){return document.documentElement.classList.contains("light")}let Te=new MutationObserver(()=>{let R=be();re?.setTheme(R),ae?.setTheme(R),ce?.setTheme(R)});Te.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ue(R,D="",U=!1){if(R==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${R}`;let F=document.createElement("div");F.className="bp-v-state-card";let q=document.createElement("div");if(q.className="bp-v-state-msg",q.textContent=D,F.append(q),U){let X=document.createElement("button");X.type="button",X.className="bp-v-btn is-primary",X.textContent=h("tools.retry","Retry"),X.addEventListener("click",()=>void $e(!0)),F.append(X)}d.replaceChildren(F)}function te(R,D){m.textContent=R,m.hidden=!R,m.classList.toggle("is-warn",D)}function je(){if(pe)return xt(pe);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(j);return""}function Z(){s.textContent=Ki(g);let R=je();if(a.hidden=!R,r.hidden=!R,r.textContent=R,o.replaceChildren(),g==="mech"&&_.length>1){let U=document.createElement("select");U.className="bp-v-select",U.setAttribute("aria-label",h("viewer.mech","Mech"));for(let F of _){let q=document.createElement("option");q.value=F,q.textContent=xt(F),q.selected=F===j,U.append(q)}U.addEventListener("change",()=>{j=U.value,Z(),$e(!1)}),o.append(U)}if(vn(g)){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(ke?" is-on":""),U.textContent=T?.layerHead||"Layers",U.setAttribute("data-testid","viewer-layers-btn"),U.addEventListener("click",()=>{if(ke=!ke,p.hidden=!ke,U.classList.toggle("is-on",ke),ke)Ue("","")}),o.append(U)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Fit",U.setAttribute("data-testid","viewer-fit-btn"),U.addEventListener("click",()=>{re?.fit(),ae?.fit()}),o.append(U)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(le&&!ie?" is-on":""),U.textContent=le?ie?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",U.setAttribute("data-testid","viewer-follow-btn"),U.addEventListener("click",()=>void nt()),o.append(U)}let D=document.createElement("button");D.type="button",D.className="bp-v-btn bp-v-close",D.textContent="✕",D.title=h("common.close","Close"),D.setAttribute("aria-label",h("common.close","Close")),D.setAttribute("data-testid","viewer-close-btn"),D.addEventListener("click",()=>t.closeViewer()),o.append(D)}function Ce(){if(!T){p.replaceChildren();return}let R=document.createDocumentFragment(),D=document.createElement("div");D.className="bp-v-layers-head";let U=document.createElement("span");if(U.textContent=T.layerHead||"Layers",D.append(U),T.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void Ue("reset","")),D.append(Q)}if(R.append(D),T.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((he,ge)=>{let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(T?.layerMode===ge?" is-on":""),Le.textContent=he,Le.addEventListener("click",()=>void Ue("mode",String(ge))),Q.append(Le)}),R.append(Q)}let F=re?.presentColors()??new Map,q=(T.layerList||[]).concat(T.layerMarks||[]),X=document.createElement("div");X.className="bp-v-layers-list";for(let Q of q){let he=F.get(Q.layer);if(he===void 0)continue;let ge=document.createElement("div");ge.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Le=document.createElement("input");Le.type="checkbox",Le.checked=Q.on!==!1,Le.addEventListener("change",()=>void Ue("toggle",String(Q.layer)));let we=document.createElement("span");we.className="bp-v-layer-swatch";let Be=he>>>16&255,Re=he>>>8&255,We=he&255;we.style.background=Q.on!==!1?`rgb(${Be},${Re},${We})`:`rgba(${Be},${Re},${We},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=Q.name,De.addEventListener("click",()=>void Ue("pick",String(Q.layer))),ge.append(Le,we,De),X.append(ge)}R.append(X),p.replaceChildren(R)}async function Ue(R,D){if(!vn(g))return;let U=w;try{let F=await t.hub.rpc("viewer.layers",{kind:g,present:Me,off:Ne,focus:ve,...R?{action:R,value:D}:{}});if(U!==w||!F)return;Ne=Number(F.own)||0,ve=typeof F.focus==="string"?F.focus:"",T=F;let q={off:Number(F.off)||0,dim:Number(F.dim)||0,lift:typeof F.lift==="number"?F.lift:255};if(re?.setLayers(q),Z(),ke)Ce()}catch{}}async function ze(){if(!le||ie||!f||!t.hub.hasFeature("follow"))return;ie=!0,Z();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function nt(){if(!f||!t.hub.hasFeature("follow"))return;let R=!le?"on":ie?"resume":"off";try{let D=await t.hub.rpc("viewer.follow",{thread:f,action:R});if(le=!!D.on,ie=!!D.paused,Z(),D.on&&!D.paused&&D.focus&&Array.isArray(D.focus.box)&&D.focus.box.length===4&&(D.seq||0)>ye)ye=D.seq||ye,re?.zoomToBoxMm([D.focus.box[0],D.focus.box[1],D.focus.box[2],D.focus.box[3]])}catch{}}function oe(){b.hidden=!0,b.replaceChildren(),re?.setHighlights([])}function lt(R){let D=R.split(";").filter(Boolean),U=D.shift()||R,F=[],q="",X="";for(let we of D){if(we.startsWith("g="))continue;let Be=we.indexOf("=");if(Be>0){let Re=we.slice(0,Be),We=we.slice(Be+1);if((Re==="ref"||Re==="symbol")&&!q)q=We;if(Re==="net"&&!X)X=We;F.push([Re,We])}else F.push([we,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let he=document.createElement("span");he.className="bp-v-info-title",he.textContent=U;let ge=document.createElement("button");ge.type="button",ge.className="bp-v-info-x",ge.textContent="×",ge.setAttribute("aria-label","Clear selection"),ge.addEventListener("click",oe),Q.append(he,ge);let Le=document.createElement("div");Le.className="bp-v-info-rows";for(let[we,Be]of F){let Re=document.createElement("span");Re.className="bp-v-info-chip",Re.textContent=Be?`${we}: ${Be}`:we,Le.append(Re)}return b.replaceChildren(Q,...F.length>0?[Le]:[]),b.hidden=!1,{ref:q||void 0,net:X||void 0}}async function Je(R){if(!R){oe();return}let D=Array.from(S)[0]||"";if(!D)return;let U=w;try{let F=await t.hub.rpc("viewer.info",{key:D,at:R.at,idx:R.idx});if(U!==w)return;let q=typeof F.info==="string"?F.info:"";if(!q){oe();return}let{ref:X,net:Q}=lt(q),he=[];if(X)he.push(["ref",X]);if(Q)he.push(["net",Q]);let ge=[[R.at,R.idx]];for(let[Le,we]of he){let Be=await t.hub.rpc("viewer.probe",{key:D,name:Le,value:we});if(U!==w)return;if(Array.isArray(Be.matches))for(let Re of Be.matches)ge.push(Re)}re?.setHighlights(ge)}catch{oe()}}function ct(){J?.destroy(),J=null,ce?.destroy(),ce=null,re?.destroy(),re=null,ae?.destroy(),ae=null,u.replaceChildren(),ke=!1,p.hidden=!0,b.hidden=!0,b.replaceChildren(),te("",!1),ue("none")}function Ye(){L=[],M=0}async function $e(R){if(!f||!g)return;let D=++w;if(S.clear(),k=!1,Ye(),ct(),Z(),Ie(),de(),(g==="board"||g==="schematic")&&f)ee(f);if(qs(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")J=Hi(u,t,f,(q,X)=>{if(g=q,pe=X,q==="mech")j=X;$e(!1)});else if(g==="diff")J=Di(u,t,f);else if(g==="review")J=Fi(u,t,f);else if(g==="browser")J=Ii(u,t,f);else if(g==="terminal")ue("loading","Loading terminal…"),import("/assets/terminal.js").then((X)=>{if(D!==w)return;if(ue("none"),X?.mountTerminalPane)ce=X.mountTerminalPane(u,t,f,be());else ue("error","Terminal chunk missing",!0)},(X)=>{if(D!==w)return;ue("error",X instanceof Error?X.message:String(X),!0)});return}if(ue("loading","Loading…"),!W.root)try{let q=await t.hub.rpc("viewer.files",{thread:f});if(D!==w)return;W=q||{},Z()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){ue("empty","No Gerbers in this project",!1);return}let U=be();if(g==="3d"||g==="mech")ae=new fn(u,{onStatus:(q,X)=>{if(X)ue("none"),te(q,!1);else if(q)ue("loading",q);else ue("none"),te("",!1)},onUserMove:()=>void ze()}),ae.setTheme(U);else if(g==="board"||g==="schematic"||g==="gerbers")re=new hn(u,{onPick:(q)=>void Je(q),onUserMove:()=>void ze()}),re.setTheme(U);else{ue("empty",`${Ki(g)} is not available in this viewer`,!1);return}let F={thread:f};if(R)F.force=!0;if(g==="mech"){if(_.length===0)try{let q=await t.hub.rpc("mech.list",{thread:f});if(D!==w)return;if(_=Array.isArray(q.parts)?q.parts:[],!j)j=q.primary||_[0]||"";Z()}catch(q){if(D!==w)return;ue("error",q instanceof Error?q.message:String(q),!0);return}if(!j){ue("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}F.kind="3d",F.path=j}else{if(F.kind=g,pe&&(g==="board"||g==="schematic"))F.path=pe;if(g==="3d"&&!R&&ae){let q=ae.keptToken();if(q)F.kept=q}if((g==="board"||g==="schematic"||g==="gerbers")&&!R&&t.hub.hasFeature("keptChunks"))F.keptChunks=Array.from(H.keys())}k=!0,G="",z="",me="",N="";try{let q=await t.hub.rpc("viewer.watch",F);if(D!==w)return;S=new Set(Array.isArray(q.keys)?q.keys:[]),k=!1;let X=L;Ye();for(let Q of X)if(Q.kind==="bin")Ge(Q.buf);else Oe(Q.key,Q.none,Q.retryable)}catch(q){if(D!==w)return;k=!1,S.clear(),Ye();let X=q instanceof Error?q.message:String(q),Q=/no gerbers|not in this project|another machine/i.test(X);ue(Q?"empty":"error",X,!Q)}}function Oe(R,D,U){if(k){if(L.length{if(R.t==="plot"&&typeof R.none==="string"&&typeof R.key==="string")Oe(R.key,R.none,R.retryable===!0)}),Dt=Lt(()=>{if(g)Z()}),kt=(R)=>{if(R.key==="Escape"&&g&&!b.hidden)oe()};return window.addEventListener("keydown",kt),{open(R,D){if(D!==f){if(f=D,W={},_=[],j="",B.clear(),le=!1,ie=!1,ye=0,Ne=0,ve="",Me=0,T=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:D}).then((U)=>{if(D!==f)return;if(le=!!U.on,ie=!!U.paused,ye=Number(U.seq)||0,g)Z()}).catch(()=>{})}if(R!==g)Y(),x.goLive(),Ne=0,ve="",Me=0,T=null;g=R,pe="",$e(!1)},reconcileHas(R){if(g&&!_s(g,R))t.closeViewer()},close(){if(w++,k=!1,Y(),I=!1,G="",z="",me="",N="",x.goLive(),c.hidden=!0,y.hidden=!0,Ye(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",S.clear(),ct()}}}var zi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(zi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(zi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ks(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ji(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Yi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function zs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Xi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,c,m,l);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let p=document.createElement("span");p.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(d,p,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let k=document.createElement("span");k.textContent=h("menu.settle","Settle"),w.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),k);let S=document.createElement("div");S.className="bp-menu-wrap";let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost bp-top-act",L.textContent="▾",L.title="Thread menu",L.setAttribute("aria-label","Thread menu"),L.setAttribute("data-testid","thread-menu-btn");let M=document.createElement("div");M.className="bp-popover bp-hidden",M.setAttribute("data-testid","thread-menu"),S.append(L,M),y.append(f,w,S);let B=document.createElement("div");B.className="bp-top-right";let H=document.createElement("button");H.type="button",H.className="bp-btn-ghost bp-top-act bp-hide-tablet",H.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=h("gpui.improvements","Improvements"),H.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let j=document.createElement("button");j.type="button",j.className="icon bp-top-icon",j.title="Search",j.setAttribute("aria-label","Search"),j.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let pe=document.createElement("button");pe.type="button",pe.className="icon bp-top-icon",pe.title=h("palette.settings","Settings"),pe.setAttribute("aria-label",h("palette.settings","Settings")),pe.setAttribute("data-testid","settings-btn"),pe.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),B.append(H,_,j,pe),t.append(n,i,u,y,B);let le=document.createElement("div");le.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let ke=document.createElement("div");ke.className="bp-right-area bp-hidden",ke.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let ve=document.createElement("section");ve.className="bp-viewer-pane bp-hidden",ve.setAttribute("data-testid","viewer-pane"),Ne.appendChild(ve),ke.appendChild(Ne);let Me=document.createElement("nav");Me.className="bp-rail",Me.setAttribute("aria-label","Viewer rail"),Me.setAttribute("data-testid","viewer-rail"),le.append(ie,ye,ke,Me),e.append(t,le);let T=new pn,re=null,ae=new Set,J=0,ce=null,x=[],C=[],I=[],G=[],z=[],me=[],N="",Y=0,Ie=0,Ae=null,de=null,ee="",be=null,Te=20,ue={},te=new Map;function je(v,E){te.delete(v),te.set(v,E);while(te.size>Te){let A=te.keys().next().value;if(A!==void 0)te.delete(A);else break}}let Z=new ln(ie,{onSelectThread:(v)=>{if(v===N&&Ae!==null){ie.classList.remove("bp-sidebar-open");return}we(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{we(v.thread)},onThreadAct:(v,E)=>{Qe(v,E)},onToggleSection:(v)=>{if(ae.has(v))ae.delete(v);else ae.add(v);he()},onToggleProjectFold:(v)=>{T.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>he()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let E=Rt(v,!1);if(!E)return;if(E.kind==="thread"){we(E.id);return}if(E.kind!=="call")return;let A=fi(await T.rpc(E.method,E.params));if(A?.kind==="thread")we(A.id);he()},hasRoomView:!1,onAddProject:()=>Oe.open({mode:"folder"})}),Ce=new qt(ye,{onLoadOlder:()=>{We()},onGoToEntry:(v)=>{Re(v)},onAnswerAsk:(v,E)=>{T.rpc("ask.answer",{ask:v,answer:E}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not send answer")})},onToggleReview:(v)=>{if(!N)return;let E=Y;T.rpc("thread.review",{thread:N,on:v}).then((A)=>{if(E===Y)Ce.setReview(A.review??null)}).catch(()=>{})},onUnansweredAction:(v,E)=>{if(!N)return;if(v==="again"||v==="thread-again")T.rpc("thread.again",{thread:N,value:E}).catch(()=>{});else T.rpc("thread.act",{thread:N,action:v,value:E}).catch(()=>{})},onReplyEntry:(v)=>{if(!T.hasFeature("reply")){let E=(v.text||"").split(` +`)[0]?.slice(0,100)??"";if(E)oe.prependDraft(`> ${E} +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,E)=>{try{let A={entry:v,path:E};if(T.hasFeature("blobs"))A.metaOnly=!0;let P=await T.rpc("message.image",A);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function Ue(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function ze(v,E){if(!N)return;let A=Y,P=N;T.rpc(v,E).then((V)=>{if(A!==Y||N!==P)return;if(V.thread){let ne=C.findIndex((fe)=>fe.id===V.thread.id);if(ne>=0)C[ne]=V.thread;else C.unshift(V.thread);Z.setData(x,C,I,G),Ce.updateThreadMeta(V.thread),R(),oe.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(A===Y&&N===P)oe.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let nt,oe=new zt(ye,{onSend:(v,E)=>{wn(v,E)},onRunCommand:(v)=>{En(v)},onInterrupt:()=>{if(N)T.rpc("turn.interrupt",{thread:N}).catch(()=>{})},onQueryMentions:async(v,E)=>{try{return(await T.rpc("mentions.list",{q:v,kind:E,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=C.find((A)=>A.id===N)??null,E=Ue(v);if(!E||!N)return;if(E.interaction!=="plan")ze("thread.planonce",{thread:N,on:!0});else if(E.once)ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!N)return;if(v==="once")ze("thread.planonce",{thread:N,on:!0});else if(v==="always")ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})}});nt=new cn(T,{getThreadId:()=>N,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function lt(){let v=ee!=="",E=Je.isOpen();ke.classList.toggle("bp-hidden",!v&&!E),ke.classList.toggle("bp-has-viewer",v),ke.classList.toggle("bp-has-mgmt",E)}let Je=new tn(Ne,ke,{hub:T,getThreadId:()=>N,getThreadGen:()=>Y,onSendText:(v)=>{wn(v)},onOpenChange:()=>lt()});function ct(v){let E=window.prompt("Rename thread",v.title||"");if(!E||!E.trim())return;T.rpc("thread.act",{thread:v.id,action:"rename",title:E.trim()}).then((A)=>{if(A.thread)C=C.map((P)=>P.id===A.thread.id?A.thread:P),R(),he()}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":we(v.id);break;case"rail":if(!N&&v.id!=="terminal")break;if(ee===v.id)D();else U(v.id);break;case"thread-act":if(N)Qe(N,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let E=C.find((A)=>A.id===N);if(E)ct(E);break}case"prev-thread":case"next-thread":{let E=C.filter((ne)=>!ne.archived&&!ne.swarm);if(E.length<2)break;let A=E.findIndex((ne)=>ne.id===N),P=v.type==="next-thread"?1:-1,V=E[(A<0?0:A+P+E.length)%E.length];if(V)we(V.id);break}case"command":if(v.runDirectly)En(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":kt();break;case"settings":qe.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let $e=new nn(e,{getState:()=>({selectedThreadId:N,threads:C,projects:x,bots:I,railItems:z,commands:me}),onSearch:async(v)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:v,limit:20})},onExecute:Ye}),Oe=new Vt(e,{hub:T,onProjectAdded:(v)=>{if(he(),v.id)De(v.id)},onCloneDone:(v)=>{if(he(),v.thread)we(v.thread)}}),Ge=new sn(Me,(v)=>{if(v==="commands"){$e.open();return}if(!N)return;if(ee===v)D();else U(v)}),it=null,qe=new an(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,E)=>{await T.rpc("devices.page.act",{action:v,value:E})},onGetHome:()=>it,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>Hn(()=>{T.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let Dt=new on(e,(v,E)=>E?T.rpc("thread.context.mcp",{thread:v,...E}):T.rpc("thread.context",{thread:v}));L.addEventListener("click",(v)=>{v.stopPropagation();let E=C.find((V)=>V.id===N);if(!E)return;if(!M.classList.contains("bp-hidden")){M.classList.add("bp-hidden");return}let A=[{label:"Rename…",run:()=>ct(E)},{label:E.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(E.id,E.pinned?"unpin":"pin")}},{label:E.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(E.id,E.settled?"unsettle":"settle")}},{label:E.archived?"Unarchive":"Archive",run:()=>{Qe(E.id,E.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(E.id,"delete")}}];if(T.hasFeature("threadContext"))A.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Dt.open(E.id)});let P=document.createDocumentFragment();for(let V of A){let ne=document.createElement("button");ne.type="button",ne.className="bp-popover-item"+(V.danger?" danger":""),ne.textContent=V.label,ne.addEventListener("click",()=>{M.classList.add("bp-hidden"),V.run()}),P.appendChild(ne)}M.replaceChildren(P),M.classList.remove("bp-hidden")}),document.addEventListener("click",()=>M.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let E=document.createElement("div");E.className="bp-modal";let A=document.createElement("div");A.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),A.append(P,V);let ne=document.createElement("div");ne.className="bp-modal-body",ne.textContent="Loading…",E.append(A,ne),v.appendChild(E),v.addEventListener("click",(fe)=>{if(fe.target===v)v.remove()}),e.appendChild(v);try{let fe=await T.rpc("improvements.projects",{}),He=fe.projects??[];if(He.length===0){ne.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Se of He){let se=document.createElement("div");se.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Se.title||Se.name||Se.id;let tt=document.createElement("button");tt.type="button",tt.className=Se.id===fe.project?"primary":"",tt.textContent=Se.id===fe.project?"Active":"Select",tt.addEventListener("click",()=>{T.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Ze,tt),et.appendChild(se)}ne.replaceChildren(et)}catch(fe){ne.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}H.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>$e.open()),j.addEventListener("click",()=>$e.open()),pe.addEventListener("click",()=>{qe.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function R(){let v=C.find((P)=>P.id===N)??null,E=v?x.find((P)=>P.id===v.project):void 0;o.textContent=E?.title??"",r.classList.toggle("bp-hidden",!E),c.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let A=Ue(v);if(oe.setPlanMode(A),!A||A.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",A.phase==="executing"),l.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=A.phase==="armed"&&A.once?h("gpui.planmode.top.once","Plan (1 turn)"):A.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):A.phase==="planning"?h("gpui.planmode.top.planning","Planning"):A.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){p.className=`bp-dot ${Ks(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),k.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;oe.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function D(v=!0){if(Ie++,ee="",Ge.setActive(""),ve.classList.add("bp-hidden"),be?.close(),lt(),v&&N&&T.getState()==="connected")T.rpc("viewer.watch",{thread:N,kind:""}).catch(()=>{})}function U(v){if(Ie++,ee=v,Ge.setActive(v),ve.classList.remove("bp-hidden"),lt(),!be&&typeof yn==="function")be=yn(ve,{hub:T,getThreadId:()=>N,closeViewer:()=>D(!0)});if(be)be.open(v,N);else{let E=document.createElement("div");E.className="bp-viewer-placeholder";let A=document.createElement("div");A.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>D(!0)),A.append(P,V);let ne=document.createElement("div");ne.className="bp-dim bp-viewer-msg",ne.textContent=`Viewer pane (${v}).`,E.append(A,ne),ve.replaceChildren(E)}}async function F(v,E){if(!v||!T.hasFeature("rail")){if(E===Y)z=[],Ge.setItems([]);return}let A=++Ie;try{let P=await T.rpc("viewer.rail",{thread:v,page:ee});if(E!==Y||A!==Ie)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(z=V,Ge.setItems(V),P.has){if(be?.reconcileHas?.(P.has),ee&&!Ji(P.has,ee))D(!0)}}catch{if(E===Y&&A===Ie)z=[],Ge.setItems([])}}function q(v){for(let E of v)if(E.kind==="threads"){for(let A of E.rows)if(!A.off&&(A.nav||A.id)&&!(A.nav||"").startsWith("@room:"))return A.nav||A.id}else if(E.kind==="projects"){for(let A of E.rows)for(let P of A.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function X(v,E){for(let A of v)if(A.kind==="threads"){if(A.rows.some((P)=>(P.nav||P.id)===E))return!0}else if(A.kind==="projects"){for(let P of A.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===E))return!0}return!1}function Q(v){let E=[];for(let A of v){if(A.kind!=="projects")continue;for(let P of A.rows)E.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(E.length>0)x=E}async function he(){if(!T.hasFeature("sections"))return!1;let v=++J;try{let E=await T.rpc("sidebar.sections",{open:Array.from(ae)});if(v!==J)return!0;let A=Array.isArray(E.sections)?E.sections:[];return re=A,Q(A),Z.setData(x,C,I,G),Z.setSections(A,I,G),R(),!0}catch{return!1}}function ge(){if(!T.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,he()},150)}async function Le(){if(Ae=null,T.hasFeature("bots"))try{let E=await T.rpc("bots.list",{});I=E.bots??[],G=E.rooms??[]}catch{}if(T.hasFeature("shell")){let E=await T.rpc("shell.sync",{have:ue,settled:25}),A=new Set(E.removed??[]),P=new Set((E.projects??[]).map((V)=>V.id));if(A.size>0||P.size>0)x=[...x.filter((V)=>!A.has(V.id)&&!P.has(V.id)),...E.projects??[]],C=[...C.filter((V)=>!A.has(V.project)&&!P.has(V.project)),...E.threads??[]];else if(Array.isArray(E.threads)&&E.threads.length>0){let V=new Map(C.map((ne)=>[ne.id,ne]));for(let ne of E.threads)V.set(ne.id,ne);C=Array.from(V.values())}if(E.sections!==void 0){let V=Array.isArray(E.sections)?E.sections:Array.isArray(E.sections?.sections)?E.sections.sections:null;if(V)re=V,Q(V)}if(E.h)ue=E.h;Z.setData(x,C,I,G),Z.setSections(re,I,G)}else if(T.hasFeature("sections")){let[E,A]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(ae)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(C=A.threads??[],E&&Array.isArray(E.sections)){let P=E.sections;if(!P.some((ne)=>ne.kind==="projects"&&ne.rows.length>0)){let ne=P.find((fe)=>fe.kind==="projects"&&fe.fold&&fe.toggle&&(fe.count??0)>0);if(ne?.toggle&&!ae.has(ne.toggle)){ae.add(ne.toggle);let fe=await T.rpc("sidebar.sections",{open:Array.from(ae)}).catch(()=>null);if(fe&&Array.isArray(fe.sections))P=fe.sections}}re=P,Q(P),Z.setData(x,C,I,G),Z.setSections(P,I,G)}else re=null,x=(await T.rpc("projects.list",{limit:100})).projects??[],Z.setSections(null,I,G),Z.setData(x,C,I,G);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{re=null;let[E,A]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);x=E.projects??[],C=A.threads??[],Z.setSections(null,I,G),Z.setData(x,C,I,G),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=N;if(!v){let E="";try{E=localStorage.getItem("bp.lastThread")||""}catch{}if(E&&(re&&X(re,E)||C.some((A)=>A.id===E)))v=E;else if(re)v=q(re);if(!v)v=(C.find((P)=>!P.archived&&!P.swarm&&!P.settled)??C.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(re&&X(re,v)||C.some((E)=>E.id===v)))await we(v);else N="",z=[],Ge.setItems([]),oe.setState(!1,!1),R()}async function we(v){if(N&&N!==v){nt.cancel();let Se=Ce.getEntries();if(Se.length>0){let se=te.get(N);je(N,{entries:Se,ids:se?.ids??Se.map((Ze)=>Ze.id),olderCursor:de,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??z,hashes:se?.hashes??{}})}}let E=++Y;Ie++,Ve(null);let A=Ae;if(Ae=null,A!==null)T.rpc("unsubscribe",{sub:A}).catch(()=>{});N=v;let P=te.get(v);de=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}Z.setSelected(v),ie.classList.remove("bp-sidebar-open"),R();let V=C.find((Se)=>Se.id===v)??null;if(P)Ce.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),z=P.rail,Ge.setItems(P.rail);else Ce.setLoading(V),z=[],Ge.setItems([]);if(oe.setState(!0,V?.state==="working"),T.hasFeature("open")){let Se={};if(P){for(let[Pe,pt]of Object.entries(P.hashes))Se[Pe]=pt;for(let Pe of P.entries)if(Pe.h)Se[Pe.id]=Pe.h}let se;try{se=await T.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Pe){if(E===Y){let pt=Pe instanceof Error&&Pe.message?Pe.message:"Could not load messages.";Ce.setError(V,pt,()=>{we(v)})}return}if(E!==Y){if(se.sub!==void 0&&se.sub!==null)T.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Ae=se.sub??null,se.thread){V=se.thread;let Pe=C.findIndex((pt)=>pt.id===se.thread.id);if(Pe>=0)C[Pe]=se.thread;else C.unshift(se.thread);R(),oe.setState(!0,V.state==="working")}if("next"in se)de=se.next??null;let Ze=new Map;if(P)for(let Pe of P.entries)Ze.set(Pe.id,Pe);for(let Pe of se.entries??[])Ze.set(Pe.id,Pe);let tt=se.ids??P?.ids??(se.entries??[]).map((Pe)=>Pe.id),Cn=tt.map((Pe)=>Ze.get(Pe)).filter((Pe)=>Boolean(Pe)),dt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))dt=se.rail;else if(dt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(be?.reconcileHas?.(se.rail.has),ee&&!Ji(se.rail.has,ee))D(!0)}}z=dt,Ge.setItems(dt);let Ft=P?.review??null;if(T.hasFeature("reviewmode"))try{let Pe=await T.rpc("thread.review",{thread:v});if(E!==Y)return;Ft=Pe.review??null}catch{}if(E!==Y)return;let kn="unanswered"in se?se.unanswered??null:P?.unanswered??null,Zi=se.h??P?.hashes??{};if(je(v,{entries:Cn,ids:tt,olderCursor:de,review:Ft,unanswered:kn,rail:dt,hashes:Zi}),Ce.setThread(V,Cn,Boolean(de),Ft,kn),Be(v,E),ee)U(ee);return}let ne;try{ne=await T.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(E===Y){let se=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";Ce.setError(V,se,()=>{we(v)})}return}if(E!==Y)return;if(ne.thread){let Se=C.findIndex((se)=>se.id===ne.thread.id);if(Se>=0)C[Se]=ne.thread;else C.unshift(ne.thread);R()}de=ne.next??null;let fe=null;if(T.hasFeature("reviewmode"))try{let Se=await T.rpc("thread.review",{thread:v});if(E!==Y)return;fe=Se.review??null}catch{}if(E!==Y)return;let He=ne.entries??[],et=ne.unanswered??null;je(v,{entries:He,ids:He.map((Se)=>Se.id),olderCursor:de,review:fe,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),Ce.setThread(V,He,Boolean(de),fe,et);try{let se=(await T.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(E!==Y){T.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Ae=se}}catch{}if(E!==Y)return;if(F(v,E),Be(v,E),ee)U(ee)}async function Be(v,E){if(!v||!T.hasFeature("mgmt")){if(E===Y)Je.clear();return}let A=C.find((V)=>V.id===v),P=A?.project?x.find((V)=>V.id===A.project)?.root??"":"";if(!P&&T.hasFeature("viewers"))try{let V=await T.rpc("viewer.files",{thread:v});if(E!==Y)return;P=V.pcb||V.sch||V.root||""}catch{}if(E!==Y)return;if(P)await Je.watchProject(P);else Je.clear()}async function Re(v){let E=Y;for(let A=0;A<25&&E===Y;A++){if(Ce.goTo(v))return;if(!de)return;let P=de;if(await We(),de===P)return}}async function We(){if(!N||!de){Ce.clearLoadingOlder();return}let v=Y,E=N,A=de;try{let P=await T.rpc("thread.entries",{thread:E,limit:40,before:A});if(v!==Y||N!==E)return;de=P.next??null,Ce.prependEntries(P.entries??[],Boolean(de))}catch{if(v===Y)Ce.clearLoadingOlder()}}async function De(v){try{let E=await T.rpc("thread.create",{project:v});if(E.thread)C=[E.thread,...C.filter((A)=>A.id!==E.thread.id)],Z.setData(x,C,I,G),he(),await we(E.thread.id),oe.focus()}catch(E){oe.showError(E instanceof Error?E.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` +`).map((E)=>E.trim()).find((E)=>E.length>0)??"").slice(0,200)}function Ve(v){Xe=v,oe.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Re(Xe.id)},()=>Ve(null))}async function wn(v,E=[]){if(!N)return;let A=Y,P=N,V=zs(),ne=`local-${V}`,fe=Xe&&v.trim()&&T.hasFeature("reply")?Xe:null;if(fe)Ve(null);Ce.upsertEntry({id:ne,kind:"user",text:v,at:Date.now(),clientId:V,...fe?{replyTo:{id:fe.id,quote:St(fe.text)}}:{},attachments:E.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:V};if(E.length>0)He.attachments=E;if(fe)He.replyTo={id:fe.id,text:fe.text};let et=await T.rpc("message.send",He);if(A!==Y||N!==P)return;if(et.entry)Ce.upsertEntry(et.entry)}catch(He){if(A===Y&&N===P){if(Ce.removeEntry(ne),oe.setDraft(v),fe&&!Xe)Ve(fe);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function En(v){if(!N)return;let E=Y,A=N;try{let P=await T.rpc("composer.run",{thread:A,text:v});if(E!==Y||N!==A)return;if(P.error)oe.setDraft(v),oe.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")oe.setDraft(P.text);else if(P.kind==="project")Oe.open({mode:"folder"});else if(P.kind==="clone")Oe.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(E===Y&&N===A)oe.setDraft(v),oe.showError(P instanceof Error?P.message:"Command refused")}}async function Qe(v,E){try{let A=await T.rpc("thread.act",{thread:v,action:E});if(A.thread){if(C=C.map((P)=>P.id===A.thread.id?A.thread:P),Z.setData(x,C,I,G),A.thread.id===N)Ce.updateThreadMeta(A.thread),R()}he()}catch(A){oe.showError(A instanceof Error?A.message:`Action "${E}" not allowed`)}}function xn(v,E){if(!v||!v.text||E-v.at>=300000)return"";let A=v.build.split("-").pop()??"";if(v.reason==="build"&&A)return h("hub.restarting.build",v.text,{build:A});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function At(v){if(v==="connected")Z.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&xn(T.restarting,Date.now()))Z.setConnStatus(xn(T.restarting,Date.now()),"");else if(v==="reconnecting")Z.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")Z.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Z.setConnStatus("Connecting…","")}Lt(()=>{At(T.getState()),W.textContent=h("gpui.improvements","Improvements"),pe.title=h("palette.settings","Settings"),pe.setAttribute("aria-label",h("palette.settings","Settings")),R(),Z.refreshLocale(),Ce.refreshLocale(),oe.refreshLocale(),Ge.render(),qe.refreshLocale(),Oe.refreshLocale()}),T.onState((v,E)=>{if(v==="connected"&&E){if(E.locale)Mn(E.locale);if(E.theme)Yi(E.theme);if(E.name)Z.setHostName(E.name);if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();At(v);let A=typeof E.hubBack==="string"?String(E.hubBack):"";if(A)try{let P=JSON.parse(A);if(P.reason==="crash")Z.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>At(T.getState()),6000)}catch{}if(oe.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(E.commands))me=E.commands,oe.setCommands(me);else me=[];Le(),Oe.reconcile()}else nt.cancel(),At(v)}),T.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let E=v;if(E.k==="clone"||E.k==="clone.repos"||E.k==="clone.signin"){Oe.handleFrame(E);return}switch(E.k){case"project":{let A=E.project;if(!A)break;let P=x.findIndex((V)=>V.id===A.id);if(P>=0)x[P]=A;else x.unshift(A);Z.setData(x,C,I,G),R(),ge();break}case"thread":{let A=E.thread;if(!A)break;let P=C.findIndex((V)=>V.id===A.id);if(P>=0)C[P]=A;else C.unshift(A);if(Z.setData(x,C,I,G),A.id===N)Ce.updateThreadMeta(A),R(),oe.setState(!0,A.state==="working");ge();break}case"thread.removed":{let A=String(E.id??"");C=C.filter((P)=>P.id!==A),Z.setData(x,C,I,G),ge();break}case"entry":{if(E.thread===N&&E.entry)Ce.upsertEntry(E.entry);break}case"text":{if(E.thread===N)Ce.appendLiveText(String(E.entry??""),String(E.append??""),Number(E.at??Date.now()));break}case"turn":{if(E.thread===N){let A=String(E.state??"idle");oe.setState(!0,A==="working"),F(N,Y)}ge();break}case"btw":{if(E.thread===N)Ce.showBtw(String(E.q??""),String(E.a??""));break}case"unanswered":{if(E.thread===N)Ce.setUnanswered(E.unanswered??null);break}case"theme":{if(typeof E.theme==="string")Yi(E.theme);break}case"home":{if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let E=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(E==="k"||v.shiftKey&&E==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Oe.isOpen())Oe.escape();else if(qe.isOpen())qe.close();else if(Ce.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Xi);else Xi(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index fcb36b6c69..617cab83dc 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var F={en:{"agy.signout":"Sign out","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.verify":"Verify","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.verify":"Verificar","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.verify":"検証","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var G=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(F.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=G}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==G;if(G=s,Y(),r)for(let d of W)d(G);return r}function c(a,t,s){let d=(F[G]||F.en||{})[a]??F.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],I=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(I[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)I[t]=I[t-255]}function J(a,t){return a===0||t===0?0:I[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-o*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,E]=s,w=d-u*f,g=[],S=(e,o)=>{for(let n=o-1;n>=0;n--)g.push(e>>>n&1)};S(4,4),S(t.length,8);for(let e of t)S(e,8);for(let e=0;e<4&&g.length{if(e<0||o<0||e>=p||o>=p)return;z[e*p+o]=n?1:0,A[e*p+o]=1},P=(e,o)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=o+m,i=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,i)}};P(0,0),P(0,p-7),P(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let o=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let i=(m+l&1)===0?h^1:h;z[m*p+l]=i}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(R>>>14-e&1)===1);return{size:p,modules:z}}function X(a){let t=ie(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let i=h.startsWith("https://")?h:`https://${h}`;if(!i.startsWith("https://")||i.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=i,y.setAttribute("data-testid","pair-address");let N=document.createElement("button");N.type="button",N.className="bp-pair-copy";let H=c("common.copy","Copy");N.textContent=H,N.addEventListener("click",()=>{navigator.clipboard?.writeText(i).then(()=>{N.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{N.textContent=H},1200)}).catch(()=>{})}),x.append(v,y,N);let U=document.createDocumentFragment();U.appendChild(x);let K=X(i);if(K){let O=document.createElement("div");O.className="bp-pair-qr",O.setAttribute("data-testid","pair-qr"),O.appendChild(K),U.appendChild(O)}p.replaceChildren(U),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")z(h.address)}).catch(()=>{}),t.append(s,u,f,S,C,p),a.appendChild(t);let A=null,b=null,P=null,j=0,D=0,R=150,e=1000;function o(){if(j++,P)P.abort(),P=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){o(),f.classList.remove("bp-hidden"),S.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;P=h;try{let i=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,i.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(i.status===200||i.status===204){let v={};if(i.status===200)try{v=await i.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(i.status===204||v.approved===!0||y==="approved"||y==="ok"){o(),C.textContent=c("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(l)},150);return}if(i.status===429){let v=Number(i.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(i.status===401||i.status===403||i.status===404||i.status===410){let v="";try{let y=await i.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||i.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let i=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},i)}finally{if(P===h)P=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,C.textContent=c("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let i=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!i.ok){let H=c("web.pair.failed","Pairing request failed ({status})",{status:i.status});try{let U=await i.json();if(U.error)H=U.error}catch{}if(i.status===429)H=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(H,!0);return}let x=await i.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),o();let N=j;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),S.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(N)},R)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); +var F={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var G=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(F.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=G}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==G;if(G=s,Y(),r)for(let d of W)d(G);return r}function c(a,t,s){let d=(F[G]||F.en||{})[a]??F.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],I=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(I[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)I[t]=I[t-255]}function J(a,t){return a===0||t===0?0:I[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,E]=s,w=d-u*f,g=[],S=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};S(4,4),S(t.length,8);for(let e of t)S(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;z[e*p+i]=n?1:0,C[e*p+i]=1},R=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};R(0,0),R(0,p-7),R(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let o=(m+l&1)===0?h^1:h;z[m*p+l]=o}}}let P=30660;for(let e=0;e<=5;e++)b(8,e,(P>>>14-e&1)===1);b(8,7,(P>>>8&1)===1),b(8,8,(P>>>7&1)===1),b(7,8,(P>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(P>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(P>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(P>>>14-e&1)===1);return{size:p,modules:z}}function X(a){let t=oe(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let N=document.createElement("button");N.type="button",N.className="bp-pair-copy";let H=c("common.copy","Copy");N.textContent=H,N.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{N.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{N.textContent=H},1200)}).catch(()=>{})}),x.append(v,y,N);let U=document.createDocumentFragment();U.appendChild(x);let K=X(o);if(K){let O=document.createElement("div");O.className="bp-pair-qr",O.setAttribute("data-testid","pair-qr"),O.appendChild(K),U.appendChild(O)}p.replaceChildren(U),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")z(h.address)}).catch(()=>{}),t.append(s,u,f,S,A,p),a.appendChild(t);let C=null,b=null,R=null,j=0,D=0,P=150,e=1000;function i(){if(j++,R)R.abort(),R=null;if(C!==null)window.clearTimeout(C),C=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),S.classList.add("bp-hidden"),g.disabled=!1,A.textContent=l,A.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;R=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,o.status===202){C=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),A.textContent=c("web.pair.approved","Approved. Opening Backplane…"),A.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}C=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);C=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||o.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},o)}finally{if(R===h)R=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,A.textContent=c("web.pair.requesting","Requesting pairing code…"),A.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let H=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let U=await o.json();if(U.error)H=U.error}catch{}if(o.status===429)H=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(H,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let N=j;e=1000,P=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),S.classList.remove("bp-hidden"),A.textContent="",m(),b=window.setInterval(m,1000),C=window.setTimeout(()=>{k(N)},P)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); diff --git a/web/dist/assets/style.css b/web/dist/assets/style.css index a6aa36e38b..509b880c8a 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -815,6 +815,10 @@ html.light .bp-code-block { background: var(--panel); } .bp-mgmt-close { width: 28px; height: 28px; flex-shrink: 0; color: var(--dim); } .bp-mgmt-panel { width: 370px; + max-width: 100%; + min-width: 0; + overflow: hidden; + box-sizing: border-box; flex-shrink: 0; display: flex; flex-direction: column; @@ -1761,6 +1765,220 @@ button.primary.bp-send-btn.is-plan-exec { color: var(--faint); flex-shrink: 0; } +.bp-mgmt-panel.bp-plan-expanded { + width: min(720px, 100%); + max-width: 100%; + flex-shrink: 1; + min-width: 0; +} +.bp-right-area:has(.bp-mgmt-panel.bp-plan-expanded), +.bp-right-area.bp-has-viewer.bp-has-mgmt:has(.bp-mgmt-panel.bp-plan-expanded) { + width: 68%; +} +.bp-plan-err .bp-mgmt-flex1 { + white-space: normal; + overflow-wrap: anywhere; + text-overflow: clip; +} +.bp-plan-viewbar, +.bp-plan-layerbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + padding: 4px 8px; + background: var(--panel); + border-bottom: 1px solid var(--rule); + flex-shrink: 0; + font-size: 11px; +} +.bp-plan-layerbar { + background: var(--bg); + font-size: 10px; +} +.bp-plan-sep { + width: 1px; + height: 12px; + background: var(--line); + margin: 0 2px; +} +.bp-plan-inspector { + display: flex; + flex-direction: column; + gap: 5px; + padding: 6px 8px; + background: var(--panel); + border-bottom: 1px solid var(--rule); + flex-shrink: 0; + font-size: 11px; +} +.bp-plan-ins-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 5px; +} +.bp-plan-ins-sw { + width: 10px; + height: 10px; + flex-shrink: 0; +} +.bp-plan-ins-pill { + padding: 1px 4px; + border: 1px solid var(--line); + font-size: 10px; + color: var(--dim); +} +.bp-plan-ins-pill.warn { + border-color: var(--warn); + color: var(--warn); +} +.bp-plan-ins-val { + padding: 0 4px; + font-family: var(--mono); + color: var(--text); +} +.bp-plan-note-form { + display: flex; + align-items: center; + gap: 4px; +} +.bp-plan-note-input { + flex: 1; + min-width: 0; + padding: 3px 6px; + background: var(--bg); + border: 1px solid var(--line); + color: var(--text); + font-size: 11px; +} +.bp-plan-hint { + font-size: 10px; + color: var(--faint); +} +.bp-plan-canvas-scroll { + flex: 1 1 0%; + min-height: 240px; + overflow-y: auto; + background: var(--bg); +} +.bp-plan-canvas-grid { + display: grid; + grid-template-columns: 1fr; + gap: 8px; + padding: 6px; + outline: none; +} +.bp-plan-canvas-grid.two-cols { + grid-template-columns: 1fr 1fr; + align-items: start; +} +.bp-plan-card { + display: flex; + flex-direction: column; + border: 1px solid var(--line); + background: var(--panel); + min-width: 0; +} +.bp-plan-card-head { + display: flex; + flex-direction: column; + gap: 2px; + padding: 5px 8px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} +.bp-plan-card-head-top { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.bp-plan-card-bar { + width: 3px; + height: 14px; + flex-shrink: 0; +} +.bp-plan-card-bar.sig { background: var(--accent); } +.bp-plan-card-bar.pwr { background: var(--warn); } +.bp-plan-card-title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 700; + font-size: 12px; + color: var(--text); +} +.bp-plan-card-sub { + font-size: 10px; + color: var(--dim); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.bp-plan-mini-btn { + padding: 1px 6px; + font-size: 10px; +} +.bp-plan-card-canvas-wrap { + position: relative; + width: 100%; + background: #111917; + overflow: hidden; +} +.bp-plan-card-canvas { + display: block; + width: 100%; + touch-action: none; +} +.bp-plan-hover-hud { + position: absolute; + top: 8px; + right: 8px; + padding: 2px 6px; + background: rgba(17, 25, 23, 0.94); + border: 1px solid #526b61; + color: #eef5f2; + font-family: var(--mono); + font-size: 10px; + pointer-events: none; +} +.bp-plan-legend { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 5px; + padding: 5px 8px; + background: var(--panel); + border-top: 1px solid var(--line); +} +.bp-plan-legend-chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 5px; + background: var(--bg); + border: 1px solid var(--line); + color: var(--dim); + font-family: var(--mono); + font-size: 10px; + cursor: pointer; +} +.bp-plan-legend-chip:hover { background: var(--raise); color: var(--text); } +.bp-plan-legend-chip.active { border-color: var(--accent); background: var(--raise); color: var(--text); } +.bp-plan-legend-sw { + width: 8px; + height: 8px; + flex-shrink: 0; +} +.bp-plan-split-list { + flex: 0 0 155px; + min-height: 110px; + border-top: 1px solid var(--rule); + overflow-y: auto; +} /* Web viewer pane + 1440 / 820 / 390 px responsive styles. diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 80ccf6dcc4..cdab82f165 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,9 +1,10 @@ { "version": 1, - "totalAssetGzipBytes": 188137, + "totalAssetGzipBytes": 200377, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", + "android.hub.machines.approve", "android.load.earlier", "approval.dismiss", "approval.implement", @@ -64,16 +65,29 @@ "gpui.mgmt.fab.use", "gpui.mgmt.life.nopart", "gpui.mgmt.life.reading", + "gpui.mgmt.plan.addnote", "gpui.mgmt.plan.all", "gpui.mgmt.plan.before", + "gpui.mgmt.plan.compact", "gpui.mgmt.plan.done", "gpui.mgmt.plan.drawn", + "gpui.mgmt.plan.edited", "gpui.mgmt.plan.elsewhere", "gpui.mgmt.plan.emptysub", + "gpui.mgmt.plan.expand", + "gpui.mgmt.plan.fit", + "gpui.mgmt.plan.grid.all", + "gpui.mgmt.plan.grid.pair", + "gpui.mgmt.plan.grid.single", "gpui.mgmt.plan.hide", + "gpui.mgmt.plan.hint", "gpui.mgmt.plan.keysnote", "gpui.mgmt.plan.layer", + "gpui.mgmt.plan.layer.move", + "gpui.mgmt.plan.lock", + "gpui.mgmt.plan.locked", "gpui.mgmt.plan.noboard", + "gpui.mgmt.plan.note.placeholder", "gpui.mgmt.plan.nothing", "gpui.mgmt.plan.offwords", "gpui.mgmt.plan.onwords", @@ -81,6 +95,7 @@ "gpui.mgmt.plan.reference", "gpui.mgmt.plan.refused", "gpui.mgmt.plan.reject", + "gpui.mgmt.plan.rejectlayer", "gpui.mgmt.plan.reqplain", "gpui.mgmt.plan.requested", "gpui.mgmt.plan.saved", @@ -96,8 +111,14 @@ "gpui.mgmt.plan.st.verified", "gpui.mgmt.plan.stackup", "gpui.mgmt.plan.stop", + "gpui.mgmt.plan.sync", "gpui.mgmt.plan.tab", + "gpui.mgmt.plan.unlock", "gpui.mgmt.plan.verify", + "gpui.mgmt.plan.view.canvas", + "gpui.mgmt.plan.view.list", + "gpui.mgmt.plan.view.split", + "gpui.mgmt.plan.width", "gpui.next.thread", "gpui.nothing.matches", "gpui.planmode.bar.always", @@ -244,7 +265,7 @@ "web.plan.net.one", "web.plan.nets" ], - "i18nSubsetSha256": "255f3188e4d8738ee228c38305a13aeaef637f6fb713e7f5a6f37e900972d2e2", + "i18nSubsetSha256": "b079c983cf999a76abef7087f76178a3d7e8417a3eba3bdfaaabcefbb194ee64", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", "web/src/app.ts": "89f69e24aaafeea13d4ec613ac7743a665870ea3b0e238a7f28134f209f2180c", @@ -257,16 +278,17 @@ "web/src/inflate.ts": "bc10ed23159668193d6de6d582e60baf009cae0a619018f0588f836a77dde831", "web/src/logout.ts": "9d29482c4671deee1e868ee477b123e067a4c22f7d8ac30b4c2420cf71b8ebe2", "web/src/md.ts": "c606d1ec598b3ce132c7cc9366383dacafc3fcb71c0fccd97b41ec0e19a96c78", - "web/src/mgmt-model.ts": "6eb90e8ac49d7e897207271377e089aed176b6721f569cc60aea6ed88d7543a6", - "web/src/mgmt.ts": "eb20231f133c3fa106352f35f7082af0fbc56bc39504b41b28f12df8ab59d897", + "web/src/mgmt-model.ts": "5135cce33f870d5b45b9fd8c2eb91f62fa7d274cd961cd523ed0df599893c955", + "web/src/mgmt.ts": "c28da4e358ddc0ae1854e7343fb33cdcc89c953f2537ee4a5fee111f687d76fe", "web/src/pair.html": "cf7b94703316f910718356e9ff8e99e088b68211db39b5200213b623c9275f6e", "web/src/pair.ts": "af07d19224043f8176f8cd2298d00b6806248eee453fd2f287c183e71a08179b", "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", + "web/src/plan-canvas.ts": "be46faf9e3207600516dfac12d93ba6cf8798ba65615a3eb24ff3dfacc0f8507", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "7b4d8be26fabc6c2a0b8af94a64572a0e3c1e589bf079bfa58c8985a8acd984a", - "web/src/shell.css": "081eb8f1641c6ee2b1f3e5daaea06bfecd1e5110857ae7c8cb14f4a58871e3d5", + "web/src/shell.css": "a91f0817a8cc922d1ca268ab51c8acff67631a14b255a3abcba9fcd08d8466c3", "web/src/sidebar.ts": "0c326c895375f8a2718ec424b07ca59006d7bc0938f05fe8e3e231ffb6af375f", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", @@ -295,9 +317,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 293973, - "gzipBytes": 82954, - "sha256": "0a6e221533ada874600539687579b4f456fbd87de9eda2b246cc22e4c7740613" + "bytes": 332727, + "gzipBytes": 93791, + "sha256": "7239bcb9bef8033954fc9426efff1938728f548e8bef177a26496f154e9d3e76" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -315,14 +337,14 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 47833, - "gzipBytes": 14860, - "sha256": "428e9b0951e440ff175eaa47a6f13515b3f23b83aff69aa4e165c8f46d9c57ce" + "bytes": 50565, + "gzipBytes": 15659, + "sha256": "d89386a3e4f69e4c0754e6f72072bb80dbeb55eb125e5c516fc9bef9b4ac6e7d" }, "assets/style.css": { - "bytes": 67975, - "gzipBytes": 12024, - "sha256": "0310fbb55ab0c8984abdf9ea149c2605660398c2f7f2bac5ff5c3d80f3fa1df2" + "bytes": 72271, + "gzipBytes": 12628, + "sha256": "1a865f0f2abc656317668c30671ff4a688b7af931f04a6725d4aa225a6d0c6ad" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/mgmt-model.ts b/web/src/mgmt-model.ts index 6d3edc9a9c..4b624a654f 100644 --- a/web/src/mgmt-model.ts +++ b/web/src/mgmt-model.ts @@ -121,10 +121,76 @@ export interface PlanItem { impedance?: string | null; problems?: number; problem_text?: string; + edited?: boolean; + order?: number; + priority?: number; + from?: string[]; + to?: string[]; +} + +export interface PlanPartBox { + r: string; + s: "F" | "B" | string; + b: [number, number, number, number]; + o: boolean; +} + +export interface PlanCopperLayer { + layer: string; + index: number; + role: string; + alias?: string; + title?: string; + subtitle?: string; +} + +export interface PlanBoardGeom { + bbox: [number, number, number, number]; + outline: Array>; + parts: PlanPartBox[]; +} + +export interface PlanBand { + id: string; + layer: string; + width?: number; + path?: Array<[number, number]>; + state?: string; + color?: string; + nets?: number; + vias?: Array<[number, number]>; + name?: string; + group?: string; + locked?: boolean; + edited?: boolean; + order?: number; + from?: string[]; + to?: string[]; + impedance?: string | null; + guides?: Array<[number, number, number, number]>; + problem_text?: string; +} + +export interface PlanRegion { + id: string; + layer: string; + net?: string; + outline?: Array<[number, number]>; + holes?: Array>; + state?: string; + color?: string; + locked?: boolean; + edited?: boolean; + reference?: string; + priority?: number; + problem_text?: string; } export interface PlanLayer { layer: string; + index?: number; + title?: string; + subtitle?: string; role?: string; stackup?: string; status?: string; @@ -154,11 +220,36 @@ export interface PlanInfo { impedances?: string[]; asks?: Array<{ id?: string; what?: string; note?: string }>; elsewhere?: Array<{ pcb?: string; rel?: string; name?: string }>; - draw?: { bands?: unknown[]; regions?: unknown[] }; + board?: PlanBoardGeom; + board_trimmed?: boolean; + copper_layers?: PlanCopperLayer[]; + notes?: Array<{ id?: string; text?: string; by?: string }>; + constraints?: unknown; + draw?: { bands?: PlanBand[]; regions?: PlanRegion[] }; keys_note?: string; layers?: PlanLayer[]; } +export interface PlanCamera { + cx: number; + cy: number; + scale: number; + fitted: number; + touched: boolean; +} + +export type PlanHit = + | { kind: "vertex"; id: string; isPlane: boolean; idx: number } + | { kind: "midpoint"; id: string; isPlane: boolean; segIdx: number; pos: [number, number] } + | { kind: "band"; id: string } + | { kind: "region"; id: string }; + +export interface PlanPlacedLabel { + text: string; + cx: number; + cy: number; +} + export interface FabLimitSide { text?: string; source?: string; @@ -481,3 +572,305 @@ export function isChecksFixCurrent(start: ChecksFixSnapshot, now: ChecksFixSnaps start.threadGen === now.threadGen ); } + +// ---- Interactive Floorplanner Canvas pure helpers ---- + +const PLAN_RAIL_PALETTE = [ + "#f59e0b", "#38bdf8", "#c084fc", "#2dd4bf", "#ef4444", "#a3e635", "#f97316", "#ec4899", +]; +const PLAN_BUS_PALETTE = [ + "#14b8a6", "#f59e0b", "#c084fc", "#22c55e", "#38bdf8", "#ef4444", "#e879f9", "#84cc16", +]; + +function fnv1aHash(s: string): number { + let h = 2166136261; + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 16777619) >>> 0; + } + return h; +} + +export function planRailColor(net: string, fallback = ""): string { + const low = fallback.trim().toLowerCase(); + if (low && low !== "#5a7a9a" && low !== "#8a8a8a") return fallback; + const up = net.toUpperCase(); + if (up.includes("3V3A") || up.includes("AVDD") || up.includes("VDDA")) return "#38bdf8"; + if (up.includes("1V8") || up.includes("1.8V")) return "#c084fc"; + if (up.includes("2V5") || up.includes("2.5V")) return "#a3e635"; + if (up.includes("3V3") || up.includes("3.3V") || up.includes("VCC")) return "#f59e0b"; + if (up.includes("5V") || up.startsWith("+5")) return "#ef4444"; + if (up.includes("12V") || up.includes("24V")) return "#f97316"; + if (up.includes("VBAT") || up.includes("VIN")) return "#ec4899"; + if (up.includes("GND")) return "#2dd4bf"; + return PLAN_RAIL_PALETTE[fnv1aHash(up) % PLAN_RAIL_PALETTE.length]; +} + +export function planBusColor(name: string, fallback = ""): string { + const low = fallback.trim().toLowerCase(); + if (low && low !== "#8a8a8a") return fallback; + return PLAN_BUS_PALETTE[fnv1aHash(name) % PLAN_BUS_PALETTE.length]; +} + +export function planFitCamera(bbox: [number, number, number, number], w: number, h: number, pad = 14): PlanCamera { + const bw = Math.max(1, Math.abs(bbox[2] - bbox[0])); + const bh = Math.max(1, Math.abs(bbox[3] - bbox[1])); + const uw = Math.max(20, w - pad * 2); + const uh = Math.max(20, h - pad * 2); + const scale = Math.max(0.05, Math.min(200, Math.min(uw / bw, uh / bh))); + return { + cx: (bbox[0] + bbox[2]) * 0.5, + cy: (bbox[1] + bbox[3]) * 0.5, + scale, + fitted: scale, + touched: false, + }; +} + +export function planWorldToPx(cam: PlanCamera, x: number, y: number, w: number, h: number): [number, number] { + return [w * 0.5 + (x - cam.cx) * cam.scale, h * 0.5 + (y - cam.cy) * cam.scale]; +} + +export function planPxToWorld(cam: PlanCamera, pxX: number, pxY: number, w: number, h: number): [number, number] { + const s = Math.max(1e-4, cam.scale); + return [cam.cx + (pxX - w * 0.5) / s, cam.cy + (pxY - h * 0.5) / s]; +} + +export function planPanCamera(cam: PlanCamera, dxPx: number, dyPx: number): PlanCamera { + const s = Math.max(1e-4, cam.scale); + return { ...cam, cx: cam.cx - dxPx / s, cy: cam.cy - dyPx / s, touched: true }; +} + +export function planZoomCamera(cam: PlanCamera, factor: number, mx: number, my: number, w: number, h: number): PlanCamera { + const minS = Math.max(0.02, cam.fitted * 0.35); + const maxS = Math.max(40, cam.fitted * 24); + const ns = Math.max(minS, Math.min(maxS, cam.scale * factor)); + const [wx, wy] = planPxToWorld(cam, mx, my, w, h); + return { + ...cam, + cx: wx - (mx - w * 0.5) / ns, + cy: wy - (my - h * 0.5) / ns, + scale: ns, + touched: true, + }; +} + +export function planPolylineMidpoint(pts: Array<[number, number]>): [number, number] | null { + if (pts.length === 0) return null; + if (pts.length === 1) return pts[0]; + let total = 0; + for (let i = 0; i + 1 < pts.length; i++) { + total += Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); + } + if (total < 1e-6) return pts[0]; + const target = total * 0.5; + let acc = 0; + for (let i = 0; i + 1 < pts.length; i++) { + const segLen = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]); + if (acc + segLen >= target && segLen > 1e-9) { + const t = (target - acc) / segLen; + return [ + pts[i][0] + (pts[i + 1][0] - pts[i][0]) * t, + pts[i][1] + (pts[i + 1][1] - pts[i][1]) * t, + ]; + } + acc += segLen; + } + return pts[pts.length - 1]; +} + +export function planInsertVertex( + pts: Array<[number, number]>, + segIdx: number, + pos: [number, number], + closed: boolean, +): Array<[number, number]> { + const out = pts.map((p) => [p[0], p[1]] as [number, number]); + if (out.length === 0) return [pos]; + const at = closed && segIdx + 1 >= out.length ? out.length : Math.min(segIdx + 1, out.length); + out.splice(at, 0, [pos[0], pos[1]]); + return out; +} + +export function planRemoveVertex( + pts: Array<[number, number]>, + idx: number, + closed: boolean, +): Array<[number, number]> | null { + const minPts = closed ? 3 : 2; + if (pts.length <= minPts || idx < 0 || idx >= pts.length) return null; + const out = pts.map((p) => [p[0], p[1]] as [number, number]); + out.splice(idx, 1); + return out; +} + +function distToSegSq(px: number, py: number, ax: number, ay: number, bx: number, by: number): number { + const dx = bx - ax; + const dy = by - ay; + const lenSq = dx * dx + dy * dy; + if (lenSq < 1e-6) return (px - ax) * (px - ax) + (py - ay) * (py - ay); + const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lenSq)); + const cx = ax + t * dx; + const cy = ay + t * dy; + return (px - cx) * (px - cx) + (py - cy) * (py - cy); +} + +function pointInRing(x: number, y: number, ring: Array<[number, number]>): boolean { + if (ring.length < 3) return false; + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, yi] = ring[i]; + const [xj, yj] = ring[j]; + const intersect = (yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi + 1e-12) + xi; + if (intersect) inside = !inside; + } + return inside; +} + +export function planBandStrokePx(widthMm: number, scale: number): number { + return Math.max(5, Math.min(32, widthMm * scale)); +} + +export function planHitTest( + bands: PlanBand[], + regions: PlanRegion[], + layer: string, + selectedId: string, + cam: PlanCamera, + w: number, + h: number, + mx: number, + my: number, +): PlanHit | null { + if (selectedId) { + for (const b of bands) { + if (b.layer !== layer || b.id !== selectedId || b.locked) continue; + const pts = b.path ?? []; + for (let i = 0; i < pts.length; i++) { + const [vx, vy] = planWorldToPx(cam, pts[i][0], pts[i][1], w, h); + if (Math.hypot(mx - vx, my - vy) <= 9.5) return { kind: "vertex", id: selectedId, isPlane: false, idx: i }; + } + for (let i = 0; i + 1 < pts.length; i++) { + const mid: [number, number] = [(pts[i][0] + pts[i + 1][0]) * 0.5, (pts[i][1] + pts[i + 1][1]) * 0.5]; + const [hx, hy] = planWorldToPx(cam, mid[0], mid[1], w, h); + if (Math.hypot(mx - hx, my - hy) <= 8.5) return { kind: "midpoint", id: selectedId, isPlane: false, segIdx: i, pos: mid }; + } + } + for (const r of regions) { + if (r.layer !== layer || r.id !== selectedId || r.locked) continue; + const pts = r.outline ?? []; + for (let i = 0; i < pts.length; i++) { + const [vx, vy] = planWorldToPx(cam, pts[i][0], pts[i][1], w, h); + if (Math.hypot(mx - vx, my - vy) <= 9.5) return { kind: "vertex", id: selectedId, isPlane: true, idx: i }; + } + if (pts.length >= 3) { + for (let i = 0; i < pts.length; i++) { + const a = pts[i]; + const b = pts[(i + 1) % pts.length]; + const mid: [number, number] = [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]; + const [hx, hy] = planWorldToPx(cam, mid[0], mid[1], w, h); + if (Math.hypot(mx - hx, my - hy) <= 8.5) return { kind: "midpoint", id: selectedId, isPlane: true, segIdx: i, pos: mid }; + } + } + } + } + + let bestBand: { dist: number; id: string } | null = null; + for (const b of bands) { + if (b.layer !== layer) continue; + const pts = b.path ?? []; + if (pts.length < 2) continue; + const thresh = Math.max(7, planBandStrokePx(b.width ?? 1.5, cam.scale) * 0.5 + 3); + let minD2 = Number.POSITIVE_INFINITY; + for (let i = 0; i + 1 < pts.length; i++) { + const [ax, ay] = planWorldToPx(cam, pts[i][0], pts[i][1], w, h); + const [bx, by] = planWorldToPx(cam, pts[i + 1][0], pts[i + 1][1], w, h); + minD2 = Math.min(minD2, distToSegSq(mx, my, ax, ay, bx, by)); + } + const dist = Math.sqrt(minD2); + if (dist <= thresh && (!bestBand || dist <= bestBand.dist)) { + bestBand = { dist, id: b.id }; + } + } + if (bestBand) return { kind: "band", id: bestBand.id }; + + const [wx, wy] = planPxToWorld(cam, mx, my, w, h); + for (let i = regions.length - 1; i >= 0; i--) { + const r = regions[i]; + if (r.layer !== layer) continue; + const outer = r.outline ?? []; + if (!pointInRing(wx, wy, outer)) continue; + const inHole = (r.holes ?? []).some((hRing) => pointInRing(wx, wy, hRing)); + if (!inHole) return { kind: "region", id: r.id }; + } + return null; +} + +export function planDefaultLayerPair(layers: PlanLayer[]): string[] { + let bestSig: { count: number; layer: string } | null = null; + let bestPwr: { count: number; layer: string } | null = null; + const allNames: string[] = []; + for (const l of layers) { + if (!l.layer) continue; + allNames.push(l.layer); + const items = l.items ?? []; + const corN = items.filter((it) => it.kind === "corridor").length; + const plnN = items.filter((it) => it.kind === "plane").length; + if ((corN > 0 || l.role === "signal") && (!bestSig || corN > bestSig.count)) { + bestSig = { count: corN, layer: l.layer }; + } + if ((plnN > 0 || l.role === "power" || l.role === "plane") && (!bestPwr || plnN > bestPwr.count)) { + bestPwr = { count: plnN, layer: l.layer }; + } + } + const out: string[] = []; + if (bestSig) out.push(bestSig.layer); + if (bestPwr && !out.includes(bestPwr.layer)) out.push(bestPwr.layer); + for (const name of allNames) { + if (out.length >= 2) break; + if (!out.includes(name)) out.push(name); + } + return out; +} + +export function planLayoutLabels( + parts: PlanPartBox[], + cam: PlanCamera, + w: number, + h: number, + pinned: string[], +): PlanPlacedLabel[] { + const pinSet = new Set(pinned); + const cands: Array<{ text: string; cx: number; cy: number; bw: number; bh: number; score: number }> = []; + for (const p of parts) { + if (!p.r || !p.b || p.b.length !== 4) continue; + const [x0, y0] = planWorldToPx(cam, p.b[0], p.b[1], w, h); + const [x1, y1] = planWorldToPx(cam, p.b[2], p.b[3], w, h); + const pw = Math.abs(x1 - x0); + const ph = Math.abs(y1 - y0); + if (pw < 13 || ph < 9) continue; + const cx = (x0 + x1) * 0.5; + const cy = (y0 + y1) * 0.5; + if (cx < 8 || cx > w - 8 || cy < 8 || cy > h - 8) continue; + cands.push({ + text: p.r, + cx, + cy, + bw: p.r.length * 5.8 + 4, + bh: 11, + score: pw * ph + (pinSet.has(p.r) ? 10000 : 0), + }); + } + cands.sort((a, b) => b.score - a.score); + const placedBoxes: Array<[number, number, number, number]> = []; + const out: PlanPlacedLabel[] = []; + for (const c of cands) { + const rect: [number, number, number, number] = [c.cx - c.bw * 0.5, c.cy - c.bh * 0.5, c.cx + c.bw * 0.5, c.cy + c.bh * 0.5]; + const overlaps = placedBoxes.some((o) => !(rect[2] <= o[0] || rect[0] >= o[2] || rect[3] <= o[1] || rect[1] >= o[3])); + if (!overlaps) { + placedBoxes.push(rect); + out.push({ text: c.text, cx: c.cx, cy: c.cy }); + } + } + return out; +} diff --git a/web/src/mgmt.ts b/web/src/mgmt.ts index 4d7172f63a..2f2ecefa45 100644 --- a/web/src/mgmt.ts +++ b/web/src/mgmt.ts @@ -17,9 +17,12 @@ import { mgmtPanelsOf, money, pkgName, + planBusColor, + planDefaultLayerPair, planDone, planMark, planProgressSegments, + planRailColor, planStatusBadge, refsFit, stockSummary, @@ -33,8 +36,14 @@ import { type FabInfo, type LifeInfo, type MgmtStateInfo, + type PlanBand, + type PlanBoardGeom, type PlanInfo, + type PlanItem, + type PlanLayer, + type PlanRegion, } from "./mgmt-model"; +import { PlanFloorplannerCanvas, type PlanGridMode, type PlanViewMode } from "./plan-canvas"; import type { HubClient } from "./ws"; export interface MgmtCallbacks { @@ -80,6 +89,18 @@ export class MgmtStrip { private planStatus = ""; private planSelectedId = ""; private planStackupOpen = false; + private planViewMode: PlanViewMode = "split"; + private planGridMode: PlanGridMode = "pair"; + private planSyncZoom = true; + private planExpanded = false; + private planShownLayers: string[] = []; + private planOptimistic = new Map>(); + private planOptimisticRev: number | undefined = undefined; + private planHydratedKey = ""; + private planHydratedBoard: PlanBoardGeom | null = null; + private planHydratedDraw: { bands?: PlanBand[]; regions?: PlanRegion[] } | null = null; + private planNoteOpen = false; + private planCanvas: PlanFloorplannerCanvas | null = null; private fabStatus = ""; @@ -138,6 +159,15 @@ export class MgmtStrip { this.planStatus = ""; this.planSelectedId = ""; this.planStackupOpen = false; + this.planShownLayers = []; + this.planOptimistic.clear(); + this.planOptimisticRev = undefined; + this.planHydratedKey = ""; + this.planHydratedBoard = null; + this.planHydratedDraw = null; + this.planNoteOpen = false; + this.planCanvas?.destroy(); + this.planCanvas = null; this.fabStatus = ""; this.render(); } @@ -168,6 +198,15 @@ export class MgmtStrip { this.planStatus = ""; this.planSelectedId = ""; this.planStackupOpen = false; + this.planShownLayers = []; + this.planOptimistic.clear(); + this.planOptimisticRev = undefined; + this.planHydratedKey = ""; + this.planHydratedBoard = null; + this.planHydratedDraw = null; + this.planNoteOpen = false; + this.planCanvas?.destroy(); + this.planCanvas = null; this.fabStatus = ""; this.lifeSelectedKey = ""; this.lifePartSamples = null; @@ -257,6 +296,9 @@ export class MgmtStrip { const state = this.getStateInfo(); const tabs = mgmtPanelsOf(state); if (!this.digest || tabs.length === 0) { + this.planCanvas?.destroy(); + this.planCanvas = null; + this.panelEl.classList.remove("bp-plan-expanded"); this.stripEl.classList.add("bp-hidden"); this.panelEl.classList.add("bp-hidden"); this.panelEl.removeAttribute("data-testid"); @@ -313,6 +355,9 @@ export class MgmtStrip { // 2. Render active panel body if (!this.openPanel) { + this.planCanvas?.destroy(); + this.planCanvas = null; + this.panelEl.classList.remove("bp-plan-expanded"); this.panelEl.classList.add("bp-hidden"); this.panelEl.removeAttribute("data-testid"); this.panelEl.replaceChildren(); @@ -320,6 +365,13 @@ export class MgmtStrip { return; } + if (this.openPanel !== "plan") { + this.planCanvas?.destroy(); + this.planCanvas = null; + this.panelEl.classList.remove("bp-plan-expanded"); + } else { + this.panelEl.classList.toggle("bp-plan-expanded", this.planExpanded); + } this.panelEl.classList.remove("bp-hidden"); this.panelEl.setAttribute("data-testid", `mgmt-panel-${this.openPanel}`); this.cb.onOpenChange?.(true); @@ -934,11 +986,32 @@ export class MgmtStrip { void this.cb.hub.rpc(method, { pro: proj, ...params }) .catch((e) => { if (gen !== this.watchGen || proj !== this.project) return; + this.planOptimistic.clear(); this.planStatus = e instanceof Error ? e.message : t("gpui.mgmt.plan.refused", "KiCad refused"); this.render(); }); }; + if (d.revision !== this.planOptimisticRev) { + this.planOptimisticRev = d.revision; + this.planOptimistic.clear(); + } + + const hydKey = `${this.project}:${d.revision ?? 0}`; + if (d.board_trimmed && this.planHydratedKey !== hydKey && this.project) { + this.planHydratedKey = hydKey; + const gen = this.watchGen; + const proj = this.project; + void this.cb.hub.rpc<{ panel?: PlanInfo }>("plan.get", { pro: proj, board: true }) + .then((res) => { + if (gen !== this.watchGen || proj !== this.project || !res?.panel) return; + this.planHydratedBoard = res.panel.board ?? null; + this.planHydratedDraw = res.panel.draw ?? null; + this.render(); + }) + .catch(() => {}); + } + const toggleRow = document.createElement("div"); toggleRow.className = "bp-plan-toggle"; const on = d.on === true; @@ -1183,11 +1256,381 @@ export class MgmtStrip { wrap.appendChild(stackWrap); } + const mkChip = (label: string, active: boolean, testId: string, onClick: () => void): HTMLButtonElement => { + const b = document.createElement("button"); + b.type = "button"; + b.className = "bp-mgmt-btn bp-plan-chip-btn" + (active ? " active" : ""); + b.setAttribute("data-testid", testId); + b.setAttribute("aria-pressed", active ? "true" : "false"); + b.textContent = label; + b.addEventListener("click", onClick); + return b; + }; + + const viewBar = document.createElement("div"); + viewBar.className = "bp-plan-viewbar"; + viewBar.append( + mkChip(t("gpui.mgmt.plan.view.canvas", "Canvas"), this.planViewMode === "canvas", "mgmt-plan-view-canvas", () => { + this.planViewMode = "canvas"; + this.render(); + }), + mkChip(t("gpui.mgmt.plan.view.split", "Split"), this.planViewMode === "split", "mgmt-plan-view-split", () => { + this.planViewMode = "split"; + this.render(); + }), + mkChip(t("gpui.mgmt.plan.view.list", "List"), this.planViewMode === "list", "mgmt-plan-view-list", () => { + this.planViewMode = "list"; + this.render(); + }), + ); + if (this.planViewMode !== "list") { + const sep1 = document.createElement("span"); + sep1.className = "bp-plan-sep"; + const sep2 = document.createElement("span"); + sep2.className = "bp-plan-sep"; + const fitBtn = document.createElement("button"); + fitBtn.type = "button"; + fitBtn.className = "bp-mgmt-btn bp-plan-mini-btn"; + fitBtn.setAttribute("data-testid", "mgmt-plan-fit"); + fitBtn.textContent = t("gpui.mgmt.plan.fit", "Fit"); + fitBtn.addEventListener("click", () => this.planCanvas?.fitAll()); + + viewBar.append( + sep1, + mkChip(t("gpui.mgmt.plan.grid.pair", "Side by side"), this.planGridMode === "pair", "mgmt-plan-grid-pair", () => { + this.planGridMode = "pair"; + this.render(); + }), + mkChip(t("gpui.mgmt.plan.grid.all", "All layers"), this.planGridMode === "all", "mgmt-plan-grid-all", () => { + this.planGridMode = "all"; + this.render(); + }), + mkChip(t("gpui.mgmt.plan.grid.single", "Single"), this.planGridMode === "single", "mgmt-plan-grid-single", () => { + this.planGridMode = "single"; + this.render(); + }), + sep2, + mkChip(t("gpui.mgmt.plan.sync", "Link zoom"), this.planSyncZoom, "mgmt-plan-sync", () => { + this.planSyncZoom = !this.planSyncZoom; + this.render(); + }), + fitBtn, + ); + } + const viewSpacer = document.createElement("span"); + viewSpacer.className = "bp-mgmt-flex1"; + const expBtn = document.createElement("button"); + expBtn.type = "button"; + expBtn.className = "bp-mgmt-btn bp-plan-mini-btn"; + expBtn.setAttribute("data-testid", "mgmt-plan-expand"); + expBtn.textContent = this.planExpanded + ? t("gpui.mgmt.plan.compact", "Compact") + : t("gpui.mgmt.plan.expand", "Expand"); + expBtn.addEventListener("click", () => { + this.planExpanded = !this.planExpanded; + this.render(); + }); + viewBar.append(viewSpacer, expBtn); + wrap.appendChild(viewBar); + + const rawBoard: PlanBoardGeom = this.planHydratedKey === hydKey && this.planHydratedBoard + ? this.planHydratedBoard + : d.board ?? { bbox: [0, 0, 100, 70], outline: [], parts: [] }; + const rawDraw = this.planHydratedKey === hydKey && this.planHydratedDraw + ? this.planHydratedDraw + : d.draw ?? { bands: [], regions: [] }; + + const mergedBands: PlanBand[] = (rawDraw.bands ?? []).map((b) => { + const patch = this.planOptimistic.get(b.id); + if (!patch) return { ...b }; + return { + ...b, + ...patch, + edited: true, + state: b.state === "proposed" ? "edited" : b.state, + }; + }); + const mergedRegions: PlanRegion[] = (rawDraw.regions ?? []).map((r) => { + const patch = this.planOptimistic.get(r.id); + if (!patch) return { ...r }; + return { + ...r, + ...patch, + edited: true, + state: r.state === "proposed" ? "edited" : r.state, + }; + }); + + const movedItems: Array<{ target: string; item: PlanItem }> = []; + const mergedLayers: PlanLayer[] = (d.layers ?? []).map((l) => { + const kept: PlanItem[] = []; + for (const it of l.items ?? []) { + const patch = this.planOptimistic.get(it.id); + if (!patch) { + kept.push(it); + continue; + } + const next: PlanItem = { + ...it, + width: typeof patch.width === "number" ? patch.width : it.width, + locked: typeof patch.locked === "boolean" ? patch.locked : it.locked, + edited: true, + state: it.state === "proposed" ? "edited" : it.state, + }; + if (typeof patch.layer === "string" && patch.layer !== l.layer) { + movedItems.push({ target: patch.layer, item: next }); + } else { + kept.push(next); + } + } + return { ...l, items: kept }; + }); + for (const mv of movedItems) { + const targetLayer = mergedLayers.find((l) => l.layer === mv.target); + if (targetLayer) { + targetLayer.items = [...(targetLayer.items ?? []), mv.item]; + } + } + + const activeLayers = + this.planGridMode === "all" + ? mergedLayers.map((l) => l.layer) + : this.planGridMode === "single" + ? [ + this.planShownLayers.find((n) => mergedLayers.some((l) => l.layer === n)) ?? + planDefaultLayerPair(mergedLayers)[0] ?? + mergedLayers[0]?.layer ?? + "", + ].filter(Boolean) + : (this.planShownLayers.length > 0 && this.planShownLayers.every((n) => mergedLayers.some((l) => l.layer === n)) + ? this.planShownLayers.slice(0, 2) + : planDefaultLayerPair(mergedLayers)); + + if (this.planViewMode !== "list" && mergedLayers.length > 1) { + const layerBar = document.createElement("div"); + layerBar.className = "bp-plan-layerbar"; + for (const l of mergedLayers) { + const isShown = activeLayers.includes(l.layer); + layerBar.appendChild( + mkChip(l.title || l.layer, isShown, `mgmt-plan-layerpill-${l.layer}`, () => { + if (this.planGridMode === "single") { + this.planShownLayers = [l.layer]; + } else if (this.planGridMode === "pair") { + if (!activeLayers.includes(l.layer)) { + this.planShownLayers = activeLayers.length >= 2 ? [activeLayers[0], l.layer] : [...activeLayers, l.layer]; + } + } else { + this.planGridMode = "single"; + this.planShownLayers = [l.layer]; + } + this.render(); + }), + ); + } + wrap.appendChild(layerBar); + } + + const commitItemFields = (id: string, fields: Record): void => { + const prev = this.planOptimistic.get(id) ?? {}; + this.planOptimistic.set(id, { ...prev, ...fields }); + if (typeof fields.layer === "string") { + if (this.planGridMode === "single") { + this.planShownLayers = [fields.layer]; + } else if (this.planGridMode === "pair" && !activeLayers.includes(fields.layer)) { + this.planShownLayers = activeLayers.length >= 2 ? [activeLayers[0], fields.layer] : [...activeLayers, fields.layer]; + } + } + this.render(); + sendPlan("plan.update", { ops: [{ op: "set", id, fields }] }); + }; + + if (this.planSelectedId) { + let selLayer = ""; + let selItem: PlanItem | null = null; + for (const l of mergedLayers) { + const found = (l.items ?? []).find((it) => it.id === this.planSelectedId); + if (found) { + selLayer = l.layer; + selItem = found; + break; + } + } + if (selItem) { + const ins = document.createElement("div"); + ins.className = "bp-plan-inspector"; + ins.setAttribute("data-testid", "mgmt-plan-inspector"); + const top = document.createElement("div"); + top.className = "bp-plan-ins-row"; + const sw = document.createElement("span"); + sw.className = "bp-plan-ins-sw"; + sw.style.background = selItem.kind === "corridor" + ? planBusColor(selItem.name || selItem.id, selItem.color || "") + : planRailColor(selItem.name || selItem.id, selItem.color || ""); + const title = document.createElement("span"); + title.className = "bp-mgmt-strong"; + title.textContent = selItem.name || selItem.id; + const ltag = document.createElement("span"); + ltag.className = "bp-dim"; + ltag.textContent = selLayer; + top.append(sw, title, ltag); + if (selItem.edited || selItem.state === "edited") { + const ep = document.createElement("span"); + ep.className = "bp-plan-ins-pill warn"; + ep.textContent = t("gpui.mgmt.plan.edited", "Edited"); + top.appendChild(ep); + } + if (selItem.locked) { + const lp = document.createElement("span"); + lp.className = "bp-plan-ins-pill"; + lp.textContent = t("gpui.mgmt.plan.locked", "Locked"); + top.appendChild(lp); + } + const sp = document.createElement("span"); + sp.className = "bp-mgmt-flex1"; + top.appendChild(sp); + + const lockBtn = document.createElement("button"); + lockBtn.type = "button"; + lockBtn.className = "bp-mgmt-btn bp-plan-mini-btn"; + lockBtn.setAttribute("data-testid", "mgmt-plan-lock"); + lockBtn.textContent = selItem.locked + ? t("gpui.mgmt.plan.unlock", "Unlock") + : t("gpui.mgmt.plan.lock", "Lock"); + lockBtn.addEventListener("click", () => commitItemFields(selItem!.id, { locked: !selItem!.locked })); + top.appendChild(lockBtn); + + if (selItem.state === "proposed" || selItem.state === "edited") { + const okB = document.createElement("button"); + okB.type = "button"; + okB.className = "primary bp-mgmt-btn bp-plan-mini-btn"; + okB.textContent = t("android.hub.machines.approve", "Approve"); + okB.addEventListener("click", () => sendPlan("plan.approve", { layer: "", ids: [selItem!.id], approve: true })); + const noB = document.createElement("button"); + noB.type = "button"; + noB.className = "bp-mgmt-btn bp-plan-mini-btn"; + noB.textContent = t("gpui.mgmt.plan.reject", "Reject"); + noB.addEventListener("click", () => sendPlan("plan.approve", { layer: "", ids: [selItem!.id], approve: false })); + top.append(okB, noB); + } + + const noteBtn = document.createElement("button"); + noteBtn.type = "button"; + noteBtn.className = "bp-mgmt-btn bp-plan-mini-btn"; + noteBtn.setAttribute("data-testid", "mgmt-plan-note-toggle"); + noteBtn.textContent = t("gpui.mgmt.plan.addnote", "Add note"); + noteBtn.addEventListener("click", () => { + this.planNoteOpen = !this.planNoteOpen; + this.render(); + }); + const closeSel = document.createElement("button"); + closeSel.type = "button"; + closeSel.className = "icon"; + closeSel.textContent = "×"; + closeSel.addEventListener("click", () => { + this.planSelectedId = ""; + this.planNoteOpen = false; + this.render(); + }); + top.append(noteBtn, closeSel); + ins.appendChild(top); + + if (!selItem.locked) { + const ctrlRow = document.createElement("div"); + ctrlRow.className = "bp-plan-ins-row"; + if (selItem.kind === "corridor") { + const curW = typeof selItem.width === "number" ? selItem.width : 1.5; + const wLbl = document.createElement("span"); + wLbl.className = "bp-dim"; + wLbl.textContent = t("gpui.mgmt.plan.width", "Width"); + const wMinus = document.createElement("button"); + wMinus.type = "button"; + wMinus.className = "bp-mgmt-btn bp-plan-mini-btn"; + wMinus.setAttribute("data-testid", "mgmt-plan-w-down"); + wMinus.textContent = "-"; + wMinus.addEventListener("click", () => { + const nw = Math.round(Math.max(0.15, curW - 0.25) * 100) / 100; + commitItemFields(selItem!.id, { width: nw }); + }); + const wVal = document.createElement("span"); + wVal.className = "bp-plan-ins-val"; + wVal.textContent = `${curW.toFixed(2)}mm`; + const wPlus = document.createElement("button"); + wPlus.type = "button"; + wPlus.className = "bp-mgmt-btn bp-plan-mini-btn"; + wPlus.setAttribute("data-testid", "mgmt-plan-w-up"); + wPlus.textContent = "+"; + wPlus.addEventListener("click", () => { + const nw = Math.round(Math.min(25, curW + 0.25) * 100) / 100; + commitItemFields(selItem!.id, { width: nw }); + }); + const sepW = document.createElement("span"); + sepW.className = "bp-plan-sep"; + ctrlRow.append(wLbl, wMinus, wVal, wPlus, sepW); + } + + const moveOpts = (d.copper_layers ?? []).length > 0 + ? (d.copper_layers ?? []).map((c) => c.layer) + : mergedLayers.map((l) => l.layer); + if (moveOpts.length > 0) { + const mLbl = document.createElement("span"); + mLbl.className = "bp-dim"; + mLbl.textContent = t("gpui.mgmt.plan.layer.move", "Move to layer"); + ctrlRow.appendChild(mLbl); + for (const ml of moveOpts) { + ctrlRow.appendChild( + mkChip(ml, ml === selLayer, `mgmt-plan-move-${ml}`, () => { + if (ml !== selLayer) commitItemFields(selItem!.id, { layer: ml }); + }), + ); + } + } + ins.appendChild(ctrlRow); + } + + if (this.planNoteOpen) { + const nf = document.createElement("form"); + nf.className = "bp-plan-note-form"; + const ni = document.createElement("input"); + ni.type = "text"; + ni.className = "bp-plan-note-input"; + ni.setAttribute("data-testid", "mgmt-plan-note-input"); + ni.placeholder = t("gpui.mgmt.plan.note.placeholder", "Steering note for router…"); + const nb = document.createElement("button"); + nb.type = "submit"; + nb.className = "primary bp-mgmt-btn bp-plan-mini-btn"; + nb.setAttribute("data-testid", "mgmt-plan-note-submit"); + nb.textContent = t("gpui.mgmt.plan.addnote", "Add note"); + nf.append(ni, nb); + nf.addEventListener("submit", (e) => { + e.preventDefault(); + const txt = ni.value.trim(); + if (!txt) return; + ni.value = ""; + this.planNoteOpen = false; + this.render(); + sendPlan("plan.update", { ops: [{ op: "note", id: selItem!.id, text: txt }] }); + }); + ins.appendChild(nf); + } + + if (this.planViewMode !== "list" && !selItem.locked) { + const hint = document.createElement("div"); + hint.className = "bp-plan-hint"; + hint.textContent = t( + "gpui.mgmt.plan.hint", + "Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove", + ); + ins.appendChild(hint); + } + wrap.appendChild(ins); + } + } + const listEl = document.createElement("div"); - listEl.className = "bp-mgmt-rows"; + listEl.className = "bp-mgmt-rows" + (this.planViewMode === "split" ? " bp-plan-split-list" : ""); listEl.setAttribute("data-testid", "mgmt-plan-rows"); const doneWord = t("gpui.mgmt.plan.done", "done"); - for (const l of d.layers ?? []) { + for (const l of mergedLayers) { const items = l.items ?? []; const gh = document.createElement("div"); gh.className = "bp-mgmt-group-head bp-plan-layer-head"; @@ -1322,7 +1765,55 @@ export class MgmtStrip { listEl.appendChild(row); } } - wrap.appendChild(listEl); + if (this.planViewMode !== "list") { + if (!this.planCanvas) { + this.planCanvas = new PlanFloorplannerCanvas({ + onSelect: (id) => { + this.planSelectedId = id; + if (!id) this.planNoteOpen = false; + this.render(); + }, + onFocusItem: (id) => { + sendPlan("plan.focus", { id }); + }, + onOptimisticPatch: (id, fields) => { + const prev = this.planOptimistic.get(id) ?? {}; + this.planOptimistic.set(id, { ...prev, ...fields }); + }, + onCommitFields: (id, fields) => { + commitItemFields(id, fields); + }, + onApproveLayer: (layer, approve) => { + sendPlan("plan.approve", { layer, ids: [], approve }); + }, + onQuickApprove: (ids, approve) => { + sendPlan("plan.approve", { layer: "", ids, approve }); + }, + }); + } + const noViewer = this.panelEl.parentElement?.classList.contains("bp-has-viewer") === false; + const twoCols = this.planExpanded || this.panelEl.clientWidth >= 540 || noViewer; + this.planCanvas.update( + { + gridMode: this.planGridMode, + syncZoom: this.planSyncZoom, + shownLayers: activeLayers, + selectedId: this.planSelectedId, + board: rawBoard, + bands: mergedBands, + regions: mergedRegions, + layers: mergedLayers, + }, + twoCols, + ); + const canvasScroll = document.createElement("div"); + canvasScroll.className = "bp-plan-canvas-scroll"; + canvasScroll.appendChild(this.planCanvas.root); + wrap.appendChild(canvasScroll); + } + if (this.planViewMode !== "canvas") { + wrap.appendChild(listEl); + } if ((d.draw?.bands?.length ?? 0) > 0 || (d.draw?.regions?.length ?? 0) > 0) { const foot = document.createElement("div"); diff --git a/web/src/plan-canvas.ts b/web/src/plan-canvas.ts new file mode 100644 index 0000000000..a30892a977 --- /dev/null +++ b/web/src/plan-canvas.ts @@ -0,0 +1,951 @@ +// Interactive per-layer PCB routing floorplanner Canvas2D renderer & controller for Web UI. +// Matches native/gpui/src/screens/mgmt_plan_canvas.rs in visual styling, 10-step back-to-front +// paint order, hit testing, pan/zoom synchronization, and direct vertex/midpoint/keyboard steering. +import { t } from "./i18n"; +import { + planBandStrokePx, + planBusColor, + planDefaultLayerPair, + planFitCamera, + planHitTest, + planInsertVertex, + planLayoutLabels, + planPanCamera, + planPolylineMidpoint, + planPxToWorld, + planRailColor, + planRemoveVertex, + planWorldToPx, + planZoomCamera, + type PlanBand, + type PlanBoardGeom, + type PlanCamera, + type PlanHit, + type PlanLayer, + type PlanRegion, +} from "./mgmt-model"; + +export type PlanViewMode = "canvas" | "split" | "list"; +export type PlanGridMode = "pair" | "all" | "single"; + +export interface PlanCanvasStateSnapshot { + gridMode: PlanGridMode; + syncZoom: boolean; + shownLayers: string[]; + selectedId: string; + board: PlanBoardGeom; + bands: PlanBand[]; + regions: PlanRegion[]; + layers: PlanLayer[]; +} + +export interface PlanCanvasCallbacks { + onSelect: (id: string) => void; + onFocusItem: (id: string) => void; + onOptimisticPatch: (id: string, fields: Record) => void; + onCommitFields: (id: string, fields: Record) => void; + onApproveLayer: (layer: string, approve: boolean) => void; + onQuickApprove: (ids: string[], approve: boolean) => void; +} + +const SUBSTRATE_BG = "#111917"; +const BOARD_FILL = "#16201d"; +const EDGE_STROKE = "rgba(212, 224, 219, 0.92)"; +const PART_STROKE = "rgba(61, 80, 73, 0.72)"; +const PART_OVERHANG = "rgba(82, 107, 97, 0.85)"; +const REFDES_COLOR = "rgba(143, 163, 155, 0.88)"; +const HANDLE_ACTIVE = "#f59e0b"; +const HANDLE_BG = "#eef5f2"; +const BAD_RED = "#ef4444"; + +function hexToRgba(hex: string, alpha: number): string { + const h = hex.trim().replace(/^#/, ""); + if (h.length === 6) { + const r = parseInt(h.slice(0, 2), 16); + const g = parseInt(h.slice(2, 4), 16); + const b = parseInt(h.slice(4, 6), 16); + if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b)) { + return `rgba(${r}, ${g}, ${b}, ${alpha})`; + } + } + return `rgba(20, 184, 166, ${alpha})`; +} + +function bandAlphas(state: string, selected: boolean, hovered: boolean): { glow: number; body: number; core: number; bad: boolean } { + let glow = 0.14; + let body = 0.45; + let core = 0.85; + let bad = false; + switch (state) { + case "approved": + case "routing": + glow = 0.16; body = 0.51; core = 0.91; break; + case "edited": + glow = 0.20; body = 0.56; core = 0.95; break; + case "routed": + case "verified": + glow = 0.08; body = 0.26; core = 0.59; break; + case "rejected": + case "failed": + glow = 0.05; body = 0.13; core = 0.27; break; + case "blocked": + glow = 0.18; body = 0.48; core = 0.88; bad = true; break; + } + if (selected) { + glow = Math.min(0.35, glow + 0.10); + body = Math.min(0.71, body + 0.12); + core = 1.0; + } else if (hovered) { + glow = Math.min(0.28, glow + 0.06); + body = Math.min(0.63, body + 0.07); + } + return { glow, body, core, bad }; +} + +function regionAlphas(state: string, selected: boolean, hovered: boolean): { fill: number; edge: number; bad: boolean } { + let fill = 0.27; + let edge = 0.83; + let bad = false; + switch (state) { + case "approved": + case "routing": + fill = 0.36; edge = 0.91; break; + case "edited": + fill = 0.38; edge = 0.95; break; + case "routed": + case "verified": + fill = 0.16; edge = 0.54; break; + case "rejected": + case "failed": + fill = 0.08; edge = 0.27; break; + case "blocked": + fill = 0.31; edge = 0.94; bad = true; break; + } + if (selected) { + fill = Math.min(0.53, fill + 0.12); + edge = 1.0; + } else if (hovered) { + fill = Math.min(0.45, fill + 0.06); + edge = Math.min(1.0, edge + 0.10); + } + return { fill, edge, bad }; +} + +function layerStatusBadge(l: PlanLayer): { key: string; label: string; tone: string } { + const items = l.items ?? []; + if (items.some((i) => i.state === "blocked" || i.state === "failed")) return { key: "gpui.mgmt.plan.st.blocked", label: "Blocked", tone: "bad" }; + if (items.some((i) => i.state === "routing")) return { key: "gpui.mgmt.plan.st.routing", label: "Routing", tone: "accent" }; + if (items.some((i) => i.state === "proposed" || i.state === "edited")) return { key: "gpui.mgmt.plan.st.awaiting", label: "Awaiting review", tone: "warn" }; + if (items.length > 0 && items.every((i) => i.state === "routed" || i.state === "verified")) return { key: "gpui.mgmt.plan.st.routed", label: "Routed", tone: "ok" }; + if (items.length > 0 && items.every((i) => i.state === "approved" || i.state === "routed" || i.state === "verified")) return { key: "gpui.mgmt.plan.st.approved", label: "Approved", tone: "accent" }; + return { key: "gpui.mgmt.plan.st.empty", label: "Empty", tone: "faint" }; +} + +interface CardSlot { + layer: string; + el: HTMLElement; + canvas: HTMLCanvasElement; + ctx: CanvasRenderingContext2D; + legendEl: HTMLElement; + okBtn: HTMLButtonElement | null; + noBtn: HTMLButtonElement | null; + statusEl: HTMLElement; + titleEl: HTMLElement; + subtitleEl: HTMLElement; + hoverHudEl: HTMLElement; + ro: ResizeObserver; +} + +export class PlanFloorplannerCanvas { + public readonly root: HTMLElement; + private cb: PlanCanvasCallbacks; + private state: PlanCanvasStateSnapshot | null = null; + private cards = new Map(); + private renderedLayerKey = ""; + + private sharedCam: PlanCamera | null = null; + private layerCams = new Map(); + private hover: { layer: string; hit: PlanHit } | null = null; + private selectedVertex: { id: string; idx: number } | null = null; + private drag: + | { layer: string; kind: "pan"; lastX: number; lastY: number } + | { layer: string; kind: "vertex"; id: string; isPlane: boolean; idx: number; pts: Array<[number, number]> } + | null = null; + private downPos: { x: number; y: number } | null = null; + private rafPending = 0; + + constructor(cb: PlanCanvasCallbacks) { + this.cb = cb; + this.root = document.createElement("div"); + this.root.className = "bp-plan-canvas-grid"; + this.root.tabIndex = 0; + this.root.setAttribute("data-testid", "mgmt-plan-canvas-grid"); + this.root.addEventListener("keydown", (e) => this.onKeyDown(e)); + } + + public fitAll(): void { + this.sharedCam = null; + this.layerCams.clear(); + this.scheduleDraw(); + } + + public destroy(): void { + if (this.rafPending) { + cancelAnimationFrame(this.rafPending); + this.rafPending = 0; + } + for (const card of this.cards.values()) { + card.ro.disconnect(); + } + this.cards.clear(); + this.root.replaceChildren(); + } + + private visibleLayers(s: PlanCanvasStateSnapshot): PlanLayer[] { + if (s.layers.length === 0) return []; + if (s.gridMode === "all") return s.layers; + if (s.gridMode === "single") { + const target = + s.shownLayers.find((n) => s.layers.some((l) => l.layer === n)) ?? + planDefaultLayerPair(s.layers)[0] ?? + s.layers[0]?.layer; + const found = s.layers.find((l) => l.layer === target); + return found ? [found] : []; + } + const pairNames = + s.shownLayers.length > 0 && s.shownLayers.every((n) => s.layers.some((l) => l.layer === n)) + ? s.shownLayers.slice(0, 2) + : planDefaultLayerPair(s.layers); + const out: PlanLayer[] = []; + for (const name of pairNames) { + const found = s.layers.find((l) => l.layer === name); + if (found) out.push(found); + } + return out.length > 0 ? out : s.layers.slice(0, 2); + } + + public update(snapshot: PlanCanvasStateSnapshot, twoCols: boolean): void { + this.state = snapshot; + const vis = this.visibleLayers(snapshot); + this.root.classList.toggle("two-cols", twoCols && vis.length > 1); + const key = vis.map((l) => l.layer).join("|"); + if (key !== this.renderedLayerKey) { + this.renderedLayerKey = key; + for (const card of this.cards.values()) card.ro.disconnect(); + this.cards.clear(); + this.root.replaceChildren(); + for (const l of vis) { + const slot = this.buildCard(l); + this.cards.set(l.layer, slot); + this.root.appendChild(slot.el); + } + } else { + for (const l of vis) { + const slot = this.cards.get(l.layer); + if (slot) this.syncCardHeaderAndLegend(slot, l); + } + } + this.scheduleDraw(); + } + + private effectiveBbox(board: PlanBoardGeom): [number, number, number, number] { + const bb = board.bbox; + if (!bb || bb.length !== 4 || Math.abs(bb[2] - bb[0]) < 0.5 || Math.abs(bb[3] - bb[1]) < 0.5) { + return [0, 0, 100, 70]; + } + return bb; + } + + private getCam(layer: string, w: number, h: number): PlanCamera { + const s = this.state; + const raw = s?.syncZoom ? this.sharedCam : this.layerCams.get(layer) ?? null; + if (raw && raw.touched) return raw; + return planFitCamera(s ? this.effectiveBbox(s.board) : [0, 0, 100, 70], w, h, 14); + } + + private setCam(layer: string, cam: PlanCamera): void { + if (this.state?.syncZoom) { + this.sharedCam = cam; + } else { + this.layerCams.set(layer, cam); + } + } + + private buildCard(l: PlanLayer): CardSlot { + const el = document.createElement("section"); + el.className = "bp-plan-card"; + el.setAttribute("data-testid", `mgmt-plan-card-${l.layer}`); + + const head = document.createElement("div"); + head.className = "bp-plan-card-head"; + const headTop = document.createElement("div"); + headTop.className = "bp-plan-card-head-top"; + + const bar = document.createElement("span"); + const isPower = l.role === "power" || ((l.items?.length ?? 0) > 0 && (l.items ?? []).every((i) => i.kind === "plane")); + bar.className = "bp-plan-card-bar " + (isPower ? "pwr" : "sig"); + + const titleEl = document.createElement("span"); + titleEl.className = "bp-plan-card-title"; + const statusEl = document.createElement("span"); + statusEl.className = "bp-plan-status-badge"; + + const okBtn = document.createElement("button"); + okBtn.type = "button"; + okBtn.className = "bp-mgmt-btn bp-plan-mini-btn"; + okBtn.textContent = "✓"; + okBtn.title = t("gpui.mgmt.plan.layer", "Approve layer"); + okBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.cb.onApproveLayer(l.layer, true); + }); + + const noBtn = document.createElement("button"); + noBtn.type = "button"; + noBtn.className = "bp-mgmt-btn bp-plan-mini-btn"; + noBtn.textContent = "✗"; + noBtn.title = t("gpui.mgmt.plan.rejectlayer", "Reject layer"); + noBtn.addEventListener("click", (e) => { + e.stopPropagation(); + this.cb.onApproveLayer(l.layer, false); + }); + + headTop.append(bar, titleEl, statusEl, okBtn, noBtn); + const subtitleEl = document.createElement("div"); + subtitleEl.className = "bp-plan-card-sub"; + head.append(headTop, subtitleEl); + + const wrap = document.createElement("div"); + wrap.className = "bp-plan-card-canvas-wrap"; + const canvas = document.createElement("canvas"); + canvas.className = "bp-plan-card-canvas"; + canvas.setAttribute("data-testid", `mgmt-plan-canvas-${l.layer}`); + const hoverHudEl = document.createElement("div"); + hoverHudEl.className = "bp-plan-hover-hud bp-hidden"; + wrap.append(canvas, hoverHudEl); + + const legendEl = document.createElement("div"); + legendEl.className = "bp-plan-legend bp-hidden"; + + el.append(head, wrap, legendEl); + + const ctx = canvas.getContext("2d")!; + const ro = new ResizeObserver(() => this.scheduleDraw()); + ro.observe(wrap); + + this.attachPointerListeners(canvas, l.layer); + + const slot: CardSlot = { + layer: l.layer, + el, + canvas, + ctx, + legendEl, + okBtn, + noBtn, + statusEl, + titleEl, + subtitleEl, + hoverHudEl, + ro, + }; + this.syncCardHeaderAndLegend(slot, l); + return slot; + } + + private syncCardHeaderAndLegend(slot: CardSlot, l: PlanLayer): void { + slot.titleEl.textContent = l.title || l.layer; + const sub = l.subtitle || l.stackup || ""; + slot.subtitleEl.textContent = sub; + slot.subtitleEl.classList.toggle("bp-hidden", !sub); + + const st = layerStatusBadge(l); + slot.statusEl.className = `bp-plan-status-badge tone-${st.tone}`; + slot.statusEl.textContent = t(st.key, st.label); + + const hasAwaiting = (l.items ?? []).some((i) => i.state === "proposed" || i.state === "edited"); + if (slot.okBtn) slot.okBtn.classList.toggle("bp-hidden", !hasAwaiting); + if (slot.noBtn) slot.noBtn.classList.toggle("bp-hidden", !hasAwaiting); + + const regions = (this.state?.regions ?? []).filter((r) => r.layer === l.layer); + if (regions.length === 0) { + slot.legendEl.classList.add("bp-hidden"); + slot.legendEl.replaceChildren(); + } else { + slot.legendEl.classList.remove("bp-hidden"); + const frag = document.createDocumentFragment(); + for (const r of regions) { + const chip = document.createElement("button"); + chip.type = "button"; + const isSel = this.state?.selectedId === r.id; + chip.className = "bp-plan-legend-chip" + (isSel ? " active" : ""); + const sw = document.createElement("span"); + sw.className = "bp-plan-legend-sw"; + sw.style.background = planRailColor(r.net || r.id, r.color || ""); + const tx = document.createElement("span"); + tx.textContent = r.net || r.id; + chip.append(sw, tx); + chip.addEventListener("click", () => { + this.cb.onSelect(r.id); + this.cb.onFocusItem(r.id); + }); + frag.appendChild(chip); + } + slot.legendEl.replaceChildren(frag); + } + } + + private attachPointerListeners(canvas: HTMLCanvasElement, layer: string): void { + canvas.addEventListener("contextmenu", (e) => e.preventDefault()); + + canvas.addEventListener("pointerdown", (e) => { + const s = this.state; + if (!s) return; + this.root.focus(); + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + const w = Math.max(1, rect.width); + const h = Math.max(1, rect.height); + const cam = this.getCam(layer, w, h); + const hit = planHitTest(s.bands, s.regions, layer, s.selectedId, cam, w, h, mx, my); + + if (e.button === 2) { + if (hit?.kind === "vertex") { + const pts = this.getItemPts(hit.id, hit.isPlane); + const nextPts = planRemoveVertex(pts, hit.idx, hit.isPlane); + if (nextPts) { + this.selectedVertex = null; + this.cb.onCommitFields(hit.id, { [hit.isPlane ? "outline" : "path"]: nextPts }); + } + } + return; + } + + if (e.button !== 0) return; + canvas.setPointerCapture(e.pointerId); + this.downPos = { x: e.clientX, y: e.clientY }; + + if (hit?.kind === "vertex") { + const pts = this.getItemPts(hit.id, hit.isPlane); + this.selectedVertex = { id: hit.id, idx: hit.idx }; + this.cb.onSelect(hit.id); + this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: hit.idx, pts: pts.map((p) => [p[0], p[1]]) }; + this.scheduleDraw(); + } else if (hit?.kind === "midpoint") { + const curPts = this.getItemPts(hit.id, hit.isPlane); + const newPts = planInsertVertex(curPts, hit.segIdx, hit.pos, hit.isPlane); + const insertedIdx = hit.isPlane && hit.segIdx + 1 >= curPts.length ? newPts.length - 1 : Math.min(hit.segIdx + 1, newPts.length - 1); + this.cb.onSelect(hit.id); + this.selectedVertex = { id: hit.id, idx: insertedIdx }; + this.patchLocalItem(hit.id, hit.isPlane, newPts); + this.cb.onOptimisticPatch(hit.id, { [hit.isPlane ? "outline" : "path"]: newPts }); + this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: insertedIdx, pts: newPts }; + this.scheduleDraw(); + } else { + if (hit && (hit.kind === "band" || hit.kind === "region")) { + this.cb.onSelect(hit.id); + } + this.selectedVertex = null; + this.drag = { layer, kind: "pan", lastX: mx, lastY: my }; + } + }); + + canvas.addEventListener("pointermove", (e) => { + const s = this.state; + if (!s) return; + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + const w = Math.max(1, rect.width); + const h = Math.max(1, rect.height); + + if (this.drag && this.drag.layer === layer) { + if (this.drag.kind === "pan") { + const cam = this.getCam(layer, w, h); + this.setCam(layer, planPanCamera(cam, mx - this.drag.lastX, my - this.drag.lastY)); + this.drag.lastX = mx; + this.drag.lastY = my; + this.scheduleDraw(); + return; + } + const cam = this.getCam(layer, w, h); + const [wx, wy] = planPxToWorld(cam, mx, my, w, h); + const rounded: [number, number] = [Math.round(wx * 1000) / 1000, Math.round(wy * 1000) / 1000]; + this.drag.pts[this.drag.idx] = rounded; + const copy = this.drag.pts.map((p) => [p[0], p[1]] as [number, number]); + this.patchLocalItem(this.drag.id, this.drag.isPlane, copy); + this.cb.onOptimisticPatch(this.drag.id, { [this.drag.isPlane ? "outline" : "path"]: copy }); + this.scheduleDraw(); + return; + } + + const cam = this.getCam(layer, w, h); + const hit = planHitTest(s.bands, s.regions, layer, s.selectedId, cam, w, h, mx, my); + const prevId = this.hover?.hit ? ("id" in this.hover.hit ? this.hover.hit.id : "") : ""; + const nextId = hit ? hit.id : ""; + this.hover = hit ? { layer, hit } : null; + canvas.style.cursor = hit?.kind === "vertex" || hit?.kind === "midpoint" ? "pointer" : hit ? "pointer" : "crosshair"; + if (prevId !== nextId || hit?.kind !== this.hover?.hit.kind) { + this.syncHoverHud(layer); + this.scheduleDraw(); + } + }); + + canvas.addEventListener("pointerleave", () => { + if (this.hover?.layer === layer) { + this.hover = null; + this.syncHoverHud(layer); + this.scheduleDraw(); + } + }); + + canvas.addEventListener("pointerup", (e) => { + const s = this.state; + const d = this.drag; + const down = this.downPos; + this.drag = null; + this.downPos = null; + if (canvas.hasPointerCapture(e.pointerId)) { + canvas.releasePointerCapture(e.pointerId); + } + if (d && d.kind === "vertex" && d.layer === layer) { + this.cb.onCommitFields(d.id, { [d.isPlane ? "outline" : "path"]: d.pts }); + return; + } + if (e.detail >= 2) { + this.fitAll(); + return; + } + if (s && down && Math.hypot(e.clientX - down.x, e.clientY - down.y) < 4.5) { + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + const w = Math.max(1, rect.width); + const h = Math.max(1, rect.height); + const cam = this.getCam(layer, w, h); + const hit = planHitTest(s.bands, s.regions, layer, s.selectedId, cam, w, h, mx, my); + if (hit && (hit.kind === "band" || hit.kind === "region")) { + this.cb.onSelect(hit.id); + this.cb.onFocusItem(hit.id); + } else if (!hit) { + this.cb.onSelect(""); + } + } + }); + + canvas.addEventListener( + "wheel", + (e) => { + e.preventDefault(); + const rect = canvas.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + const w = Math.max(1, rect.width); + const h = Math.max(1, rect.height); + const cam = this.getCam(layer, w, h); + const factor = Math.max(0.65, Math.min(1.55, 1 - e.deltaY * 0.002)); + this.setCam(layer, planZoomCamera(cam, factor, mx, my, w, h)); + this.scheduleDraw(); + }, + { passive: false }, + ); + } + + private patchLocalItem(id: string, isPlane: boolean, pts: Array<[number, number]>): void { + const s = this.state; + if (!s) return; + if (isPlane) { + const r = s.regions.find((x) => x.id === id); + if (r) { r.outline = pts; r.edited = true; if (r.state === "proposed") r.state = "edited"; } + } else { + const b = s.bands.find((x) => x.id === id); + if (b) { b.path = pts; b.edited = true; if (b.state === "proposed") b.state = "edited"; } + } + } + + private getItemPts(id: string, isPlane: boolean): Array<[number, number]> { + const s = this.state; + if (!s) return []; + if (isPlane) { + return (s.regions.find((r) => r.id === id)?.outline ?? []).map((p) => [p[0], p[1]]); + } + return (s.bands.find((b) => b.id === id)?.path ?? []).map((p) => [p[0], p[1]]); + } + + private syncHoverHud(layer: string): void { + const slot = this.cards.get(layer); + const s = this.state; + if (!slot || !s) return; + if (!this.hover || this.hover.layer !== layer) { + slot.hoverHudEl.classList.add("bp-hidden"); + slot.hoverHudEl.textContent = ""; + return; + } + const hid = this.hover.hit.id; + const band = s.bands.find((b) => b.id === hid); + const region = s.regions.find((r) => r.id === hid); + let txt = ""; + if (band) { + txt = `${band.name || hid} · ${band.nets ?? 0}n · ${(band.width ?? 1.5).toFixed(2)}mm`; + } else if (region) { + txt = region.reference ? `${region.net || hid} · ${region.reference}` : region.net || hid; + } + if (!txt) { + slot.hoverHudEl.classList.add("bp-hidden"); + } else { + slot.hoverHudEl.classList.remove("bp-hidden"); + slot.hoverHudEl.textContent = txt; + } + } + + private onKeyDown(e: KeyboardEvent): void { + const s = this.state; + if (!s) return; + if (e.key === "0" || e.key === "Home") { + e.preventDefault(); + this.fitAll(); + return; + } + if (e.key === "Escape") { + this.selectedVertex = null; + this.cb.onSelect(""); + return; + } + if (!s.selectedId) return; + const band = s.bands.find((b) => b.id === s.selectedId); + const region = s.regions.find((r) => r.id === s.selectedId); + const locked = Boolean(band?.locked ?? region?.locked); + const k = e.key.toLowerCase(); + if (k === "a") { + e.preventDefault(); + this.cb.onQuickApprove([s.selectedId], true); + } else if (k === "r") { + e.preventDefault(); + this.cb.onQuickApprove([s.selectedId], false); + } else if (k === "l") { + e.preventDefault(); + this.cb.onCommitFields(s.selectedId, { locked: !locked }); + } else if (k === "w" && band && !locked) { + e.preventDefault(); + const delta = e.shiftKey ? -0.25 : 0.25; + const nw = Math.round(Math.max(0.15, Math.min(25, (band.width ?? 1.5) + delta)) * 100) / 100; + this.cb.onCommitFields(s.selectedId, { width: nw }); + } else if ((e.key === "Delete" || e.key === "Backspace") && !locked && this.selectedVertex?.id === s.selectedId) { + e.preventDefault(); + const isPlane = Boolean(region); + const pts = this.getItemPts(s.selectedId, isPlane); + const next = planRemoveVertex(pts, this.selectedVertex.idx, isPlane); + if (next) { + this.selectedVertex = null; + this.cb.onCommitFields(s.selectedId, { [isPlane ? "outline" : "path"]: next }); + } + } + } + + private scheduleDraw(): void { + if (this.rafPending) return; + this.rafPending = requestAnimationFrame(() => { + this.rafPending = 0; + this.drawAll(); + }); + } + + private drawAll(): void { + const s = this.state; + if (!s) return; + const aspect = Math.max( + 0.45, + Math.min(1.25, Math.abs(this.effectiveBbox(s.board)[3] - this.effectiveBbox(s.board)[1]) / Math.max(1, Math.abs(this.effectiveBbox(s.board)[2] - this.effectiveBbox(s.board)[0]))), + ); + for (const slot of this.cards.values()) { + const wrap = slot.canvas.parentElement; + if (!wrap) continue; + const cssW = Math.max(120, Math.round(wrap.clientWidth)); + const cssH = Math.max(165, Math.min(250, Math.round(cssW * aspect))); + slot.canvas.style.height = `${cssH}px`; + const dpr = Math.max(1, window.devicePixelRatio || 1); + const pw = Math.round(cssW * dpr); + const ph = Math.round(cssH * dpr); + if (slot.canvas.width !== pw || slot.canvas.height !== ph) { + slot.canvas.width = pw; + slot.canvas.height = ph; + } + slot.ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + this.drawLayer(slot.ctx, slot.layer, cssW, cssH, s); + } + } + + private drawLayer(ctx: CanvasRenderingContext2D, layer: string, w: number, h: number, s: PlanCanvasStateSnapshot): void { + const cam = this.getCam(layer, w, h); + const toPx = (x: number, y: number): [number, number] => planWorldToPx(cam, x, y, w, h); + + // 1. Dark PCB substrate + ctx.fillStyle = SUBSTRATE_BG; + ctx.fillRect(0, 0, w, h); + + // 2. Board interior (#16201d) + const outline = (s.board.outline ?? []).filter((p) => p.length >= 3); + ctx.fillStyle = BOARD_FILL; + if (outline.length > 0) { + ctx.beginPath(); + for (const poly of outline) { + for (let i = 0; i < poly.length; i++) { + const [px, py] = toPx(poly[i][0], poly[i][1]); + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.closePath(); + } + ctx.fill("evenodd"); + } else { + const bb = this.effectiveBbox(s.board); + const [x0, y0] = toPx(bb[0], bb[1]); + const [x1, y1] = toPx(bb[2], bb[3]); + ctx.fillRect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0)); + } + + // 3. Power plane pours (on this layer, beneath components) + const layerRegions = s.regions.filter((r) => r.layer === layer); + const hovHit = this.hover?.layer === layer ? this.hover.hit : null; + for (const r of layerRegions) { + const outer = r.outline ?? []; + if (outer.length < 3) continue; + const sel = s.selectedId === r.id; + const hov = hovHit?.id === r.id; + const al = regionAlphas(r.state || "proposed", sel, hov); + const col = planRailColor(r.net || r.id, r.color || ""); + + ctx.beginPath(); + for (let i = 0; i < outer.length; i++) { + const [px, py] = toPx(outer[i][0], outer[i][1]); + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.closePath(); + for (const hole of r.holes ?? []) { + if (hole.length < 3) continue; + for (let i = 0; i < hole.length; i++) { + const [px, py] = toPx(hole[i][0], hole[i][1]); + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.closePath(); + } + ctx.fillStyle = hexToRgba(col, al.fill); + ctx.fill("evenodd"); + + ctx.beginPath(); + for (let i = 0; i < outer.length; i++) { + const [px, py] = toPx(outer[i][0], outer[i][1]); + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.closePath(); + ctx.lineWidth = sel || al.bad ? 2 : 1.25; + ctx.lineJoin = "round"; + ctx.strokeStyle = al.bad ? BAD_RED : sel ? "#ffffff" : hexToRgba(col, al.edge); + ctx.stroke(); + } + + // 4. Crisp Edge.Cuts outline + ctx.strokeStyle = EDGE_STROKE; + ctx.lineWidth = 1.25; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + if (outline.length > 0) { + ctx.beginPath(); + for (const poly of outline) { + for (let i = 0; i < poly.length; i++) { + const [px, py] = toPx(poly[i][0], poly[i][1]); + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + ctx.closePath(); + } + ctx.stroke(); + } else { + const bb = this.effectiveBbox(s.board); + const [x0, y0] = toPx(bb[0], bb[1]); + const [x1, y1] = toPx(bb[2], bb[3]); + ctx.strokeRect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0)); + } + + // 5. Component courtyard/body outlines (solid top, dashed bottom/overhang) + const parts = s.board.parts ?? []; + ctx.lineWidth = 0.85; + ctx.strokeStyle = PART_STROKE; + ctx.setLineDash([]); + ctx.beginPath(); + for (const p of parts) { + if (p.o) continue; + const [x0, y0] = toPx(p.b[0], p.b[1]); + const [x1, y1] = toPx(p.b[2], p.b[3]); + ctx.rect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0)); + } + ctx.stroke(); + + ctx.lineWidth = 0.95; + ctx.strokeStyle = PART_OVERHANG; + ctx.setLineDash([4, 3]); + ctx.beginPath(); + for (const p of parts) { + if (!p.o) continue; + const [x0, y0] = toPx(p.b[0], p.b[1]); + const [x1, y1] = toPx(p.b[2], p.b[3]); + ctx.rect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0)); + } + ctx.stroke(); + ctx.setLineDash([]); + + // 6. Collision-free refdes labels + const layerBands = s.bands.filter((b) => b.layer === layer); + const pinnedRefs: string[] = []; + for (const b of layerBands) { + for (const r of b.from ?? []) pinnedRefs.push(r); + for (const r of b.to ?? []) pinnedRefs.push(r); + } + ctx.fillStyle = REFDES_COLOR; + ctx.font = "9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + for (const lbl of planLayoutLabels(parts, cam, w, h, pinnedRefs)) { + ctx.fillText(lbl.text, lbl.cx, lbl.cy); + } + + // 7. Faint signal ratsnest guides + for (const b of layerBands) { + const guides = b.guides ?? []; + if (guides.length === 0) continue; + const active = s.selectedId === b.id || hovHit?.id === b.id; + const col = planBusColor(b.name || b.id, b.color || ""); + ctx.strokeStyle = hexToRgba(col, active ? 0.38 : 0.17); + ctx.lineWidth = active ? 1 : 0.7; + ctx.beginPath(); + for (const seg of guides) { + const [x1, y1] = toPx(seg[0], seg[1]); + const [x2, y2] = toPx(seg[2], seg[3]); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + } + ctx.stroke(); + } + + // 8, 9, 10. Multi-pass rounded-cap signal bus corridors + diamond vias + net-count badges + for (const b of layerBands) { + const pts = b.path ?? []; + if (pts.length < 2) continue; + const sel = s.selectedId === b.id; + const hov = hovHit?.id === b.id; + const al = bandAlphas(b.state || "proposed", sel, hov); + const col = planBusColor(b.name || b.id, b.color || ""); + const wpx = planBandStrokePx(b.width ?? 1.5, cam.scale); + + const tracePath = () => { + ctx.beginPath(); + for (let i = 0; i < pts.length; i++) { + const [px, py] = toPx(pts[i][0], pts[i][1]); + if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); + } + }; + + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + + // Pass 1: outer halo glow + tracePath(); + ctx.strokeStyle = hexToRgba(col, al.glow); + ctx.lineWidth = wpx + 6; + ctx.stroke(); + + if (al.bad || sel) { + tracePath(); + ctx.strokeStyle = al.bad ? BAD_RED : "rgba(255,255,255,0.75)"; + ctx.lineWidth = wpx + 2.5; + ctx.stroke(); + } + + // Pass 2: corridor envelope + tracePath(); + ctx.strokeStyle = hexToRgba(col, al.body); + ctx.lineWidth = wpx; + ctx.stroke(); + + // Pass 3: crisp inner spine + tracePath(); + ctx.strokeStyle = hexToRgba(col, al.core); + ctx.lineWidth = Math.max(1.8, Math.min(5, wpx * 0.34)); + ctx.stroke(); + + // 9. Diamond vias + for (const v of b.vias ?? []) { + const [vx, vy] = toPx(v[0], v[1]); + const r = 4.2; + ctx.beginPath(); + ctx.moveTo(vx, vy - r); + ctx.lineTo(vx + r, vy); + ctx.lineTo(vx, vy + r); + ctx.lineTo(vx - r, vy); + ctx.closePath(); + ctx.fillStyle = "rgba(17, 25, 23, 0.95)"; + ctx.fill(); + ctx.lineWidth = 1.5; + ctx.strokeStyle = sel ? "#ffffff" : col; + ctx.stroke(); + } + + // 10. Centered net-count pill + const nets = b.nets ?? 0; + if (nets > 0) { + const mid = planPolylineMidpoint(pts); + if (mid) { + const [mx, my] = toPx(mid[0], mid[1]); + const txt = String(nets); + const pw = Math.max(16, txt.length * 6.5 + 8); + const ph = 15; + ctx.fillStyle = "rgba(17, 25, 23, 0.94)"; + ctx.fillRect(mx - pw * 0.5, my - ph * 0.5, pw, ph); + ctx.lineWidth = 1.2; + ctx.strokeStyle = sel ? "#ffffff" : col; + ctx.strokeRect(mx - pw * 0.5, my - ph * 0.5, pw, ph); + ctx.fillStyle = "#eef5f2"; + ctx.font = "bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(txt, mx, my + 0.5); + } + } + } + + // 11. Selected item vertex & midpoint handles + if (s.selectedId) { + const paintHandles = (pts: Array<[number, number]>, closed: boolean) => { + const segs = closed ? pts.length : Math.max(0, pts.length - 1); + for (let i = 0; i < segs; i++) { + const a = pts[i]; + const b = pts[(i + 1) % pts.length]; + const [hx, hy] = toPx((a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5); + const isHov = hovHit?.kind === "midpoint" && hovHit.id === s.selectedId && hovHit.segIdx === i; + const sz = isHov ? 9 : 7.5; + ctx.fillStyle = "rgba(22, 32, 29, 0.92)"; + ctx.fillRect(hx - sz * 0.5, hy - sz * 0.5, sz, sz); + ctx.lineWidth = 1; + ctx.strokeStyle = isHov ? HANDLE_ACTIVE : "#94a3b8"; + ctx.strokeRect(hx - sz * 0.5, hy - sz * 0.5, sz, sz); + } + for (let i = 0; i < pts.length; i++) { + const [vx, vy] = toPx(pts[i][0], pts[i][1]); + const isSelV = this.selectedVertex?.id === s.selectedId && this.selectedVertex.idx === i; + const isHovV = hovHit?.kind === "vertex" && hovHit.id === s.selectedId && hovHit.idx === i; + const sz = isSelV || isHovV ? 9.5 : 7.5; + ctx.fillStyle = isSelV || isHovV ? HANDLE_ACTIVE : HANDLE_BG; + ctx.fillRect(vx - sz * 0.5, vy - sz * 0.5, sz, sz); + ctx.lineWidth = 1.2; + ctx.strokeStyle = SUBSTRATE_BG; + ctx.strokeRect(vx - sz * 0.5, vy - sz * 0.5, sz, sz); + } + }; + for (const b of layerBands) { + if (b.id === s.selectedId && !b.locked) paintHandles(b.path ?? [], false); + } + for (const r of layerRegions) { + if (r.id === s.selectedId && !r.locked) paintHandles(r.outline ?? [], true); + } + } + } +} diff --git a/web/src/shell.css b/web/src/shell.css index 706a5c6106..589a96b3b7 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -722,6 +722,10 @@ html.light .bp-code-block { background: var(--panel); } .bp-mgmt-close { width: 28px; height: 28px; flex-shrink: 0; color: var(--dim); } .bp-mgmt-panel { width: 370px; + max-width: 100%; + min-width: 0; + overflow: hidden; + box-sizing: border-box; flex-shrink: 0; display: flex; flex-direction: column; @@ -1668,3 +1672,217 @@ button.primary.bp-send-btn.is-plan-exec { color: var(--faint); flex-shrink: 0; } +.bp-mgmt-panel.bp-plan-expanded { + width: min(720px, 100%); + max-width: 100%; + flex-shrink: 1; + min-width: 0; +} +.bp-right-area:has(.bp-mgmt-panel.bp-plan-expanded), +.bp-right-area.bp-has-viewer.bp-has-mgmt:has(.bp-mgmt-panel.bp-plan-expanded) { + width: 68%; +} +.bp-plan-err .bp-mgmt-flex1 { + white-space: normal; + overflow-wrap: anywhere; + text-overflow: clip; +} +.bp-plan-viewbar, +.bp-plan-layerbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + padding: 4px 8px; + background: var(--panel); + border-bottom: 1px solid var(--rule); + flex-shrink: 0; + font-size: 11px; +} +.bp-plan-layerbar { + background: var(--bg); + font-size: 10px; +} +.bp-plan-sep { + width: 1px; + height: 12px; + background: var(--line); + margin: 0 2px; +} +.bp-plan-inspector { + display: flex; + flex-direction: column; + gap: 5px; + padding: 6px 8px; + background: var(--panel); + border-bottom: 1px solid var(--rule); + flex-shrink: 0; + font-size: 11px; +} +.bp-plan-ins-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 5px; +} +.bp-plan-ins-sw { + width: 10px; + height: 10px; + flex-shrink: 0; +} +.bp-plan-ins-pill { + padding: 1px 4px; + border: 1px solid var(--line); + font-size: 10px; + color: var(--dim); +} +.bp-plan-ins-pill.warn { + border-color: var(--warn); + color: var(--warn); +} +.bp-plan-ins-val { + padding: 0 4px; + font-family: var(--mono); + color: var(--text); +} +.bp-plan-note-form { + display: flex; + align-items: center; + gap: 4px; +} +.bp-plan-note-input { + flex: 1; + min-width: 0; + padding: 3px 6px; + background: var(--bg); + border: 1px solid var(--line); + color: var(--text); + font-size: 11px; +} +.bp-plan-hint { + font-size: 10px; + color: var(--faint); +} +.bp-plan-canvas-scroll { + flex: 1 1 0%; + min-height: 240px; + overflow-y: auto; + background: var(--bg); +} +.bp-plan-canvas-grid { + display: grid; + grid-template-columns: 1fr; + gap: 8px; + padding: 6px; + outline: none; +} +.bp-plan-canvas-grid.two-cols { + grid-template-columns: 1fr 1fr; + align-items: start; +} +.bp-plan-card { + display: flex; + flex-direction: column; + border: 1px solid var(--line); + background: var(--panel); + min-width: 0; +} +.bp-plan-card-head { + display: flex; + flex-direction: column; + gap: 2px; + padding: 5px 8px; + background: var(--panel); + border-bottom: 1px solid var(--line); +} +.bp-plan-card-head-top { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} +.bp-plan-card-bar { + width: 3px; + height: 14px; + flex-shrink: 0; +} +.bp-plan-card-bar.sig { background: var(--accent); } +.bp-plan-card-bar.pwr { background: var(--warn); } +.bp-plan-card-title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 700; + font-size: 12px; + color: var(--text); +} +.bp-plan-card-sub { + font-size: 10px; + color: var(--dim); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.bp-plan-mini-btn { + padding: 1px 6px; + font-size: 10px; +} +.bp-plan-card-canvas-wrap { + position: relative; + width: 100%; + background: #111917; + overflow: hidden; +} +.bp-plan-card-canvas { + display: block; + width: 100%; + touch-action: none; +} +.bp-plan-hover-hud { + position: absolute; + top: 8px; + right: 8px; + padding: 2px 6px; + background: rgba(17, 25, 23, 0.94); + border: 1px solid #526b61; + color: #eef5f2; + font-family: var(--mono); + font-size: 10px; + pointer-events: none; +} +.bp-plan-legend { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 5px; + padding: 5px 8px; + background: var(--panel); + border-top: 1px solid var(--line); +} +.bp-plan-legend-chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 5px; + background: var(--bg); + border: 1px solid var(--line); + color: var(--dim); + font-family: var(--mono); + font-size: 10px; + cursor: pointer; +} +.bp-plan-legend-chip:hover { background: var(--raise); color: var(--text); } +.bp-plan-legend-chip.active { border-color: var(--accent); background: var(--raise); color: var(--text); } +.bp-plan-legend-sw { + width: 8px; + height: 8px; + flex-shrink: 0; +} +.bp-plan-split-list { + flex: 0 0 155px; + min-height: 110px; + border-top: 1px solid var(--rule); + overflow-y: auto; +} diff --git a/web/test/mgmt.test.ts b/web/test/mgmt.test.ts index 0de12b6a21..c7bcd319ff 100644 --- a/web/test/mgmt.test.ts +++ b/web/test/mgmt.test.ts @@ -21,6 +21,15 @@ import { refsFit, stockSummary, tierWords, + planPolylineMidpoint, + planRailColor, + planBusColor, + planFitCamera, + planHitTest, + planInsertVertex, + planRemoveVertex, + planDefaultLayerPair, + planLayoutLabels, } from "../src/mgmt-model"; describe("Management strip pure model", () => { @@ -147,4 +156,64 @@ describe("Management strip pure model", () => { // Switched project -> discarded expect(isChecksFixCurrent(start, { watchGen: 2, project: "/proj/B", threadId: "t1", threadGen: 5 })).toBe(false); }); + + test("floorplanner canvas midpoint, hit-testing, vertex edit, label collision, and default pair", () => { + expect(planPolylineMidpoint([])).toBeNull(); + expect(planPolylineMidpoint([[10, 0], [20, 0], [20, 30]])).toEqual([20, 10]); + + expect(planRailColor("+3V3", "#5a7a9a")).toBe("#f59e0b"); + expect(planRailColor("+1V8")).toBe("#c084fc"); + expect(planRailColor("+5V", "#123456")).toBe("#123456"); + expect(planBusColor("USB", "#14b8a6")).toBe("#14b8a6"); + + const cam = planFitCamera([0, 0, 100, 100], 200, 200, 0); + const bands = [{ id: "c1", layer: "In5.Cu", width: 4, locked: false, path: [[10, 50], [90, 50]] as Array<[number, number]> }]; + const regions = [{ + id: "p1", + layer: "In5.Cu", + locked: false, + outline: [[5, 5], [95, 5], [95, 95], [5, 95]] as Array<[number, number]>, + holes: [[[30, 70], [45, 70], [45, 85], [30, 85]]] as Array>, + }]; + expect(planHitTest(bands, regions, "In5.Cu", "c1", cam, 200, 200, 21, 101)).toEqual({ + kind: "vertex", + id: "c1", + isPlane: false, + idx: 0, + }); + expect(planHitTest(bands, regions, "In5.Cu", "c1", cam, 200, 200, 100, 100)?.kind).toBe("midpoint"); + expect(planHitTest(bands, regions, "In5.Cu", "", cam, 200, 200, 120, 100)).toEqual({ kind: "band", id: "c1" }); + expect(planHitTest(bands, regions, "In5.Cu", "", cam, 200, 200, 30, 40)).toEqual({ kind: "region", id: "p1" }); + expect(planHitTest(bands, regions, "In5.Cu", "", cam, 200, 200, 76, 156)).toBeNull(); + + const open: Array<[number, number]> = [[0, 0], [10, 0]]; + expect(planRemoveVertex(open, 0, false)).toBeNull(); + const inserted = planInsertVertex(open, 0, [5, 4], false); + expect(inserted).toEqual([[0, 0], [5, 4], [10, 0]]); + expect(planRemoveVertex(inserted, 1, false)).toEqual(open); + + const tri: Array<[number, number]> = [[0, 0], [10, 0], [10, 10]]; + expect(planRemoveVertex(tri, 0, true)).toBeNull(); + expect(planInsertVertex(tri, 2, [0, 10], true).length).toBe(4); + + const pair = planDefaultLayerPair([ + { layer: "F.Cu", role: "signal", items: [{ id: "a", kind: "corridor" }] }, + { layer: "In3.Cu", role: "power", items: [{ id: "b", kind: "plane" }, { id: "c", kind: "plane" }] }, + { layer: "In5.Cu", role: "signal", items: [{ id: "d", kind: "corridor" }, { id: "e", kind: "corridor" }] }, + ]); + expect(pair).toEqual(["In5.Cu", "In3.Cu"]); + + const labels = planLayoutLabels( + [ + { r: "U1", s: "F", b: [20, 20, 40, 40], o: false }, + { r: "R9", s: "F", b: [26, 26, 34, 34], o: false }, + { r: "U2", s: "F", b: [70, 70, 85, 85], o: false }, + ], + planFitCamera([0, 0, 100, 100], 400, 400, 0), + 400, + 400, + [], + ); + expect(labels.map((l) => l.text)).toEqual(["U1", "U2"]); + }); }); From afa5810942f66a9ce520569e95bc2c384fcdfebb Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 22:10:20 -0500 Subject: [PATCH 2/5] plan: serialize saved-plan writes and preserve plane cutout holes --- native/gpui/src/screens/mgmt_plan_canvas.rs | 17 ++++++- native/host/src/plan/mod.rs | 56 +++++++++++++++++++-- web/dist/assets/app.js | 12 ++--- web/dist/manifest.json | 10 ++-- web/src/mgmt.ts | 18 ++++++- 5 files changed, 96 insertions(+), 17 deletions(-) diff --git a/native/gpui/src/screens/mgmt_plan_canvas.rs b/native/gpui/src/screens/mgmt_plan_canvas.rs index 7a88e20ef6..a6376c3f61 100644 --- a/native/gpui/src/screens/mgmt_plan_canvas.rs +++ b/native/gpui/src/screens/mgmt_plan_canvas.rs @@ -743,7 +743,22 @@ pub fn apply_optimistic(app: &mut Backplane, id: &str, patch: Value) { pub fn commit_item_fields(app: &mut Backplane, id: &str, fields: Value, cx: &mut Context) { apply_optimistic(app, id, fields.clone()); - mgmt_plan::send(app, "plan.update", json!({"ops": [{"op": "set", "id": id, "fields": fields}]}), cx); + let mut wire_fields = fields; + if let Some(outer) = wire_fields.get("outline").cloned() { + if outer.as_array().and_then(|a| a.first()).and_then(|p| p.as_array()).and_then(|p| p.first()).and_then(Value::as_f64).is_some() { + let d = app.screens.mgmt.data("plan"); + let (_, draw) = resolved_board_and_draw(app, &d); + if let Some(holes) = draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == id).and_then(|r| r["holes"].as_array()).filter(|h| !h.is_empty()) { + let mut rings = Vec::with_capacity(1 + holes.len()); + rings.push(outer); + rings.extend(holes.iter().cloned()); + if let Some(obj) = wire_fields.as_object_mut() { + obj.insert("outline".into(), Value::Array(rings)); + } + } + } + } + mgmt_plan::send(app, "plan.update", json!({"ops": [{"op": "set", "id": id, "fields": wire_fields}]}), cx); } fn board_bbox_f32(board: &Value) -> [f32; 4] { diff --git a/native/host/src/plan/mod.rs b/native/host/src/plan/mod.rs index 43b9a75043..f59d0558c3 100644 --- a/native/host/src/plan/mod.rs +++ b/native/host/src/plan/mod.rs @@ -392,6 +392,17 @@ pub fn apply_person_ops(plan: &mut Value, ops: &[Value]) -> Result, for (k, v) in fields { if matches!(k.as_str(), "op" | "id" | "fields") { continue } if k == "layer" { if let Some(s) = v.as_str() { new_layer = s.to_string(); } } + if k == "outline" { + if let (Some(new_rings), Some(old_rings)) = (v.as_array(), obj.get("outline").and_then(Value::as_array)) { + if new_rings.len() == 1 && old_rings.len() > 1 { + let mut merged = Vec::with_capacity(old_rings.len()); + merged.push(new_rings[0].clone()); + merged.extend(old_rings[1..].iter().cloned()); + obj.insert(k.clone(), Value::Array(merged)); + continue; + } + } + } obj.insert(k.clone(), v.clone()); } obj.insert("edited".into(), json!(true)); @@ -496,12 +507,23 @@ pub fn apply_person_approve(plan: &mut Value, layer: &str, ids: &[String], yes: changed } +static PLAN_FILE_LOCK: Mutex<()> = Mutex::new(()); +static PLAN_TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + fn write_plan_file(pcb: &str, plan: &Value) -> Result<(), String> { let f = Path::new(pcb).with_extension("kicad_plan"); - let tmp = f.with_extension("kicad_plan.tmp"); + let seq = PLAN_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = f.with_extension(format!("kicad_plan.{}.{seq}.tmp", std::process::id())); let txt = serde_json::to_string_pretty(plan).map_err(|e| e.to_string())?; - std::fs::write(&tmp, txt).map_err(|e| e.to_string())?; - crate::plat::fs::rename(&tmp, &f).map_err(|e| e.to_string()) + if let Err(e) = std::fs::write(&tmp, txt) { + let _ = std::fs::remove_file(&tmp); + return Err(e.to_string()); + } + if let Err(e) = crate::plat::fs::rename(&tmp, &f) { + let _ = std::fs::remove_file(&tmp); + return Err(e.to_string()); + } + Ok(()) } /// The person's steering edits (the Plan canvas/inspector): sends KiCad's `UpdatePlan` as the person when open, @@ -530,6 +552,7 @@ pub async fn update(hub: &Arc, pcb: &str, base: Option, ops: &[Value]) let f = Path::new(pcb).with_extension("kicad_plan"); let pcb_s = pcb.to_string(); let res = tokio::task::spawn_blocking(move || -> Result<(Value, Vec), String> { + let _guard = PLAN_FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let raw = std::fs::read_to_string(&f).map_err(|_| "no saved routing plan for this board".to_string())?; let mut plan: Value = serde_json::from_str(&raw).map_err(|_| "saved routing plan is not valid JSON".to_string())?; let touched = apply_person_ops(&mut plan, &norm)?; @@ -551,6 +574,7 @@ pub async fn approve(hub: &Arc, pcb: &str, layer: &str, ids: &[String], yes if f.exists() { let (pcb_s, layer_s, ids_v) = (pcb.to_string(), layer.to_string(), ids.to_vec()); let res = tokio::task::spawn_blocking(move || -> Result { + let _guard = PLAN_FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let raw = std::fs::read_to_string(&f).map_err(|e| e.to_string())?; let mut plan: Value = serde_json::from_str(&raw).map_err(|_| "saved routing plan is not valid JSON".to_string())?; let changed = apply_person_approve(&mut plan, &layer_s, &ids_v, yes); @@ -751,4 +775,30 @@ mod tests { assert!(normalize_person_ops(&[json!({"op": "set", "id": "c1", "path": [[0.0, 0.0]]})]).is_err()); assert!(crate::api::RpcHandler::methods(&Rpc).contains(&"plan.update")); } + + #[test] fn plane_outline_edit_preserves_existing_holes() { + let hole = json!([[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]]); + let mut p = json!({ + "revision": 1, + "layers": [{"layer": "In2.Cu", "role": "power", "status": "proposed"}], + "planes": [{"id": "p1", "net": "GND", "layer": "In2.Cu", "outline": [[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]], hole], "status": "proposed"}] + }); + let single_ops = normalize_person_ops(&[ + json!({"op": "set", "id": "p1", "outline": [[0.0, 0.0], [12.0, 0.0], [12.0, 10.0], [0.0, 10.0]]}) + ]).unwrap(); + apply_person_ops(&mut p, &single_ops).unwrap(); + let rings = p["planes"][0]["outline"].as_array().unwrap(); + assert_eq!(rings.len(), 2); + assert_eq!(rings[0], json!([[0.0, 0.0], [12.0, 0.0], [12.0, 10.0], [0.0, 10.0]])); + assert_eq!(rings[1], hole); + + let new_hole = json!([[3.0, 3.0], [5.0, 3.0], [5.0, 5.0]]); + let multi_ops = normalize_person_ops(&[ + json!({"op": "set", "id": "p1", "outline": [[[0.0, 0.0], [14.0, 0.0], [14.0, 10.0]], new_hole]}) + ]).unwrap(); + apply_person_ops(&mut p, &multi_ops).unwrap(); + let rings2 = p["planes"][0]["outline"].as_array().unwrap(); + assert_eq!(rings2.len(), 2); + assert_eq!(rings2[1], new_hole); + } } diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index e0bb51d713..e105306513 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,11 +1,11 @@ -function $t(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function Sn(e){return e==="done"||e==="failed"||e==="cancelled"}function An(e,t){if(!e||e.id!==t.id)return!0;let n=Sn(e.state),i=Sn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Ln(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Pn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ht=Qi(),Gt=new Set,Ut=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function Qi(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Nn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ht}Nn();function Lt(e){return Gt.add(e),()=>{Gt.delete(e)}}function Mn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ht;if(ht=n,Nn(),i)for(let s of Gt)s(ht);return i}function h(e,t,n){let s=(mt[ht]||mt.en||{})[e]??mt.en?.[e]??t??e;return Pn(s,n)}function Ee(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return h(t,e)}function K(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=K("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function es(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ts(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Ot{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=K("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=K("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=K("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=K("div","bp-fb-list"),this.errEl=K("div","bp-ap-err bp-hidden");let a=K("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(K("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(Ee(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(K("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(ts(this.path,n))});i.append(K("span","bp-fb-icon","▸"),K("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(es(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(Ee(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Vt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=K("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=K("div","bp-modal bp-ap"),n=K("div","bp-modal-head"),i=K("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=K("div","bp-ap-tabs"),this.bodyEl=K("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Ot(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=K("div","bp-ap-form"),n=K("div","bp-ap-repo"),i=K("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=K("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=K("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=K("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=K("label","bp-ap-check"),a=K("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,K("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(K("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=K("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=K("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),r.push(o,c),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(c)=>c.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=K("div","bp-ap-sug-top");if(o.append(K("span","bp-ap-sug-name",s.name)),s.private)o.append(K("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(K("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(K("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=K("div","bp-ap-sug-note");if(s.append(K("span","",Ee(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(Ee(t.error)))}else if(t){let r=K("div","bp-ap-where"),o=K("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),r.append(o,c),n.push(r);let m=K("label","bp-ap-name");m.append(K("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let l=K("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(l),n.push(m),!t.ok&&t.error)n.push(this.errLine(Ee(t.error)));else if(t.same)n.push(K("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=K("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Ot(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=$t();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=Ee(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=$t(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=Ee(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Ln(e))this.goTo(e)}renderJobView(){this.jobEl=K("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=K("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[K("div","bp-ap-job-title",s)];if(t.state==="running"){let r=K("div","bp-ap-phase",Ee(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=K("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=K("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(K("div","bp-ap-detail bp-dim",t.detail));let m=K("div","bp-ap-foot"),l=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),m.append(l),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=K("div","bp-ap-err",Ee(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=K("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let c=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),r.append(c),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let l=K("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let u of r)l.appendChild(K("li","",Ee(u)));a.push(l)}let o=K("div","bp-ap-foot"),c=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=Fe(c,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=K("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(K("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(K("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=K("div","bp-ap-code-row"),s=K("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=K("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(K("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(K("div","bp-ap-err",Ee(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ns(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ut(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ns(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,e.appendChild(c)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i=(e.ended??0)}function Ln(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Pn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ht=Qi(),Gt=new Set,Ut=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function Qi(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Nn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ht}Nn();function Lt(e){return Gt.add(e),()=>{Gt.delete(e)}}function Mn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ht;if(ht=n,Nn(),i)for(let s of Gt)s(ht);return i}function h(e,t,n){let s=(mt[ht]||mt.en||{})[e]??mt.en?.[e]??t??e;return Pn(s,n)}function Ee(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return h(t,e)}function z(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=z("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function es(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ts(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Ot{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=z("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=z("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=z("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=z("div","bp-fb-list"),this.errEl=z("div","bp-ap-err bp-hidden");let a=z("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(z("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(Ee(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(z("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(ts(this.path,n))});i.append(z("span","bp-fb-icon","▸"),z("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(es(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(Ee(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Vt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=z("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=z("div","bp-modal bp-ap"),n=z("div","bp-modal-head"),i=z("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=z("div","bp-ap-tabs"),this.bodyEl=z("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Ot(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=z("div","bp-ap-form"),n=z("div","bp-ap-repo"),i=z("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=z("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=z("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=z("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=z("label","bp-ap-check"),a=z("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,z("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(z("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=z("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=z("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),r.push(o,c),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(c)=>c.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=z("div","bp-ap-sug-top");if(o.append(z("span","bp-ap-sug-name",s.name)),s.private)o.append(z("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(z("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(z("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=z("div","bp-ap-sug-note");if(s.append(z("span","",Ee(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(Ee(t.error)))}else if(t){let r=z("div","bp-ap-where"),o=z("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),r.append(o,c),n.push(r);let m=z("label","bp-ap-name");m.append(z("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let l=z("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(l),n.push(m),!t.ok&&t.error)n.push(this.errLine(Ee(t.error)));else if(t.same)n.push(z("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=z("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Ot(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=$t();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=Ee(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=$t(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=Ee(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Ln(e))this.goTo(e)}renderJobView(){this.jobEl=z("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=z("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[z("div","bp-ap-job-title",s)];if(t.state==="running"){let r=z("div","bp-ap-phase",Ee(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=z("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=z("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(z("div","bp-ap-detail bp-dim",t.detail));let m=z("div","bp-ap-foot"),l=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),m.append(l),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=z("div","bp-ap-err",Ee(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=z("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let c=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),r.append(c),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let l=z("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let u of r)l.appendChild(z("li","",Ee(u)));a.push(l)}let o=z("div","bp-ap-foot"),c=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=Fe(c,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=z("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(z("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(z("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=z("div","bp-ap-code-row"),s=z("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=z("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(z("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(z("div","bp-ap-err",Ee(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ns(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ut(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ns(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,e.appendChild(c)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),d.append(p,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=l,f.appendChild(g),u.append(d,f),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let c=document.createElement(`h${Math.min(4,a[1].length+1)}`);c.className="bp-md-h",ut(c,a[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ut(c,m.join(` `)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));ut(o,r[c])}t.appendChild(o)}return t}var Tn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Tn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Tn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function _t(e){return e<10000000000?e*1000:e}function is(e){if(!e)return"";return new Date(_t(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ss(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Wt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class qt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!Wt(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!Wt(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Wt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=h("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let u=is(e.at);if(t)l.textContent=u,i.append(s,...m?[o]:[],l);else{let d=n&&e.at?ss(_t(e.at)-_t(n)):"",p=u?d?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:d}):h("web.chat.finished","Finished {time}",{time:u}):"";l.textContent=e.live?h("web.chat.streaming","Streaming…"):p,i.append(l,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,l.appendChild(u),a.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=a.tool.summary,l.appendChild(d)}r.appendChild(l),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let l=a.ask;if(l.kind==="plan"){r.appendChild(this.renderPlanAsk(l)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,u.appendChild(d),l.state==="open"){let p=document.createElement("div");if(p.className="bp-ask-opts",l.options&&l.options.length>0)for(let b of l.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,b.id)),p.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=h("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=h("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(l.id,b.value.trim())}),p.append(b,y)}u.appendChild(p)}else{let p=document.createElement("div");p.className="bp-ask-answered",p.textContent=h("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),u.appendChild(p)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),c=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!c&&!m&&!a.live)continue;if(a.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};l.addEventListener("click",d),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"||p.key===" ")p.preventDefault(),d()}),r.appendChild(l)}if(o||a.live){let l=document.createElement("div");if(l.className="bp-entry-body",a.kind==="user")l.textContent=a.text;else l.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,l);r.appendChild(l)}if(m&&a.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=u.previewUrl,d.alt=u.name||"attachment",l.appendChild(d)}else if(u.path||u.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=u.name||u.path||"image",l.appendChild(d)}if(l.childElementCount>0)r.appendChild(l)}if(a.images&&a.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let u of a.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=u;let p=`${a.id}|${u}`,b=this.imageCache.get(p);if(b)d.src=b;else this.cb.onLoadImage(a.id,u).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(p,f),d.src=f});l.appendChild(d)}r.appendChild(l)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):Ee(e.head),s.append(a,r),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let u=h("common.copy","Copy"),d=document.createElement("span");d.textContent=u,l.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=u},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let u=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=u?.label&&u.label!=="Implement"?Ee(u.label):h("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),l.appendChild(d),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(y)}let p=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=p?.label&&p.label!=="Dismiss"?Ee(p.label):h("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"dismiss")}),l.appendChild(b),i.appendChild(l),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=h("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let w=()=>{let L=f.value.trim();if(!L)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${L}`)},k=()=>{this.closePlanRevise()};y.addEventListener("keydown",(L)=>{if(L.key==="Escape")L.preventDefault(),L.stopPropagation(),k()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(L)=>{if(L.key==="Enter"&&!L.shiftKey)L.preventDefault(),w()}),g.addEventListener("click",w);let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost",S.textContent=h("common.cancel","Cancel"),S.addEventListener("click",k),y.append(f,g,S),i.appendChild(y)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Bn="http://www.w3.org/2000/svg",In=4,Rn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Kt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function jn(){return Pt(["M6 4l14 8-14 8z"])}function as(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class zt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Kt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let m=c.clipboardData?.items;if(!m)return;let l=[];for(let u=0;u0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=as(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` `)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?jn():Kt()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?jn():Kt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let c=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let l=(u,d,p,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(d?" active":""),y.textContent=u,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(p)),y};m.append(l(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(m)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} ${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Rn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=In){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:In}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Hn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var rs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&rs.has(t.id))}function Gn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var os=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ls=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Un(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(os.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ls.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function On(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Vn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function Wn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Jt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function _n(e){return e.state==="routed"||e.state==="verified"}function qn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Kn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function zn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Jn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Yn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Yt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Xn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Xt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Dn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Fn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Zn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Dn[Zn(i)%Dn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Fn[Zn(e)%Fn.length]}function Qn(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ke(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ei(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ti(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(r,Math.min(o,e.scale*t)),[m,l]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/c,cy:l-(i-a*0.5)/c,scale:c,touched:!0}}function ni(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function ii(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Zt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function cs(e,t,n,i,s,a){let r=s-n,o=a-i,c=r*r+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/c)),l=n+m*r,u=i+m*o;return(e-l)*(e-l)+(t-u)*(t-u)}function $n(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(c-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function Qt(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let p=d.path??[];for(let b=0;b=3)for(let b=0;b=0;d--){let p=t[d];if(p.layer!==n)continue;let b=p.outline??[];if(!$n(l,u,b))continue;if(!(p.holes??[]).some((f)=>$n(l,u,f)))return{kind:"region",id:p.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,c=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((c>0||a.role==="power"||a.role==="plane")&&(!n||c>n.count))n={count:c,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function si(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[l,u]=Ke(t,m.b[0],m.b[1],n,i),[d,p]=Ke(t,m.b[2],m.b[3],n,i),b=Math.abs(d-l),y=Math.abs(p-u);if(b<13||y<9)continue;let f=(l+d)*0.5,g=(u+p)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,l)=>l.score-m.score);let o=[],c=[];for(let m of r){let l=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((d)=>!(l[2]<=d[0]||l[0]>=d[2]||l[3]<=d[1]||l[1]>=d[3])))o.push(l),c.push({text:m.text,cx:m.cx,cy:m.cy})}return c}var ai="#111917",ds="#16201d",ps="rgba(212, 224, 219, 0.92)",ms="rgba(61, 80, 73, 0.72)",hs="rgba(82, 107, 97, 0.85)",us="rgba(143, 163, 155, 0.88)",ri="#f59e0b",bs="#eef5f2",oi="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function gs(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function fs(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function vs(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class en{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){if(e.layers.length===0)return[];if(e.gridMode==="all")return e.layers;if(e.gridMode==="single"){let i=e.shownLayers.find((a)=>e.layers.some((r)=>r.layer===a))??rt(e.layers)[0]??e.layers[0]?.layer,s=e.layers.find((a)=>a.layer===i);return s?[s]:[]}let t=e.shownLayers.length>0&&e.shownLayers.every((i)=>e.layers.some((s)=>s.layer===i))?e.shownLayers.slice(0,2):rt(e.layers),n=[];for(let i of t){let s=e.layers.find((a)=>a.layer===i);if(s)n.push(s)}return n.length>0?n:e.layers.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return Qn(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=h("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,c,m);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let p=document.createElement("div");p.className="bp-plan-hover-hud bp-hidden",u.append(d,p);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=d.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(d,e.layer);let g={layer:e.layer,el:t,canvas:d,ctx:y,legendEl:b,okBtn:c,noBtn:m,statusEl:o,titleEl:r,subtitleEl:l,hoverHudEl:p,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=vs(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let c=document.createElement("button");c.type="button";let m=this.state?.selectedId===o.id;c.className="bp-plan-legend-chip"+(m?" active":"");let l=document.createElement("span");l.className="bp-plan-legend-sw",l.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,c.append(l,u),c.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(c)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(n)=>n.preventDefault()),e.addEventListener("pointerdown",(n)=>{let i=this.state;if(!i)return;this.root.focus();let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r);if(n.button===2){if(l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane),d=Zt(u,l.idx,l.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(l.id,{[l.isPlane?"outline":"path"]:d})}return}if(n.button!==0)return;if(e.setPointerCapture(n.pointerId),this.downPos={x:n.clientX,y:n.clientY},l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane);this.selectedVertex={id:l.id,idx:l.idx},this.cb.onSelect(l.id),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:l.idx,pts:u.map((d)=>[d[0],d[1]])},this.scheduleDraw()}else if(l?.kind==="midpoint"){let u=this.getItemPts(l.id,l.isPlane),d=ii(u,l.segIdx,l.pos,l.isPlane),p=l.isPlane&&l.segIdx+1>=u.length?d.length-1:Math.min(l.segIdx+1,d.length-1);this.cb.onSelect(l.id),this.selectedVertex={id:l.id,idx:p},this.patchLocalItem(l.id,l.isPlane,d),this.cb.onOptimisticPatch(l.id,{[l.isPlane?"outline":"path"]:d}),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:p,pts:d},this.scheduleDraw()}else{if(l&&(l.kind==="band"||l.kind==="region"))this.cb.onSelect(l.id);this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:r}}}),e.addEventListener("pointermove",(n)=>{let i=this.state;if(!i)return;let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let w=this.getCam(t,o,c);this.setCam(t,ei(w,a-this.drag.lastX,r-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=r,this.scheduleDraw();return}let p=this.getCam(t,o,c),[b,y]=Bt(p,a,r,o,c),f=[Math.round(b*1000)/1000,Math.round(y*1000)/1000];this.drag.pts[this.drag.idx]=f;let g=this.drag.pts.map((w)=>[w[0],w[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,g),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:g}),this.scheduleDraw();return}let m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r),u=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=l?l.id:"";if(this.hover=l?{layer:t,hit:l}:null,e.style.cursor=l?.kind==="vertex"||l?.kind==="midpoint"?"pointer":l?"pointer":"crosshair",u!==d||l?.kind!==this.hover?.hit.kind)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerup",(n)=>{let i=this.state,s=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(n.pointerId))e.releasePointerCapture(n.pointerId);if(s&&s.kind==="vertex"&&s.layer===t){this.cb.onCommitFields(s.id,{[s.isPlane?"outline":"path"]:s.pts});return}if(n.detail>=2){this.fitAll();return}if(i&&a&&Math.hypot(n.clientX-a.x,n.clientY-a.y)<4.5){let r=e.getBoundingClientRect(),o=n.clientX-r.left,c=n.clientY-r.top,m=Math.max(1,r.width),l=Math.max(1,r.height),u=this.getCam(t,m,l),d=It(i.bands,i.regions,t,i.selectedId,u,m,l,o,c);if(d&&(d.kind==="band"||d.kind==="region"))this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);else if(!d)this.cb.onSelect("")}}),e.addEventListener("wheel",(n)=>{n.preventDefault();let i=e.getBoundingClientRect(),s=n.clientX-i.left,a=n.clientY-i.top,r=Math.max(1,i.width),o=Math.max(1,i.height),c=this.getCam(t,r,o),m=Math.max(0.65,Math.min(1.55,1-n.deltaY*0.002));this.setCam(t,ti(c,m,s,a,r,o)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),c=Zt(o,this.selectedVertex.idx,r);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),c=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(p,b)=>Ke(a,p,b,n,i);e.fillStyle=ai,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((p)=>p.length>=3);if(e.fillStyle=ds,o.length>0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let p of c){let b=p.outline??[];if(b.length<3)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=fs(p.state||"proposed",y,f),w=ft(p.net||p.id,p.color||"");e.beginPath();for(let k=0;k0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),d=[];for(let p of u){for(let b of p.from??[])d.push(b);for(let b of p.to??[])d.push(b)}e.fillStyle=us,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let p of si(l,a,n,i,d))e.fillText(p.text,p.cx,p.cy);for(let p of u){let b=p.guides??[];if(b.length===0)continue;let y=s.selectedId===p.id||m?.id===p.id,f=vt(p.name||p.id,p.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[w,k]=r(g[0],g[1]),[S,L]=r(g[2],g[3]);e.moveTo(w,k),e.lineTo(S,L)}e.stroke()}for(let p of u){let b=p.path??[];if(b.length<2)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=gs(p.state||"proposed",y,f),w=vt(p.name||p.id,p.color||""),k=Qt(p.width??1.5,a.scale),S=()=>{e.beginPath();for(let M=0;M0){let M=ni(b);if(M){let[B,H]=r(M[0],M[1]),W=String(L),_=Math.max(16,W.length*6.5+8),j=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(B-_*0.5,H-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":w,e.strokeRect(B-_*0.5,H-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,B,H+0.5)}}}if(s.selectedId){let p=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let r=document.createElement("button");r.type="button";let o=this.openPanel===a.id;r.className="bp-mgmt-tab"+(o?" active":""),r.setAttribute("data-testid",`mgmt-tab-${a.id}`),r.setAttribute("aria-pressed",o?"true":"false");let c=document.createElement("span");c.textContent=Ee(a.label),r.appendChild(c);let m=this.getPanelData(a.id),l=Gn(m);if(l){let u=document.createElement("span");u.className=`bp-mgmt-badge bp-tone-${l.tone}`,u.textContent=l.text,r.appendChild(u)}r.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(r)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=h("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,s.appendChild(a)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=Ee(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),m.appendChild(l),e.appendChild(m)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Vn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),c.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),c.appendChild(y)}else{let y=On(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,c.appendChild(f)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",Un(a.footprint??"")].filter(Boolean).join(" · "),p=document.createElement("span");p.className="bp-dim",p.textContent=d;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(p,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=Ee(a.stock.class),u.appendChild(y)}o.append(c,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,p=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Yt(b,o()))return;this.bomLastUndo=!p&&(y.changed??0)>0?{project:d.project,editId:b.editId,refs:d.refs.slice(),field:d.field,was:typeof y.was==="string"?y.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=p?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Yt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(l,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn",p.textContent="Undo",p.addEventListener("click",()=>{c(Xn(d),!0)}),m.appendChild(p)}if(t.append(i,r,m),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),p.textContent=s(d)+(a(d)?" · judged":""),p.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(p)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let d=this.watchGen,p=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:p}).then(()=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(c,m),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let u=Wn(n,this.checksSource);if(u.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let p=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${p}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(d.source)} · ${d.rule}`;let g=document.createElement("span");g.className=`bp-tone-${p}`,g.textContent=String(d.n),b.append(y,f,g),l.appendChild(b);for(let w of d.rows??[]){let k=document.createElement("div");k.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=Ee(w.title??""),k.appendChild(S),w.names||this.checksSelectedId===w.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let M=document.createElement("span");if(M.className="bp-dim bp-mgmt-flex1",M.textContent=w.names??"",L.appendChild(M),this.checksSelectedId===w.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(H)=>{H.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:w.id}).then((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),L.appendChild(B)}k.appendChild(L)}k.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(k)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let m=i[c]??0,l=Jt(c),u=document.createElement("span");u.className=m>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",u.textContent=`${l.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(c,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=a[a.length-1],m=r[r.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${at(c[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,l=Jt(c.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let p=document.createElement("span");p.className="bp-mgmt-strong",p.textContent=Mt(c.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=c.mpn||c.key;let y=document.createElement("span");if(y.className=`bp-tone-${l.tone}`,y.textContent=l.label,d.append(p,b,y),typeof c.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(c.stock),d.appendChild(f)}if(u.appendChild(d),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((f)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(x,C)=>{let I=this.watchGen,G=this.project;this.planStatus="",this.cb.hub.rpc(x,{pro:G,...C}).catch((z)=>{if(I!==this.watchGen||G!==this.project)return;this.planOptimistic.clear(),this.planStatus=z instanceof Error?z.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydratedKey!==i&&this.project){this.planHydratedKey=i;let x=this.watchGen,C=this.project;this.cb.hub.rpc("plan.get",{pro:C,board:!0}).then((I)=>{if(x!==this.watchGen||C!==this.project||!I?.panel)return;this.planHydratedBoard=I.panel.board??null,this.planHydratedDraw=I.panel.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),c.setAttribute("data-testid","mgmt-plan-off"),c.setAttribute("aria-pressed",!a?"true":"false"),c.textContent=h("gpui.bots.recall.off","Off"),c.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,c),e.appendChild(s);for(let x of t.elsewhere??[]){let C=document.createElement("div");C.className="bp-plan-elsewhere";let I=document.createElement("span");I.className="bp-tone-warn bp-mgmt-flex1",I.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:x.name||x.rel||""}),C.appendChild(I),e.appendChild(C)}if(t.empty){let x=document.createElement("div");x.className="bp-mgmt-note";let C=document.createElement("div");C.className="bp-dim",C.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let I=document.createElement("div");return I.className="bp-mgmt-faint",I.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),x.append(C,I),e.appendChild(x),e}let m=t.awaiting??0,l=t.blocked??0,u=t.done??0,d=t.total??0,p=t.revision??0,b=Kn(t),y=zn(t),f=y.reduce((x,C)=>x+C.count,0),g=document.createElement("div");g.className="bp-plan-status";let w=document.createElement("div");w.className="bp-plan-status-top";let k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${b.tone}`,k.textContent=h(b.key,b.label),w.appendChild(k),p>0){let x=document.createElement("span");x.className="bp-dim",x.textContent=`v${p}`,w.appendChild(x)}let S=document.createElement("span");if(S.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":l>0?"bp-tone-bad":"bp-dim"),S.textContent=d>0?`${u}/${d} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),w.appendChild(S),!t.live){let x=document.createElement("span");x.className="bp-mgmt-pill",x.textContent=h("gpui.mgmt.plan.saved","saved plan"),w.appendChild(x)}if(g.appendChild(w),f>0){let x=document.createElement("div");x.className="bp-plan-segbar";for(let C of y){if(C.count<=0)continue;let I=document.createElement("div");I.className=`bp-plan-seg bp-tone-bg-${C.tone}`,I.style.flexGrow=String(C.count),x.appendChild(I)}g.appendChild(x)}e.appendChild(g);let L=document.createElement("div");if(L.className="bp-mgmt-head",m>0){let x=document.createElement("button");x.type="button",x.className="primary bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-approve-all"),x.textContent=h("gpui.mgmt.plan.all","Approve all"),x.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(x)}if(t.routing){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-stop"),x.textContent=h("gpui.mgmt.plan.stop","Stop routing"),x.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(x)}if(t.live&&u>0){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-verify"),x.textContent=h("gpui.mgmt.plan.verify","Verify"),x.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(x)}let M=document.createElement("span");M.className="bp-mgmt-flex1";let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.setAttribute("data-testid","mgmt-plan-hide"),B.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),B.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.append(M,B),e.appendChild(L);let H=Array.isArray(t.asks)?t.asks:[];if(H.length>0){let x=H.map((me)=>me.what||"").filter(Boolean).join(", "),C=H[0]?.note||"",I=document.createElement("div");I.className="bp-plan-elsewhere";let G=document.createElement("div");G.className="bp-plan-ask-col";let z=document.createElement("div");if(z.className="bp-tone-warn",z.textContent=x?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:x}):h("gpui.mgmt.plan.reqplain","Approval requested"),G.appendChild(z),C){let me=document.createElement("div");me.className="bp-dim",me.textContent=C,G.appendChild(me)}I.appendChild(G),e.appendChild(I)}if(this.planStatus){let x=document.createElement("div");x.className="bp-mgmt-note bp-plan-err bp-tone-bad";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):Ee(this.planStatus);let I=document.createElement("button");I.type="button",I.className="icon",I.textContent="×",I.title=h("common.close","Close"),I.addEventListener("click",()=>{this.planStatus="",this.render()}),x.append(C,I),e.appendChild(x)}if(t.keys_note){let x=document.createElement("div");x.className="bp-mgmt-note bp-dim";let C="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";x.textContent=t.keys_note===C?h("gpui.mgmt.plan.keysnote",C):Ee(t.keys_note),e.appendChild(x)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let x=document.createElement("div");x.className="bp-plan-stackup";let C=document.createElement("button");C.type="button",C.className="bp-plan-stackup-head",C.setAttribute("data-testid","mgmt-plan-stackup-toggle"),C.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let I=document.createElement("span");I.className="bp-plan-chev",I.textContent=this.planStackupOpen?"▾":"▸";let G=document.createElement("span");if(G.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),C.append(I,G),C.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),x.appendChild(C),this.planStackupOpen){let z=document.createElement("div");if(z.className="bp-plan-stackup-body",z.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let me=document.createElement("div");me.className="bp-dim",me.textContent=W,z.appendChild(me)}for(let me of _){let N=document.createElement("div");N.className="bp-mgmt-faint",N.textContent=`· ${me}`,z.appendChild(N)}x.appendChild(z)}e.appendChild(x)}let j=(x,C,I,G)=>{let z=document.createElement("button");return z.type="button",z.className="bp-mgmt-btn bp-plan-chip-btn"+(C?" active":""),z.setAttribute("data-testid",I),z.setAttribute("aria-pressed",C?"true":"false"),z.textContent=x,z.addEventListener("click",G),z},pe=document.createElement("div");if(pe.className="bp-plan-viewbar",pe.append(j(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),j(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),j(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let x=document.createElement("span");x.className="bp-plan-sep";let C=document.createElement("span");C.className="bp-plan-sep";let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn bp-plan-mini-btn",I.setAttribute("data-testid","mgmt-plan-fit"),I.textContent=h("gpui.mgmt.plan.fit","Fit"),I.addEventListener("click",()=>this.planCanvas?.fitAll()),pe.append(x,j(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),j(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),j(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),C,j(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),I)}let le=document.createElement("span");le.className="bp-mgmt-flex1";let ie=document.createElement("button");ie.type="button",ie.className="bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-expand"),ie.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),ie.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),pe.append(le,ie),e.appendChild(pe);let ye=this.planHydratedKey===i&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ke=this.planHydratedKey===i&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Ne=(ke.bands??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),ve=(ke.regions??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),Me=[],T=(t.layers??[]).map((x)=>{let C=[];for(let I of x.items??[]){let G=this.planOptimistic.get(I.id);if(!G){C.push(I);continue}let z={...I,width:typeof G.width==="number"?G.width:I.width,locked:typeof G.locked==="boolean"?G.locked:I.locked,edited:!0,state:I.state==="proposed"?"edited":I.state};if(typeof G.layer==="string"&&G.layer!==x.layer)Me.push({target:G.layer,item:z});else C.push(z)}return{...x,items:C}});for(let x of Me){let C=T.find((I)=>I.layer===x.target);if(C)C.items=[...C.items??[],x.item]}let re=this.planGridMode==="all"?T.map((x)=>x.layer):this.planGridMode==="single"?[this.planShownLayers.find((x)=>T.some((C)=>C.layer===x))??rt(T)[0]??T[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((x)=>T.some((C)=>C.layer===x))?this.planShownLayers.slice(0,2):rt(T);if(this.planViewMode!=="list"&&T.length>1){let x=document.createElement("div");x.className="bp-plan-layerbar";for(let C of T){let I=re.includes(C.layer);x.appendChild(j(C.title||C.layer,I,`mgmt-plan-layerpill-${C.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"){if(!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}else this.planGridMode="single",this.planShownLayers=[C.layer];this.render()}))}e.appendChild(x)}let ae=(x,C)=>{let I=this.planOptimistic.get(x)??{};if(this.planOptimistic.set(x,{...I,...C}),typeof C.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"&&!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}this.render(),n("plan.update",{ops:[{op:"set",id:x,fields:C}]})};if(this.planSelectedId){let x="",C=null;for(let I of T){let G=(I.items??[]).find((z)=>z.id===this.planSelectedId);if(G){x=I.layer,C=G;break}}if(C){let I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let G=document.createElement("div");G.className="bp-plan-ins-row";let z=document.createElement("span");z.className="bp-plan-ins-sw",z.style.background=C.kind==="corridor"?vt(C.name||C.id,C.color||""):ft(C.name||C.id,C.color||"");let me=document.createElement("span");me.className="bp-mgmt-strong",me.textContent=C.name||C.id;let N=document.createElement("span");if(N.className="bp-dim",N.textContent=x,G.append(z,me,N),C.edited||C.state==="edited"){let ee=document.createElement("span");ee.className="bp-plan-ins-pill warn",ee.textContent=h("gpui.mgmt.plan.edited","Edited"),G.appendChild(ee)}if(C.locked){let ee=document.createElement("span");ee.className="bp-plan-ins-pill",ee.textContent=h("gpui.mgmt.plan.locked","Locked"),G.appendChild(ee)}let Y=document.createElement("span");Y.className="bp-mgmt-flex1",G.appendChild(Y);let Ie=document.createElement("button");if(Ie.type="button",Ie.className="bp-mgmt-btn bp-plan-mini-btn",Ie.setAttribute("data-testid","mgmt-plan-lock"),Ie.textContent=C.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),Ie.addEventListener("click",()=>ae(C.id,{locked:!C.locked})),G.appendChild(Ie),C.state==="proposed"||C.state==="edited"){let ee=document.createElement("button");ee.type="button",ee.className="primary bp-mgmt-btn bp-plan-mini-btn",ee.textContent=h("android.hub.machines.approve","Approve"),ee.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!0}));let be=document.createElement("button");be.type="button",be.className="bp-mgmt-btn bp-plan-mini-btn",be.textContent=h("gpui.mgmt.plan.reject","Reject"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!1})),G.append(ee,be)}let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-note-toggle"),Ae.textContent=h("gpui.mgmt.plan.addnote","Add note"),Ae.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let de=document.createElement("button");if(de.type="button",de.className="icon",de.textContent="×",de.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),G.append(Ae,de),I.appendChild(G),!C.locked){let ee=document.createElement("div");if(ee.className="bp-plan-ins-row",C.kind==="corridor"){let Te=typeof C.width==="number"?C.width:1.5,ue=document.createElement("span");ue.className="bp-dim",ue.textContent=h("gpui.mgmt.plan.width","Width");let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn bp-plan-mini-btn",te.setAttribute("data-testid","mgmt-plan-w-down"),te.textContent="-",te.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,Te-0.25)*100)/100;ae(C.id,{width:Ue})});let je=document.createElement("span");je.className="bp-plan-ins-val",je.textContent=`${Te.toFixed(2)}mm`;let Z=document.createElement("button");Z.type="button",Z.className="bp-mgmt-btn bp-plan-mini-btn",Z.setAttribute("data-testid","mgmt-plan-w-up"),Z.textContent="+",Z.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,Te+0.25)*100)/100;ae(C.id,{width:Ue})});let Ce=document.createElement("span");Ce.className="bp-plan-sep",ee.append(ue,te,je,Z,Ce)}let be=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((Te)=>Te.layer):T.map((Te)=>Te.layer);if(be.length>0){let Te=document.createElement("span");Te.className="bp-dim",Te.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),ee.appendChild(Te);for(let ue of be)ee.appendChild(j(ue,ue===x,`mgmt-plan-move-${ue}`,()=>{if(ue!==x)ae(C.id,{layer:ue})}))}I.appendChild(ee)}if(this.planNoteOpen){let ee=document.createElement("form");ee.className="bp-plan-note-form";let be=document.createElement("input");be.type="text",be.className="bp-plan-note-input",be.setAttribute("data-testid","mgmt-plan-note-input"),be.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let Te=document.createElement("button");Te.type="submit",Te.className="primary bp-mgmt-btn bp-plan-mini-btn",Te.setAttribute("data-testid","mgmt-plan-note-submit"),Te.textContent=h("gpui.mgmt.plan.addnote","Add note"),ee.append(be,Te),ee.addEventListener("submit",(ue)=>{ue.preventDefault();let te=be.value.trim();if(!te)return;be.value="",this.planNoteOpen=!1,this.render(),n("plan.update",{ops:[{op:"note",id:C.id,text:te}]})}),I.appendChild(ee)}if(this.planViewMode!=="list"&&!C.locked){let ee=document.createElement("div");ee.className="bp-plan-hint",ee.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(ee)}e.appendChild(I)}}let J=document.createElement("div");J.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),J.setAttribute("data-testid","mgmt-plan-rows");let ce=h("gpui.mgmt.plan.done","done");for(let x of T){let C=x.items??[],I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let G=document.createElement("div");G.className="bp-mgmt-row-line";let z=document.createElement("span");z.className="bp-mgmt-strong",z.textContent=x.layer;let me=document.createElement("span");if(me.className="bp-dim bp-mgmt-flex1",me.textContent=`${x.role?`${x.role} · `:""}${x.done??0}/${C.length} ${ce}`,G.append(z,me),x.status!=="approved"&&C.length>0){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.plan.layer","Approve layer"),N.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!0}));let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent=h("gpui.mgmt.plan.reject","Reject"),Y.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!1})),G.append(N,Y)}if(I.appendChild(G),x.stackup){let N=document.createElement("div");N.className="bp-plan-layer-stackup",N.textContent=x.stackup,I.appendChild(N)}J.appendChild(I);for(let N of C){if(this.planHideDone&&_n(N))continue;let Y=this.planSelectedId===N.id,Ie=document.createElement("div");Ie.className="bp-mgmt-row bp-plan-row"+(Y?" active":""),Ie.setAttribute("data-testid",`mgmt-plan-row-${N.id}`);let Ae=document.createElement("div");Ae.className="bp-mgmt-row-line";let de=document.createElement("span");de.className=`bp-plan-swatch bp-plan-st-${N.state||"proposed"}`,de.style.setProperty("--swatch-color",N.color||"#8a8a8a");let ee=document.createElement("span");ee.className="bp-mgmt-flex1"+(N.state==="blocked"||N.state==="failed"?" bp-tone-bad":N.state==="edited"?" bp-tone-warn":N.state==="rejected"||N.state==="routed"||N.state==="verified"?" bp-dim":""),ee.textContent=`${N.name||N.id}${N.locked?" \uD83D\uDD12":""}`;let be=[];if(N.kind==="plane"){if(N.reference)be.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:N.reference}))}else{let te=N.nets??0;be.push(te===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:te}))}if(typeof N.width==="number"&&Number.isFinite(N.width))be.push(`${N.width.toFixed(2)}mm`);if(N.impedance)be.push(N.impedance);let Te=be.join(" · "),ue=document.createElement("span");if(ue.className="bp-plan-mark "+(N.state==="blocked"||N.state==="failed"?"bp-tone-bad":N.state==="verified"||N.state==="routed"?"bp-tone-ok":N.state==="approved"?"bp-tone-accent":"bp-dim"),ue.textContent=qn(N),Ae.append(de,ee,ue),N.state==="proposed"||N.state==="edited"){let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn",te.textContent="✓",te.title=h("gpui.mgmt.plan.layer","Approve layer"),te.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!0})});let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent="✗",je.title=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!1})}),Ae.append(te,je)}if(Ie.appendChild(Ae),Te){let te=document.createElement("div");te.className="bp-mgmt-row-sub bp-plan-detail bp-dim",te.textContent=Te,Ie.appendChild(te)}if(N.state==="routing"&&typeof N.total==="number"&&N.total>0){let te=document.createElement("div");te.className="bp-plan-microbar";let je=document.createElement("div");je.className="bp-plan-microbar-fill";let Z=Math.max(0,Math.min(100,Math.round((N.routed??0)/N.total*100)));je.style.width=`${Z}%`,te.appendChild(je),Ie.appendChild(te)}if(N.problem_text){let te=document.createElement("div");te.className="bp-plan-problem",te.textContent=N.problem_text,Ie.appendChild(te)}Ie.addEventListener("click",()=>{this.planSelectedId=N.id,n("plan.focus",{id:N.id}),this.render()}),J.appendChild(Ie)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new en({onSelect:(G)=>{if(this.planSelectedId=G,!G)this.planNoteOpen=!1;this.render()},onFocusItem:(G)=>{n("plan.focus",{id:G})},onOptimisticPatch:(G,z)=>{let me=this.planOptimistic.get(G)??{};this.planOptimistic.set(G,{...me,...z})},onCommitFields:(G,z)=>{ae(G,z)},onApproveLayer:(G,z)=>{n("plan.approve",{layer:G,ids:[],approve:z})},onQuickApprove:(G,z)=>{n("plan.approve",{layer:"",ids:G,approve:z})}});let x=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,C=this.planExpanded||this.panelEl.clientWidth>=540||x;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:re,selectedId:this.planSelectedId,board:ye,bands:Ne,regions:ve,layers:T},C);let I=document.createElement("div");I.className="bp-plan-canvas-scroll",I.appendChild(this.planCanvas.root),e.appendChild(I)}if(this.planViewMode!=="canvas")e.appendChild(J);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let x=document.createElement("div");x.className="bp-plan-footer",x.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(x)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,k={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:w,...k}).catch((M)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=M instanceof Error?M.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Yn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(c?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(u),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}m.appendChild(l),o.appendChild(m);let p=Jn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(p.button?"bp-tone-warn":"bp-dim"),f.textContent=p.text,y.appendChild(f),p.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=p.button,w.addEventListener("click",()=>n("drc")),y.appendChild(w)}b.appendChild(y),o.appendChild(b);for(let w of t.conflicts??[]){let k=document.createElement("div");k.className="bp-mgmt-row bp-tone-bad",k.textContent=w,o.appendChild(k)}for(let w of t.suggestions??[]){let k=document.createElement("div");k.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.apply","Apply"),M.addEventListener("click",()=>n("apply",{key:w.key})),S.append(L,M),k.appendChild(S),o.appendChild(k)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,k.appendChild(L),S){let M=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=h("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:M})),k.appendChild(B)}w.appendChild(k),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=h("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),k.append(S,L),w.appendChild(k);for(let M of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=M,w.appendChild(B)}o.appendChild(w)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=h("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=h("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=h("gpui.mgmt.fab.extra","Costs more");let M=document.createElement("span");M.className="bp-mgmt-col bp-mgmt-col-read",M.textContent=h("gpui.mgmt.fab.readcol","Read"),w.append(k,S,L,M),o.appendChild(w);for(let H of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let j=document.createElement("span");j.className="bp-mgmt-flex1"+(H.changed?" bp-tone-warn":H.inherited?" bp-dim":""),j.textContent=`${H.changed?"• ":""}${H.label??""}`;let pe=document.createElement("span");pe.className="bp-mgmt-col",pe.textContent=H.free?.text||"—";let le=document.createElement("span");le.className="bp-mgmt-col bp-dim",le.textContent=H.extra?.text||"—";let ie=H.free&&typeof H.free==="object"?H.free:H.extra,ye=ie?.fetched??"",ke=Boolean(ye)&&ie?.confidence!=="published",Ne=ye?ke?`${ye}*`:ye:"—",ve=ie?.source??"",Me;if(ve.startsWith("https://")&&ye){let T=document.createElement("a");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",T.href=ve,T.target="_blank",T.rel="noopener noreferrer",T.textContent=Ne,Me=T}else{let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",T.textContent=Ne,Me=T}_.append(j,pe,le,Me),W.appendChild(_),o.appendChild(W)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(B)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var ys={trs:(e)=>e,t:(e,t)=>t},ws=new Set(["/settle"]);function li(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function di(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function pi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function mi(e,t=ys){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let c=ws.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:m}=ci(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:di(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function hi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let b of i)d.set(b.id,b.title||b.id);let p=new Set;for(let b of c)if(b.action.type==="thread")p.add(b.action.id);for(let b of n.threads){if(!b.id||p.has(b.id))continue;p.add(b.id);let{urgency:y,want:f}=ci(b);c.push({label:b.title||"Untitled thread",place:b.project?d.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:di(b),action:{type:"thread",id:b.id}})}}let m=[];for(let d=0;d0)m.push({score:f,index:d,item:p})}m.sort((d,p)=>{if(o){let f=(p.item.urgency??0)-(d.item.urgency??0);if(f!==0)return f}if(p.score!==d.score)return p.score-d.score;let b=d.item.kind==="thread"?0:1,y=p.item.kind==="thread"?0:1;if(b!==y)return b-y;return d.index-p.index});let l=new Set,u=[];for(let d of m){let p=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(p))continue;if(l.add(p),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=mi(t,{t:h,trs:Ee}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=hi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,d)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(d,p),m.appendChild(b),p{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var xs=new Set(["resume","raise","retry","move","signin"]);function gi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Rt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(xs.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function fi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class an{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";p.textContent=b,d.appendChild(p);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(d.appendChild(y),u.appendChild(d),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(l,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let c=document.createElement("div");c.className="bp-set-head",c.textContent="Paired devices",o.appendChild(c);try{let m=await this.cb.onLoadDevices();if(m.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",o.appendChild(l)}else for(let l of m){let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div");if(p.textContent=l.title||l.head||"",d.appendChild(p),l.text||l.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=l.text||l.detail||"",d.appendChild(b)}if(u.appendChild(d),l.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of l.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let l=document.createElement("div");l.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";l.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(l)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function rn(e){return xe("pre","bp-context-code",e)}function Cs(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,Ee(e))}function jt(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),Cs(t)),n}class on{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(jt(t.path,t.status),xe("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,rn(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),rn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,Ee(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(jt(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(jt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(jt(s.name,s.status),rn(a)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=xe("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var vi="http://www.w3.org/2000/svg";function yi(){let e=document.createElementNS(vi,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(vi,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function ks(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function wi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class ln{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=h("thread.new","New thread"),c.setAttribute("aria-label",h("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),r.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${ks(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?gi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,c.appendChild(m);for(let u of r.actions){if(!Rt(u,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=u.label,d.setAttribute("data-testid",`need-${u.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(p)=>{p.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=l,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),c.appendChild(m);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(r.kind==="projects"){let o=r.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!c&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,d=r.open?"▾":"▸";if(l.textContent=`${r.title.toUpperCase()} (${u}) ${d}`,r.hint)l.title=r.hint;l.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(l)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!c||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",m.appendChild(l)}for(let l of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(l.off?" bp-dim":""),u.setAttribute("data-project-id",l.id),l.nav||l.key)u.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let p=document.createElement("button");p.type="button",p.className="bp-proj-toggle";let b=yi();if(l.css)b.style.color=l.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=l.title||l.id,p.append(b,y),l.fold==="project-fold"&&l.nav)p.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${l.id}`),l.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(p,f),u.appendChild(d),!l.folded||Boolean(t)){let g=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:wi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,m=yi();if(i.css)m.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(m,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!c)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:wi(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let l of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`@${l.name}`,u.append(d,p),u.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(c,m),r.appendChild(o);for(let l of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,u.appendChild(d),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ss(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function As(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?c/m:0));s[a]=l<0?l*32768:l*32767}return s}class cn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ss(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),c=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=As(r.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var Ei=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],xi=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ci=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ki=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ls=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[c]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ps=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Ns=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class dn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},r=(u)=>{let d=0,p=0,b=0;for(let y=1;y<=u.maxBits;y++){d|=a(1);let f=u.counts[y];if(d-f{let d=c+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let p=o.length;while(p{m(1),o[c++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let p=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(p^65535)!==b)throw Error("invalid stored block length");if(n+p>e.length)throw Error("truncated stored payload");m(p);for(let y=0;y=e.length)break}else if(d===1||d===2){let p=Ps,b=Ns;if(d===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,w=new Uint8Array(19);for(let B=0;BS)throw Error("code length overflow");for(let _=0;_S)throw Error("code length overflow");M+=H}else if(B===18){let H=a(7)+11;if(M+H>S)throw Error("code length overflow");M+=H}else throw Error("invalid code length symbol")}p=Et(L,y),b=Et(L.subarray(y),f)}while(!0){let y=r(p);if(y<256)l(y);else if(y===256)break;else{let f=y-257;if(f>=Ei.length)throw Error("invalid length symbol");let g=Ei[f]+(xi[f]?a(xi[f]):0),w=r(b);if(w>=Ci.length)throw Error("invalid distance symbol");let k=Ci[w]+(ki[w]?a(ki[w]):0);m(g);let S=this.winPos-k&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new dn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(c))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ms=new TextDecoder;function Si(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ai(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let l=e.subarray(t,t+m);return t+=m,l}case 3:{if(t+m>e.length)return null;let l=Ms.decode(e.subarray(t,t+m));return t+=m,l}case 4:{if(m>e.length)return null;let l=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Pi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,c=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Li(m),u=[],d=[],p=0,b=0;while(l.more()){let y=l.nextU32(),f=u.length,g=1/0,w=1/0,k=-1/0,S=-1/0;if(a===2)p=p+l.nextI32()|0,b=b+l.nextI32()|0,u.push(p,b),g=k=p,w=S=b;else{let M=Math.min(l.nextU32(),1048576);for(let B=0;Bk)k=p;if(bS)S=b}}let L=(u.length-f)/2;if(L>0){let M=a===2||L===1?2:a===0?0:1,B=a===0?0:o;d.push({info:y,x0:g-B,y0:w-B,x1:k+B,y1:S+B,at:f,n:L,kind:M})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:c,pts:new Float32Array(u),pieces:d}}function Ni(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Mi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,c=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,l=(t-c)/r;if(m<0||m>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ti=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Bi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class mn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Ii(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,c=!1,m=-1,l=null,u=new mn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let p=document.createElement("div");p.className="bp-pane-bar bp-browser-nav";function b(J,ce,x){let C=document.createElement("button");if(C.type="button",C.className="bp-v-btn",C.textContent=J,C.setAttribute("data-testid",ce),x)C.title=x;return C}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let k=document.createElement("input");k.type="text",k.className="bp-browser-input",k.placeholder="https://…",k.autocomplete="off",k.spellcheck=!1,k.setAttribute("data-testid","browser-url");let S=b("Go","browser-go","Navigate");S.type="submit",w.append(k,S);let L=b("Take over","browser-takeover");L.classList.add("is-primary"),p.append(y,f,g,w,L);let M=document.createElement("div");M.className="bp-browser-drive-bar",M.hidden=!0;let B=document.createElement("div");B.className="bp-browser-keys-row";let H=document.createElement("input");H.type="text",H.className="bp-browser-input",H.placeholder="Type text or press Enter/Tab/Arrows…",H.autocomplete="off",H.spellcheck=!1,H.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");B.append(H,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[J,ce]of Ti){let x=b(J,`browser-key-${ce}`);x.addEventListener("click",()=>ve("press",{key:ce})),_.append(x)}M.append(B,_);let j=document.createElement("div");j.className="bp-browser-err",j.setAttribute("data-testid","browser-error"),j.hidden=!0;let pe=document.createElement("div");pe.className="bp-browser-stage",pe.setAttribute("data-testid","browser-stage");let le=document.createElement("img");le.className="bp-browser-img",le.alt="Hub browser screen",le.draggable=!1,le.hidden=!0,le.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",pe.append(le,ie);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,d.append(p,M,j,pe,ye),e.replaceChildren(d);function ke(J){j.textContent=J,j.hidden=!J}function Ne(){M.hidden=!s,ye.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),le.classList.toggle("is-driving",s)}function ve(J,ce={},x){u.enqueue(async()=>{if(!i)return;ke("");try{if(await t.hub.rpc("browser",{thread:n,op:J,...ce}),!i)return;x?.(),re()}catch(C){if(!i)return;ke(C instanceof Error?C.message:String(C))}})}function Me(J){ve("toolbar",{command:J},()=>{s=!0,Ne()})}y.addEventListener("click",()=>Me("back")),f.addEventListener("click",()=>Me("forward")),g.addEventListener("click",()=>Me("reload")),w.addEventListener("submit",(J)=>{J.preventDefault();let ce=Bi(k.value);if(!ce)return;if(k.value=ce,!s)ve("takeover",{},()=>{s=!0,Ne()});ve("navigate",{url:ce},()=>{s=!0,Ne()})}),L.addEventListener("click",()=>{if(s)ve("handback",{},()=>{s=!1,Ne()});else ve("takeover",{},()=>{s=!0,Ne(),H.focus()})});function T(){let J=H.value;if(!J)return;H.value="",ve("type",{text:J})}W.addEventListener("click",T),H.addEventListener("keydown",(J)=>{if(!s)return;if(J.key==="Enter"){if(J.preventDefault(),H.value)T();ve("press",{key:"Enter"});return}if(J.key==="Tab"||J.key==="Escape"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="ArrowLeft"||J.key==="ArrowRight"||J.key==="Backspace"&&H.value==="")J.preventDefault(),ve("press",{key:J.key})}),le.addEventListener("click",(J)=>{if(!s||!a)return;let ce=le.getBoundingClientRect(),x=Mi(J.clientX,J.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:le.naturalWidth,naturalHeight:le.naturalHeight});if(!x)return;ve("click",x)}),le.addEventListener("wheel",(J)=>{if(!s||!a)return;J.preventDefault();let ce=Math.round(J.deltaX),x=Math.round(J.deltaY);if(ce===0&&x===0)return;ve("scroll",{dx:ce,dy:x})},{passive:!1});async function re(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let J=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(J.ok){let ce=await J.blob();if(!i)return;let x=URL.createObjectURL(ce),C=r;if(r=x,le.src=x,le.hidden=!1,ie.hidden=!0,a=!0,C)URL.revokeObjectURL(C)}else if(!a)le.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!a)le.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let ae=t.hub.onFrame((J)=>{if(!i)return;if(J.t==="shot"&&J.bot===n){if(typeof J.n==="number"){if(J.n===m)return;m=J.n}re()}});return re(),{destroy(){if(i=!1,ae(),l?.abort(),r)URL.revokeObjectURL(r),r=""}}}function O(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ht(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function ji(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Bs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ri(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Is(e){let t=ji(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Hi(e,t,n,i){let s=!0,a="",r="",o=O("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=O("div","bp-pane-bar"),m=O("div","bp-files-crumbs"),l=O("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void f(a)),c.append(m,l);let u=O("div","bp-files-split"),d=O("div","bp-files-list");d.setAttribute("data-testid","files-list");let p=O("div","bp-files-preview");p.setAttribute("data-testid","files-preview"),p.append(O("div","bp-pane-empty","Select a file to preview")),u.append(d,p),o.append(c,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=O("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let w=a.split("/").filter(Boolean),k="";for(let S of w){k=k?`${k}/${S}`:S;let L=k;m.append(O("span","bp-vh-sep","/"));let M=O("button","bp-crumb-btn",S);M.type="button",M.addEventListener("click",()=>void f(L)),m.append(M)}}async function y(g,w,k){r=g,p.replaceChildren();let S=O("div","bp-files-prev-head");S.append(O("span","bp-files-prev-name",g));let L=O("div","bp-files-prev-acts"),M=Is(w);if(M){let _=O("button","bp-v-btn is-primary",`Open in ${M}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(M,g)),L.append(_)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,H=O("a","bp-v-btn","Download");H.href=B,H.download=w,L.append(H),S.append(L),p.append(S);let W=ji(w);if(Bs(W)){let _=O("div","bp-files-img-wrap"),j=document.createElement("img");j.className="bp-files-img",j.alt=w,j.src=B,_.append(j),p.append(_);return}if(k>524288&&!Ri(W)){p.append(O("div","bp-pane-empty",`Binary file (${Ht(k)}). Use Download to save.`));return}if(Ri(W)||k<=65536){let _=O("div","bp-pane-empty","Loading…");p.append(_);try{let j=await fetch(B,{credentials:"same-origin"});if(!s||r!==g)return;if(!j.ok){_.textContent=`Could not load file (${j.status})`;return}if((j.headers.get("content-type")||"").startsWith("image/")){_.remove();let ae=document.createElement("img");ae.className="bp-files-img",ae.alt=w,ae.src=B,p.append(ae);return}let le=262144,ie=[],ye=0,ke=!1;if(j.body){let ae=j.body.getReader();try{while(!0){let{done:J,value:ce}=await ae.read();if(J||!ce)break;if(ye+ce.byteLength>le){let x=le-ye;if(x>0)ie.push(ce.subarray(0,x)),ye+=x;ke=!0,await ae.cancel();break}ie.push(ce),ye+=ce.byteLength}}finally{ae.releaseLock()}}if(!s||r!==g)return;let Ne=new Uint8Array(ye),ve=0;for(let ae of ie)Ne.set(ae,ve),ve+=ae.byteLength;let Me=!1;for(let ae=0;aei.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Rn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=In){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:In}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Hn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var rs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&rs.has(t.id))}function Gn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var os=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ls=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Un(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(os.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ls.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function On(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Vn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function Wn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Jt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function _n(e){return e.state==="routed"||e.state==="verified"}function qn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Kn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function zn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Jn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Yn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Yt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Xn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Xt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Dn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Fn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Zn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Dn[Zn(i)%Dn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Fn[Zn(e)%Fn.length]}function Qn(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ke(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ei(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ti(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(r,Math.min(o,e.scale*t)),[m,l]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/c,cy:l-(i-a*0.5)/c,scale:c,touched:!0}}function ni(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function ii(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Zt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function cs(e,t,n,i,s,a){let r=s-n,o=a-i,c=r*r+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/c)),l=n+m*r,u=i+m*o;return(e-l)*(e-l)+(t-u)*(t-u)}function $n(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(c-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function Qt(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let p=d.path??[];for(let b=0;b=3)for(let b=0;b=0;d--){let p=t[d];if(p.layer!==n)continue;let b=p.outline??[];if(!$n(l,u,b))continue;if(!(p.holes??[]).some((f)=>$n(l,u,f)))return{kind:"region",id:p.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,c=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((c>0||a.role==="power"||a.role==="plane")&&(!n||c>n.count))n={count:c,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function si(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[l,u]=Ke(t,m.b[0],m.b[1],n,i),[d,p]=Ke(t,m.b[2],m.b[3],n,i),b=Math.abs(d-l),y=Math.abs(p-u);if(b<13||y<9)continue;let f=(l+d)*0.5,g=(u+p)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,l)=>l.score-m.score);let o=[],c=[];for(let m of r){let l=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((d)=>!(l[2]<=d[0]||l[0]>=d[2]||l[3]<=d[1]||l[1]>=d[3])))o.push(l),c.push({text:m.text,cx:m.cx,cy:m.cy})}return c}var ai="#111917",ds="#16201d",ps="rgba(212, 224, 219, 0.92)",ms="rgba(61, 80, 73, 0.72)",hs="rgba(82, 107, 97, 0.85)",us="rgba(143, 163, 155, 0.88)",ri="#f59e0b",bs="#eef5f2",oi="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function gs(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function fs(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function vs(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class en{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){if(e.layers.length===0)return[];if(e.gridMode==="all")return e.layers;if(e.gridMode==="single"){let i=e.shownLayers.find((a)=>e.layers.some((r)=>r.layer===a))??rt(e.layers)[0]??e.layers[0]?.layer,s=e.layers.find((a)=>a.layer===i);return s?[s]:[]}let t=e.shownLayers.length>0&&e.shownLayers.every((i)=>e.layers.some((s)=>s.layer===i))?e.shownLayers.slice(0,2):rt(e.layers),n=[];for(let i of t){let s=e.layers.find((a)=>a.layer===i);if(s)n.push(s)}return n.length>0?n:e.layers.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return Qn(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=h("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,c,m);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let p=document.createElement("div");p.className="bp-plan-hover-hud bp-hidden",u.append(d,p);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=d.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(d,e.layer);let g={layer:e.layer,el:t,canvas:d,ctx:y,legendEl:b,okBtn:c,noBtn:m,statusEl:o,titleEl:r,subtitleEl:l,hoverHudEl:p,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=vs(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let c=document.createElement("button");c.type="button";let m=this.state?.selectedId===o.id;c.className="bp-plan-legend-chip"+(m?" active":"");let l=document.createElement("span");l.className="bp-plan-legend-sw",l.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,c.append(l,u),c.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(c)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(n)=>n.preventDefault()),e.addEventListener("pointerdown",(n)=>{let i=this.state;if(!i)return;this.root.focus();let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r);if(n.button===2){if(l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane),d=Zt(u,l.idx,l.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(l.id,{[l.isPlane?"outline":"path"]:d})}return}if(n.button!==0)return;if(e.setPointerCapture(n.pointerId),this.downPos={x:n.clientX,y:n.clientY},l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane);this.selectedVertex={id:l.id,idx:l.idx},this.cb.onSelect(l.id),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:l.idx,pts:u.map((d)=>[d[0],d[1]])},this.scheduleDraw()}else if(l?.kind==="midpoint"){let u=this.getItemPts(l.id,l.isPlane),d=ii(u,l.segIdx,l.pos,l.isPlane),p=l.isPlane&&l.segIdx+1>=u.length?d.length-1:Math.min(l.segIdx+1,d.length-1);this.cb.onSelect(l.id),this.selectedVertex={id:l.id,idx:p},this.patchLocalItem(l.id,l.isPlane,d),this.cb.onOptimisticPatch(l.id,{[l.isPlane?"outline":"path"]:d}),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:p,pts:d},this.scheduleDraw()}else{if(l&&(l.kind==="band"||l.kind==="region"))this.cb.onSelect(l.id);this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:r}}}),e.addEventListener("pointermove",(n)=>{let i=this.state;if(!i)return;let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let w=this.getCam(t,o,c);this.setCam(t,ei(w,a-this.drag.lastX,r-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=r,this.scheduleDraw();return}let p=this.getCam(t,o,c),[b,y]=Bt(p,a,r,o,c),f=[Math.round(b*1000)/1000,Math.round(y*1000)/1000];this.drag.pts[this.drag.idx]=f;let g=this.drag.pts.map((w)=>[w[0],w[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,g),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:g}),this.scheduleDraw();return}let m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r),u=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=l?l.id:"";if(this.hover=l?{layer:t,hit:l}:null,e.style.cursor=l?.kind==="vertex"||l?.kind==="midpoint"?"pointer":l?"pointer":"crosshair",u!==d||l?.kind!==this.hover?.hit.kind)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerup",(n)=>{let i=this.state,s=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(n.pointerId))e.releasePointerCapture(n.pointerId);if(s&&s.kind==="vertex"&&s.layer===t){this.cb.onCommitFields(s.id,{[s.isPlane?"outline":"path"]:s.pts});return}if(n.detail>=2){this.fitAll();return}if(i&&a&&Math.hypot(n.clientX-a.x,n.clientY-a.y)<4.5){let r=e.getBoundingClientRect(),o=n.clientX-r.left,c=n.clientY-r.top,m=Math.max(1,r.width),l=Math.max(1,r.height),u=this.getCam(t,m,l),d=It(i.bands,i.regions,t,i.selectedId,u,m,l,o,c);if(d&&(d.kind==="band"||d.kind==="region"))this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);else if(!d)this.cb.onSelect("")}}),e.addEventListener("wheel",(n)=>{n.preventDefault();let i=e.getBoundingClientRect(),s=n.clientX-i.left,a=n.clientY-i.top,r=Math.max(1,i.width),o=Math.max(1,i.height),c=this.getCam(t,r,o),m=Math.max(0.65,Math.min(1.55,1-n.deltaY*0.002));this.setCam(t,ti(c,m,s,a,r,o)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),c=Zt(o,this.selectedVertex.idx,r);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),c=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(p,b)=>Ke(a,p,b,n,i);e.fillStyle=ai,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((p)=>p.length>=3);if(e.fillStyle=ds,o.length>0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let p of c){let b=p.outline??[];if(b.length<3)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=fs(p.state||"proposed",y,f),w=ft(p.net||p.id,p.color||"");e.beginPath();for(let k=0;k0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),d=[];for(let p of u){for(let b of p.from??[])d.push(b);for(let b of p.to??[])d.push(b)}e.fillStyle=us,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let p of si(l,a,n,i,d))e.fillText(p.text,p.cx,p.cy);for(let p of u){let b=p.guides??[];if(b.length===0)continue;let y=s.selectedId===p.id||m?.id===p.id,f=vt(p.name||p.id,p.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[w,k]=r(g[0],g[1]),[S,L]=r(g[2],g[3]);e.moveTo(w,k),e.lineTo(S,L)}e.stroke()}for(let p of u){let b=p.path??[];if(b.length<2)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=gs(p.state||"proposed",y,f),w=vt(p.name||p.id,p.color||""),k=Qt(p.width??1.5,a.scale),S=()=>{e.beginPath();for(let M=0;M0){let M=ni(b);if(M){let[B,H]=r(M[0],M[1]),W=String(L),_=Math.max(16,W.length*6.5+8),j=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(B-_*0.5,H-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":w,e.strokeRect(B-_*0.5,H-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,B,H+0.5)}}}if(s.selectedId){let p=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let r=document.createElement("button");r.type="button";let o=this.openPanel===a.id;r.className="bp-mgmt-tab"+(o?" active":""),r.setAttribute("data-testid",`mgmt-tab-${a.id}`),r.setAttribute("aria-pressed",o?"true":"false");let c=document.createElement("span");c.textContent=Ee(a.label),r.appendChild(c);let m=this.getPanelData(a.id),l=Gn(m);if(l){let u=document.createElement("span");u.className=`bp-mgmt-badge bp-tone-${l.tone}`,u.textContent=l.text,r.appendChild(u)}r.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(r)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=h("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,s.appendChild(a)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=Ee(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),m.appendChild(l),e.appendChild(m)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Vn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),c.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),c.appendChild(y)}else{let y=On(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,c.appendChild(f)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",Un(a.footprint??"")].filter(Boolean).join(" · "),p=document.createElement("span");p.className="bp-dim",p.textContent=d;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(p,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=Ee(a.stock.class),u.appendChild(y)}o.append(c,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,p=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Yt(b,o()))return;this.bomLastUndo=!p&&(y.changed??0)>0?{project:d.project,editId:b.editId,refs:d.refs.slice(),field:d.field,was:typeof y.was==="string"?y.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=p?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Yt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(l,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn",p.textContent="Undo",p.addEventListener("click",()=>{c(Xn(d),!0)}),m.appendChild(p)}if(t.append(i,r,m),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),p.textContent=s(d)+(a(d)?" · judged":""),p.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(p)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let d=this.watchGen,p=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:p}).then(()=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(c,m),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let u=Wn(n,this.checksSource);if(u.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let p=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${p}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(d.source)} · ${d.rule}`;let g=document.createElement("span");g.className=`bp-tone-${p}`,g.textContent=String(d.n),b.append(y,f,g),l.appendChild(b);for(let w of d.rows??[]){let k=document.createElement("div");k.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=Ee(w.title??""),k.appendChild(S),w.names||this.checksSelectedId===w.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let M=document.createElement("span");if(M.className="bp-dim bp-mgmt-flex1",M.textContent=w.names??"",L.appendChild(M),this.checksSelectedId===w.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(H)=>{H.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:w.id}).then((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),L.appendChild(B)}k.appendChild(L)}k.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(k)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let m=i[c]??0,l=Jt(c),u=document.createElement("span");u.className=m>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",u.textContent=`${l.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(c,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=a[a.length-1],m=r[r.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${at(c[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,l=Jt(c.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let p=document.createElement("span");p.className="bp-mgmt-strong",p.textContent=Mt(c.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=c.mpn||c.key;let y=document.createElement("span");if(y.className=`bp-tone-${l.tone}`,y.textContent=l.label,d.append(p,b,y),typeof c.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(c.stock),d.appendChild(f)}if(u.appendChild(d),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((f)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(x,C)=>{let I=this.watchGen,D=this.project;this.planStatus="",this.cb.hub.rpc(x,{pro:D,...C}).catch((K)=>{if(I!==this.watchGen||D!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydratedKey!==i&&this.project){this.planHydratedKey=i;let x=this.watchGen,C=this.project;this.cb.hub.rpc("plan.get",{pro:C,board:!0}).then((I)=>{if(x!==this.watchGen||C!==this.project||!I?.panel)return;this.planHydratedBoard=I.panel.board??null,this.planHydratedDraw=I.panel.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),c.setAttribute("data-testid","mgmt-plan-off"),c.setAttribute("aria-pressed",!a?"true":"false"),c.textContent=h("gpui.bots.recall.off","Off"),c.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,c),e.appendChild(s);for(let x of t.elsewhere??[]){let C=document.createElement("div");C.className="bp-plan-elsewhere";let I=document.createElement("span");I.className="bp-tone-warn bp-mgmt-flex1",I.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:x.name||x.rel||""}),C.appendChild(I),e.appendChild(C)}if(t.empty){let x=document.createElement("div");x.className="bp-mgmt-note";let C=document.createElement("div");C.className="bp-dim",C.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let I=document.createElement("div");return I.className="bp-mgmt-faint",I.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),x.append(C,I),e.appendChild(x),e}let m=t.awaiting??0,l=t.blocked??0,u=t.done??0,d=t.total??0,p=t.revision??0,b=Kn(t),y=zn(t),f=y.reduce((x,C)=>x+C.count,0),g=document.createElement("div");g.className="bp-plan-status";let w=document.createElement("div");w.className="bp-plan-status-top";let k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${b.tone}`,k.textContent=h(b.key,b.label),w.appendChild(k),p>0){let x=document.createElement("span");x.className="bp-dim",x.textContent=`v${p}`,w.appendChild(x)}let S=document.createElement("span");if(S.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":l>0?"bp-tone-bad":"bp-dim"),S.textContent=d>0?`${u}/${d} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),w.appendChild(S),!t.live){let x=document.createElement("span");x.className="bp-mgmt-pill",x.textContent=h("gpui.mgmt.plan.saved","saved plan"),w.appendChild(x)}if(g.appendChild(w),f>0){let x=document.createElement("div");x.className="bp-plan-segbar";for(let C of y){if(C.count<=0)continue;let I=document.createElement("div");I.className=`bp-plan-seg bp-tone-bg-${C.tone}`,I.style.flexGrow=String(C.count),x.appendChild(I)}g.appendChild(x)}e.appendChild(g);let L=document.createElement("div");if(L.className="bp-mgmt-head",m>0){let x=document.createElement("button");x.type="button",x.className="primary bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-approve-all"),x.textContent=h("gpui.mgmt.plan.all","Approve all"),x.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(x)}if(t.routing){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-stop"),x.textContent=h("gpui.mgmt.plan.stop","Stop routing"),x.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(x)}if(t.live&&u>0){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-verify"),x.textContent=h("gpui.mgmt.plan.verify","Verify"),x.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(x)}let M=document.createElement("span");M.className="bp-mgmt-flex1";let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.setAttribute("data-testid","mgmt-plan-hide"),B.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),B.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.append(M,B),e.appendChild(L);let H=Array.isArray(t.asks)?t.asks:[];if(H.length>0){let x=H.map((le)=>le.what||"").filter(Boolean).join(", "),C=H[0]?.note||"",I=document.createElement("div");I.className="bp-plan-elsewhere";let D=document.createElement("div");D.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=x?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:x}):h("gpui.mgmt.plan.reqplain","Approval requested"),D.appendChild(K),C){let le=document.createElement("div");le.className="bp-dim",le.textContent=C,D.appendChild(le)}I.appendChild(D),e.appendChild(I)}if(this.planStatus){let x=document.createElement("div");x.className="bp-mgmt-note bp-plan-err bp-tone-bad";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):Ee(this.planStatus);let I=document.createElement("button");I.type="button",I.className="icon",I.textContent="×",I.title=h("common.close","Close"),I.addEventListener("click",()=>{this.planStatus="",this.render()}),x.append(C,I),e.appendChild(x)}if(t.keys_note){let x=document.createElement("div");x.className="bp-mgmt-note bp-dim";let C="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";x.textContent=t.keys_note===C?h("gpui.mgmt.plan.keysnote",C):Ee(t.keys_note),e.appendChild(x)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let x=document.createElement("div");x.className="bp-plan-stackup";let C=document.createElement("button");C.type="button",C.className="bp-plan-stackup-head",C.setAttribute("data-testid","mgmt-plan-stackup-toggle"),C.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let I=document.createElement("span");I.className="bp-plan-chev",I.textContent=this.planStackupOpen?"▾":"▸";let D=document.createElement("span");if(D.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),C.append(I,D),C.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),x.appendChild(C),this.planStackupOpen){let K=document.createElement("div");if(K.className="bp-plan-stackup-body",K.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let le=document.createElement("div");le.className="bp-dim",le.textContent=W,K.appendChild(le)}for(let le of _){let N=document.createElement("div");N.className="bp-mgmt-faint",N.textContent=`· ${le}`,K.appendChild(N)}x.appendChild(K)}e.appendChild(x)}let j=(x,C,I,D)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(C?" active":""),K.setAttribute("data-testid",I),K.setAttribute("aria-pressed",C?"true":"false"),K.textContent=x,K.addEventListener("click",D),K},me=document.createElement("div");if(me.className="bp-plan-viewbar",me.append(j(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),j(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),j(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let x=document.createElement("span");x.className="bp-plan-sep";let C=document.createElement("span");C.className="bp-plan-sep";let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn bp-plan-mini-btn",I.setAttribute("data-testid","mgmt-plan-fit"),I.textContent=h("gpui.mgmt.plan.fit","Fit"),I.addEventListener("click",()=>this.planCanvas?.fitAll()),me.append(x,j(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),j(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),j(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),C,j(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),I)}let ce=document.createElement("span");ce.className="bp-mgmt-flex1";let ie=document.createElement("button");ie.type="button",ie.className="bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-expand"),ie.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),ie.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),me.append(ce,ie),e.appendChild(me);let ye=this.planHydratedKey===i&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ke=this.planHydratedKey===i&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Ne=(ke.bands??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),ge=(ke.regions??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),Me=[],T=(t.layers??[]).map((x)=>{let C=[];for(let I of x.items??[]){let D=this.planOptimistic.get(I.id);if(!D){C.push(I);continue}let K={...I,width:typeof D.width==="number"?D.width:I.width,locked:typeof D.locked==="boolean"?D.locked:I.locked,edited:!0,state:I.state==="proposed"?"edited":I.state};if(typeof D.layer==="string"&&D.layer!==x.layer)Me.push({target:D.layer,item:K});else C.push(K)}return{...x,items:C}});for(let x of Me){let C=T.find((I)=>I.layer===x.target);if(C)C.items=[...C.items??[],x.item]}let re=this.planGridMode==="all"?T.map((x)=>x.layer):this.planGridMode==="single"?[this.planShownLayers.find((x)=>T.some((C)=>C.layer===x))??rt(T)[0]??T[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((x)=>T.some((C)=>C.layer===x))?this.planShownLayers.slice(0,2):rt(T);if(this.planViewMode!=="list"&&T.length>1){let x=document.createElement("div");x.className="bp-plan-layerbar";for(let C of T){let I=re.includes(C.layer);x.appendChild(j(C.title||C.layer,I,`mgmt-plan-layerpill-${C.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"){if(!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}else this.planGridMode="single",this.planShownLayers=[C.layer];this.render()}))}e.appendChild(x)}let se=(x,C)=>{let I=this.planOptimistic.get(x)??{};if(this.planOptimistic.set(x,{...I,...C}),typeof C.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"&&!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}let D={...C};if(Array.isArray(C.outline)&&Array.isArray(C.outline[0])&&typeof C.outline[0][0]==="number"){let K=ge.find((le)=>le.id===x);if(K?.holes&&K.holes.length>0)D.outline=[C.outline,...K.holes]}this.render(),n("plan.update",{ops:[{op:"set",id:x,fields:D}]})};if(this.planCommitFields=se,this.planSelectedId){let x="",C=null;for(let I of T){let D=(I.items??[]).find((K)=>K.id===this.planSelectedId);if(D){x=I.layer,C=D;break}}if(C){let I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let D=document.createElement("div");D.className="bp-plan-ins-row";let K=document.createElement("span");K.className="bp-plan-ins-sw",K.style.background=C.kind==="corridor"?vt(C.name||C.id,C.color||""):ft(C.name||C.id,C.color||"");let le=document.createElement("span");le.className="bp-mgmt-strong",le.textContent=C.name||C.id;let N=document.createElement("span");if(N.className="bp-dim",N.textContent=x,D.append(K,le,N),C.edited||C.state==="edited"){let ee=document.createElement("span");ee.className="bp-plan-ins-pill warn",ee.textContent=h("gpui.mgmt.plan.edited","Edited"),D.appendChild(ee)}if(C.locked){let ee=document.createElement("span");ee.className="bp-plan-ins-pill",ee.textContent=h("gpui.mgmt.plan.locked","Locked"),D.appendChild(ee)}let Y=document.createElement("span");Y.className="bp-mgmt-flex1",D.appendChild(Y);let Ie=document.createElement("button");if(Ie.type="button",Ie.className="bp-mgmt-btn bp-plan-mini-btn",Ie.setAttribute("data-testid","mgmt-plan-lock"),Ie.textContent=C.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),Ie.addEventListener("click",()=>se(C.id,{locked:!C.locked})),D.appendChild(Ie),C.state==="proposed"||C.state==="edited"){let ee=document.createElement("button");ee.type="button",ee.className="primary bp-mgmt-btn bp-plan-mini-btn",ee.textContent=h("android.hub.machines.approve","Approve"),ee.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!0}));let be=document.createElement("button");be.type="button",be.className="bp-mgmt-btn bp-plan-mini-btn",be.textContent=h("gpui.mgmt.plan.reject","Reject"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!1})),D.append(ee,be)}let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-note-toggle"),Ae.textContent=h("gpui.mgmt.plan.addnote","Add note"),Ae.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let pe=document.createElement("button");if(pe.type="button",pe.className="icon",pe.textContent="×",pe.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),D.append(Ae,pe),I.appendChild(D),!C.locked){let ee=document.createElement("div");if(ee.className="bp-plan-ins-row",C.kind==="corridor"){let Te=typeof C.width==="number"?C.width:1.5,ue=document.createElement("span");ue.className="bp-dim",ue.textContent=h("gpui.mgmt.plan.width","Width");let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn bp-plan-mini-btn",te.setAttribute("data-testid","mgmt-plan-w-down"),te.textContent="-",te.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,Te-0.25)*100)/100;se(C.id,{width:Ue})});let je=document.createElement("span");je.className="bp-plan-ins-val",je.textContent=`${Te.toFixed(2)}mm`;let Z=document.createElement("button");Z.type="button",Z.className="bp-mgmt-btn bp-plan-mini-btn",Z.setAttribute("data-testid","mgmt-plan-w-up"),Z.textContent="+",Z.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,Te+0.25)*100)/100;se(C.id,{width:Ue})});let Ce=document.createElement("span");Ce.className="bp-plan-sep",ee.append(ue,te,je,Z,Ce)}let be=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((Te)=>Te.layer):T.map((Te)=>Te.layer);if(be.length>0){let Te=document.createElement("span");Te.className="bp-dim",Te.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),ee.appendChild(Te);for(let ue of be)ee.appendChild(j(ue,ue===x,`mgmt-plan-move-${ue}`,()=>{if(ue!==x)se(C.id,{layer:ue})}))}I.appendChild(ee)}if(this.planNoteOpen){let ee=document.createElement("form");ee.className="bp-plan-note-form";let be=document.createElement("input");be.type="text",be.className="bp-plan-note-input",be.setAttribute("data-testid","mgmt-plan-note-input"),be.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let Te=document.createElement("button");Te.type="submit",Te.className="primary bp-mgmt-btn bp-plan-mini-btn",Te.setAttribute("data-testid","mgmt-plan-note-submit"),Te.textContent=h("gpui.mgmt.plan.addnote","Add note"),ee.append(be,Te),ee.addEventListener("submit",(ue)=>{ue.preventDefault();let te=be.value.trim();if(!te)return;be.value="",this.planNoteOpen=!1,this.render(),n("plan.update",{ops:[{op:"note",id:C.id,text:te}]})}),I.appendChild(ee)}if(this.planViewMode!=="list"&&!C.locked){let ee=document.createElement("div");ee.className="bp-plan-hint",ee.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(ee)}e.appendChild(I)}}let J=document.createElement("div");J.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),J.setAttribute("data-testid","mgmt-plan-rows");let de=h("gpui.mgmt.plan.done","done");for(let x of T){let C=x.items??[],I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let D=document.createElement("div");D.className="bp-mgmt-row-line";let K=document.createElement("span");K.className="bp-mgmt-strong",K.textContent=x.layer;let le=document.createElement("span");if(le.className="bp-dim bp-mgmt-flex1",le.textContent=`${x.role?`${x.role} · `:""}${x.done??0}/${C.length} ${de}`,D.append(K,le),x.status!=="approved"&&C.length>0){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.plan.layer","Approve layer"),N.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!0}));let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent=h("gpui.mgmt.plan.reject","Reject"),Y.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!1})),D.append(N,Y)}if(I.appendChild(D),x.stackup){let N=document.createElement("div");N.className="bp-plan-layer-stackup",N.textContent=x.stackup,I.appendChild(N)}J.appendChild(I);for(let N of C){if(this.planHideDone&&_n(N))continue;let Y=this.planSelectedId===N.id,Ie=document.createElement("div");Ie.className="bp-mgmt-row bp-plan-row"+(Y?" active":""),Ie.setAttribute("data-testid",`mgmt-plan-row-${N.id}`);let Ae=document.createElement("div");Ae.className="bp-mgmt-row-line";let pe=document.createElement("span");pe.className=`bp-plan-swatch bp-plan-st-${N.state||"proposed"}`,pe.style.setProperty("--swatch-color",N.color||"#8a8a8a");let ee=document.createElement("span");ee.className="bp-mgmt-flex1"+(N.state==="blocked"||N.state==="failed"?" bp-tone-bad":N.state==="edited"?" bp-tone-warn":N.state==="rejected"||N.state==="routed"||N.state==="verified"?" bp-dim":""),ee.textContent=`${N.name||N.id}${N.locked?" \uD83D\uDD12":""}`;let be=[];if(N.kind==="plane"){if(N.reference)be.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:N.reference}))}else{let te=N.nets??0;be.push(te===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:te}))}if(typeof N.width==="number"&&Number.isFinite(N.width))be.push(`${N.width.toFixed(2)}mm`);if(N.impedance)be.push(N.impedance);let Te=be.join(" · "),ue=document.createElement("span");if(ue.className="bp-plan-mark "+(N.state==="blocked"||N.state==="failed"?"bp-tone-bad":N.state==="verified"||N.state==="routed"?"bp-tone-ok":N.state==="approved"?"bp-tone-accent":"bp-dim"),ue.textContent=qn(N),Ae.append(pe,ee,ue),N.state==="proposed"||N.state==="edited"){let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn",te.textContent="✓",te.title=h("gpui.mgmt.plan.layer","Approve layer"),te.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!0})});let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent="✗",je.title=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!1})}),Ae.append(te,je)}if(Ie.appendChild(Ae),Te){let te=document.createElement("div");te.className="bp-mgmt-row-sub bp-plan-detail bp-dim",te.textContent=Te,Ie.appendChild(te)}if(N.state==="routing"&&typeof N.total==="number"&&N.total>0){let te=document.createElement("div");te.className="bp-plan-microbar";let je=document.createElement("div");je.className="bp-plan-microbar-fill";let Z=Math.max(0,Math.min(100,Math.round((N.routed??0)/N.total*100)));je.style.width=`${Z}%`,te.appendChild(je),Ie.appendChild(te)}if(N.problem_text){let te=document.createElement("div");te.className="bp-plan-problem",te.textContent=N.problem_text,Ie.appendChild(te)}Ie.addEventListener("click",()=>{this.planSelectedId=N.id,n("plan.focus",{id:N.id}),this.render()}),J.appendChild(Ie)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new en({onSelect:(D)=>{if(this.planSelectedId=D,!D)this.planNoteOpen=!1;this.render()},onFocusItem:(D)=>{n("plan.focus",{id:D})},onOptimisticPatch:(D,K)=>{let le=this.planOptimistic.get(D)??{};this.planOptimistic.set(D,{...le,...K})},onCommitFields:(D,K)=>{(this.planCommitFields??se)(D,K)},onApproveLayer:(D,K)=>{n("plan.approve",{layer:D,ids:[],approve:K})},onQuickApprove:(D,K)=>{n("plan.approve",{layer:"",ids:D,approve:K})}});let x=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,C=this.planExpanded||this.panelEl.clientWidth>=540||x;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:re,selectedId:this.planSelectedId,board:ye,bands:Ne,regions:ge,layers:T},C);let I=document.createElement("div");I.className="bp-plan-canvas-scroll",I.appendChild(this.planCanvas.root),e.appendChild(I)}if(this.planViewMode!=="canvas")e.appendChild(J);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let x=document.createElement("div");x.className="bp-plan-footer",x.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(x)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,k={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:w,...k}).catch((M)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=M instanceof Error?M.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Yn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(c?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(u),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}m.appendChild(l),o.appendChild(m);let p=Jn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(p.button?"bp-tone-warn":"bp-dim"),f.textContent=p.text,y.appendChild(f),p.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=p.button,w.addEventListener("click",()=>n("drc")),y.appendChild(w)}b.appendChild(y),o.appendChild(b);for(let w of t.conflicts??[]){let k=document.createElement("div");k.className="bp-mgmt-row bp-tone-bad",k.textContent=w,o.appendChild(k)}for(let w of t.suggestions??[]){let k=document.createElement("div");k.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.apply","Apply"),M.addEventListener("click",()=>n("apply",{key:w.key})),S.append(L,M),k.appendChild(S),o.appendChild(k)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,k.appendChild(L),S){let M=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=h("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:M})),k.appendChild(B)}w.appendChild(k),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=h("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),k.append(S,L),w.appendChild(k);for(let M of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=M,w.appendChild(B)}o.appendChild(w)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=h("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=h("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=h("gpui.mgmt.fab.extra","Costs more");let M=document.createElement("span");M.className="bp-mgmt-col bp-mgmt-col-read",M.textContent=h("gpui.mgmt.fab.readcol","Read"),w.append(k,S,L,M),o.appendChild(w);for(let H of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let j=document.createElement("span");j.className="bp-mgmt-flex1"+(H.changed?" bp-tone-warn":H.inherited?" bp-dim":""),j.textContent=`${H.changed?"• ":""}${H.label??""}`;let me=document.createElement("span");me.className="bp-mgmt-col",me.textContent=H.free?.text||"—";let ce=document.createElement("span");ce.className="bp-mgmt-col bp-dim",ce.textContent=H.extra?.text||"—";let ie=H.free&&typeof H.free==="object"?H.free:H.extra,ye=ie?.fetched??"",ke=Boolean(ye)&&ie?.confidence!=="published",Ne=ye?ke?`${ye}*`:ye:"—",ge=ie?.source??"",Me;if(ge.startsWith("https://")&&ye){let T=document.createElement("a");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",T.href=ge,T.target="_blank",T.rel="noopener noreferrer",T.textContent=Ne,Me=T}else{let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",T.textContent=Ne,Me=T}_.append(j,me,ce,Me),W.appendChild(_),o.appendChild(W)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(B)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var ys={trs:(e)=>e,t:(e,t)=>t},ws=new Set(["/settle"]);function li(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function di(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function pi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function mi(e,t=ys){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let c=ws.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:m}=ci(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:di(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function hi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let b of i)d.set(b.id,b.title||b.id);let p=new Set;for(let b of c)if(b.action.type==="thread")p.add(b.action.id);for(let b of n.threads){if(!b.id||p.has(b.id))continue;p.add(b.id);let{urgency:y,want:f}=ci(b);c.push({label:b.title||"Untitled thread",place:b.project?d.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:di(b),action:{type:"thread",id:b.id}})}}let m=[];for(let d=0;d0)m.push({score:f,index:d,item:p})}m.sort((d,p)=>{if(o){let f=(p.item.urgency??0)-(d.item.urgency??0);if(f!==0)return f}if(p.score!==d.score)return p.score-d.score;let b=d.item.kind==="thread"?0:1,y=p.item.kind==="thread"?0:1;if(b!==y)return b-y;return d.index-p.index});let l=new Set,u=[];for(let d of m){let p=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(p))continue;if(l.add(p),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=mi(t,{t:h,trs:Ee}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=hi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,d)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(d,p),m.appendChild(b),p{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var xs=new Set(["resume","raise","retry","move","signin"]);function gi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Rt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(xs.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function fi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class an{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";p.textContent=b,d.appendChild(p);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(d.appendChild(y),u.appendChild(d),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(l,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let c=document.createElement("div");c.className="bp-set-head",c.textContent="Paired devices",o.appendChild(c);try{let m=await this.cb.onLoadDevices();if(m.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",o.appendChild(l)}else for(let l of m){let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div");if(p.textContent=l.title||l.head||"",d.appendChild(p),l.text||l.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=l.text||l.detail||"",d.appendChild(b)}if(u.appendChild(d),l.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of l.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let l=document.createElement("div");l.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";l.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(l)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function rn(e){return xe("pre","bp-context-code",e)}function Cs(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,Ee(e))}function jt(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),Cs(t)),n}class on{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(jt(t.path,t.status),xe("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,rn(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),rn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,Ee(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(jt(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(jt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(jt(s.name,s.status),rn(a)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=xe("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var vi="http://www.w3.org/2000/svg";function yi(){let e=document.createElementNS(vi,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(vi,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function ks(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function wi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class ln{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=h("thread.new","New thread"),c.setAttribute("aria-label",h("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),r.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${ks(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?gi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,c.appendChild(m);for(let u of r.actions){if(!Rt(u,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=u.label,d.setAttribute("data-testid",`need-${u.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(p)=>{p.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=l,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),c.appendChild(m);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(r.kind==="projects"){let o=r.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!c&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,d=r.open?"▾":"▸";if(l.textContent=`${r.title.toUpperCase()} (${u}) ${d}`,r.hint)l.title=r.hint;l.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(l)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!c||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",m.appendChild(l)}for(let l of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(l.off?" bp-dim":""),u.setAttribute("data-project-id",l.id),l.nav||l.key)u.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let p=document.createElement("button");p.type="button",p.className="bp-proj-toggle";let b=yi();if(l.css)b.style.color=l.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=l.title||l.id,p.append(b,y),l.fold==="project-fold"&&l.nav)p.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${l.id}`),l.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(p,f),u.appendChild(d),!l.folded||Boolean(t)){let g=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:wi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,m=yi();if(i.css)m.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(m,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!c)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:wi(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let l of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`@${l.name}`,u.append(d,p),u.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(c,m),r.appendChild(o);for(let l of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,u.appendChild(d),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ss(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function As(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?c/m:0));s[a]=l<0?l*32768:l*32767}return s}class cn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ss(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),c=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=As(r.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var Ei=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],xi=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ci=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ki=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ls=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[c]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ps=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Ns=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class dn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},r=(u)=>{let d=0,p=0,b=0;for(let y=1;y<=u.maxBits;y++){d|=a(1);let f=u.counts[y];if(d-f{let d=c+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let p=o.length;while(p{m(1),o[c++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let p=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(p^65535)!==b)throw Error("invalid stored block length");if(n+p>e.length)throw Error("truncated stored payload");m(p);for(let y=0;y=e.length)break}else if(d===1||d===2){let p=Ps,b=Ns;if(d===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,w=new Uint8Array(19);for(let B=0;BS)throw Error("code length overflow");for(let _=0;_S)throw Error("code length overflow");M+=H}else if(B===18){let H=a(7)+11;if(M+H>S)throw Error("code length overflow");M+=H}else throw Error("invalid code length symbol")}p=Et(L,y),b=Et(L.subarray(y),f)}while(!0){let y=r(p);if(y<256)l(y);else if(y===256)break;else{let f=y-257;if(f>=Ei.length)throw Error("invalid length symbol");let g=Ei[f]+(xi[f]?a(xi[f]):0),w=r(b);if(w>=Ci.length)throw Error("invalid distance symbol");let k=Ci[w]+(ki[w]?a(ki[w]):0);m(g);let S=this.winPos-k&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new dn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(c))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ms=new TextDecoder;function Si(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ai(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let l=e.subarray(t,t+m);return t+=m,l}case 3:{if(t+m>e.length)return null;let l=Ms.decode(e.subarray(t,t+m));return t+=m,l}case 4:{if(m>e.length)return null;let l=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Pi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,c=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Li(m),u=[],d=[],p=0,b=0;while(l.more()){let y=l.nextU32(),f=u.length,g=1/0,w=1/0,k=-1/0,S=-1/0;if(a===2)p=p+l.nextI32()|0,b=b+l.nextI32()|0,u.push(p,b),g=k=p,w=S=b;else{let M=Math.min(l.nextU32(),1048576);for(let B=0;Bk)k=p;if(bS)S=b}}let L=(u.length-f)/2;if(L>0){let M=a===2||L===1?2:a===0?0:1,B=a===0?0:o;d.push({info:y,x0:g-B,y0:w-B,x1:k+B,y1:S+B,at:f,n:L,kind:M})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:c,pts:new Float32Array(u),pieces:d}}function Ni(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Mi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,c=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,l=(t-c)/r;if(m<0||m>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ti=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Bi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class mn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Ii(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,c=!1,m=-1,l=null,u=new mn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let p=document.createElement("div");p.className="bp-pane-bar bp-browser-nav";function b(J,de,x){let C=document.createElement("button");if(C.type="button",C.className="bp-v-btn",C.textContent=J,C.setAttribute("data-testid",de),x)C.title=x;return C}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let k=document.createElement("input");k.type="text",k.className="bp-browser-input",k.placeholder="https://…",k.autocomplete="off",k.spellcheck=!1,k.setAttribute("data-testid","browser-url");let S=b("Go","browser-go","Navigate");S.type="submit",w.append(k,S);let L=b("Take over","browser-takeover");L.classList.add("is-primary"),p.append(y,f,g,w,L);let M=document.createElement("div");M.className="bp-browser-drive-bar",M.hidden=!0;let B=document.createElement("div");B.className="bp-browser-keys-row";let H=document.createElement("input");H.type="text",H.className="bp-browser-input",H.placeholder="Type text or press Enter/Tab/Arrows…",H.autocomplete="off",H.spellcheck=!1,H.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");B.append(H,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[J,de]of Ti){let x=b(J,`browser-key-${de}`);x.addEventListener("click",()=>ge("press",{key:de})),_.append(x)}M.append(B,_);let j=document.createElement("div");j.className="bp-browser-err",j.setAttribute("data-testid","browser-error"),j.hidden=!0;let me=document.createElement("div");me.className="bp-browser-stage",me.setAttribute("data-testid","browser-stage");let ce=document.createElement("img");ce.className="bp-browser-img",ce.alt="Hub browser screen",ce.draggable=!1,ce.hidden=!0,ce.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",me.append(ce,ie);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,d.append(p,M,j,me,ye),e.replaceChildren(d);function ke(J){j.textContent=J,j.hidden=!J}function Ne(){M.hidden=!s,ye.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),ce.classList.toggle("is-driving",s)}function ge(J,de={},x){u.enqueue(async()=>{if(!i)return;ke("");try{if(await t.hub.rpc("browser",{thread:n,op:J,...de}),!i)return;x?.(),re()}catch(C){if(!i)return;ke(C instanceof Error?C.message:String(C))}})}function Me(J){ge("toolbar",{command:J},()=>{s=!0,Ne()})}y.addEventListener("click",()=>Me("back")),f.addEventListener("click",()=>Me("forward")),g.addEventListener("click",()=>Me("reload")),w.addEventListener("submit",(J)=>{J.preventDefault();let de=Bi(k.value);if(!de)return;if(k.value=de,!s)ge("takeover",{},()=>{s=!0,Ne()});ge("navigate",{url:de},()=>{s=!0,Ne()})}),L.addEventListener("click",()=>{if(s)ge("handback",{},()=>{s=!1,Ne()});else ge("takeover",{},()=>{s=!0,Ne(),H.focus()})});function T(){let J=H.value;if(!J)return;H.value="",ge("type",{text:J})}W.addEventListener("click",T),H.addEventListener("keydown",(J)=>{if(!s)return;if(J.key==="Enter"){if(J.preventDefault(),H.value)T();ge("press",{key:"Enter"});return}if(J.key==="Tab"||J.key==="Escape"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="ArrowLeft"||J.key==="ArrowRight"||J.key==="Backspace"&&H.value==="")J.preventDefault(),ge("press",{key:J.key})}),ce.addEventListener("click",(J)=>{if(!s||!a)return;let de=ce.getBoundingClientRect(),x=Mi(J.clientX,J.clientY,{left:de.left,top:de.top,width:de.width,height:de.height,naturalWidth:ce.naturalWidth,naturalHeight:ce.naturalHeight});if(!x)return;ge("click",x)}),ce.addEventListener("wheel",(J)=>{if(!s||!a)return;J.preventDefault();let de=Math.round(J.deltaX),x=Math.round(J.deltaY);if(de===0&&x===0)return;ge("scroll",{dx:de,dy:x})},{passive:!1});async function re(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let J=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(J.ok){let de=await J.blob();if(!i)return;let x=URL.createObjectURL(de),C=r;if(r=x,ce.src=x,ce.hidden=!1,ie.hidden=!0,a=!0,C)URL.revokeObjectURL(C)}else if(!a)ce.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!a)ce.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let se=t.hub.onFrame((J)=>{if(!i)return;if(J.t==="shot"&&J.bot===n){if(typeof J.n==="number"){if(J.n===m)return;m=J.n}re()}});return re(),{destroy(){if(i=!1,se(),l?.abort(),r)URL.revokeObjectURL(r),r=""}}}function O(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ht(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function ji(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Bs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ri(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Is(e){let t=ji(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Hi(e,t,n,i){let s=!0,a="",r="",o=O("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=O("div","bp-pane-bar"),m=O("div","bp-files-crumbs"),l=O("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void f(a)),c.append(m,l);let u=O("div","bp-files-split"),d=O("div","bp-files-list");d.setAttribute("data-testid","files-list");let p=O("div","bp-files-preview");p.setAttribute("data-testid","files-preview"),p.append(O("div","bp-pane-empty","Select a file to preview")),u.append(d,p),o.append(c,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=O("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let w=a.split("/").filter(Boolean),k="";for(let S of w){k=k?`${k}/${S}`:S;let L=k;m.append(O("span","bp-vh-sep","/"));let M=O("button","bp-crumb-btn",S);M.type="button",M.addEventListener("click",()=>void f(L)),m.append(M)}}async function y(g,w,k){r=g,p.replaceChildren();let S=O("div","bp-files-prev-head");S.append(O("span","bp-files-prev-name",g));let L=O("div","bp-files-prev-acts"),M=Is(w);if(M){let _=O("button","bp-v-btn is-primary",`Open in ${M}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(M,g)),L.append(_)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,H=O("a","bp-v-btn","Download");H.href=B,H.download=w,L.append(H),S.append(L),p.append(S);let W=ji(w);if(Bs(W)){let _=O("div","bp-files-img-wrap"),j=document.createElement("img");j.className="bp-files-img",j.alt=w,j.src=B,_.append(j),p.append(_);return}if(k>524288&&!Ri(W)){p.append(O("div","bp-pane-empty",`Binary file (${Ht(k)}). Use Download to save.`));return}if(Ri(W)||k<=65536){let _=O("div","bp-pane-empty","Loading…");p.append(_);try{let j=await fetch(B,{credentials:"same-origin"});if(!s||r!==g)return;if(!j.ok){_.textContent=`Could not load file (${j.status})`;return}if((j.headers.get("content-type")||"").startsWith("image/")){_.remove();let se=document.createElement("img");se.className="bp-files-img",se.alt=w,se.src=B,p.append(se);return}let ce=262144,ie=[],ye=0,ke=!1;if(j.body){let se=j.body.getReader();try{while(!0){let{done:J,value:de}=await se.read();if(J||!de)break;if(ye+de.byteLength>ce){let x=ce-ye;if(x>0)ie.push(de.subarray(0,x)),ye+=x;ke=!0,await se.cancel();break}ie.push(de),ye+=de.byteLength}}finally{se.releaseLock()}}if(!s||r!==g)return;let Ne=new Uint8Array(ye),ge=0;for(let se of ie)Ne.set(se,ge),ge+=se.byteLength;let Me=!1;for(let se=0;seS.dir===L.dir?S.name.localeCompare(L.name):S.dir?-1:1),d.replaceChildren(),g){let S=O("button","bp-file-row is-dir");S.type="button",S.append(O("span","bp-file-icon","↰"),O("span","bp-file-name",".."));let L=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";S.addEventListener("click",()=>void f(L)),d.append(S)}if(k.length===0){d.append(O("div","bp-pane-empty","Empty folder"));return}for(let S of k){let L=g?`${g}/${S.name}`:S.name,M=O("button","bp-file-row"+(S.dir?" is-dir":"")+(L===r?" is-sel":""));M.type="button",M.setAttribute("data-testid",`file-row-${S.name}`),M.append(O("span","bp-file-icon",S.dir?"▸":"·"),O("span","bp-file-name",S.name),O("span","bp-file-size",S.dir?"":Ht(S.size))),M.addEventListener("click",()=>{if(S.dir)f(L);else d.querySelectorAll(".bp-file-row.is-sel").forEach((B)=>B.classList.remove("is-sel")),M.classList.add("is-sel"),y(L,S.name,S.size)}),d.append(M)}}catch(w){if(!s)return;d.replaceChildren(O("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return f(""),{destroy(){s=!1}}}function Di(e,t,n){let i=!0,s=O("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=O("div","bp-pane-bar"),r=O("span","bp-diff-summary","Loading diff…"),o=O("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let c=O("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(a,c),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){r.textContent="Not a git repository",c.append(O("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof l?.diff==="string"?l.diff:"";if(!u.trim()){r.textContent="Clean working tree",c.append(O("div","bp-pane-empty","No uncommitted changes."));return}let d=u.split(` `),p=0,b=0,y=0,f=document.createDocumentFragment(),g=O("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=O("div","bp-diff-file"),p++;let k=w.match(/ b\/(.+)$/);g.append(O("div","bp-diff-file-head",k?k[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))g.append(O("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))g.append(O("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))b++,g.append(O("div","bp-diff-line is-add",w));else if(w.startsWith("-"))y++,g.append(O("div","bp-diff-line is-del",w));else g.append(O("div","bp-diff-line",w))}if(g.childNodes.length>0)f.append(g);r.textContent=`${p||1} file${p===1?"":"s"} · +${b} -${y}`,c.append(f)}catch(l){if(!i)return;r.textContent="Diff unavailable",c.append(O("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return m(),{destroy(){i=!1}}}function Fi(e,t,n){let i=!0,s="checks",a=O("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=O("div","bp-pane-bar"),o=O("div","bp-review-tabs"),c=O("button","bp-v-btn is-on","Checks"),m=O("button","bp-v-btn","BOM"),l=O("button","bp-v-btn","Comments");c.type=m.type=l.type="button",o.append(c,m,l);let u=O("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void y()),r.append(o,u);let d=O("div","bp-review-body");d.setAttribute("data-testid","review-body"),a.append(r,d),e.replaceChildren(a);function p(f){s=f,c.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),y()}c.addEventListener("click",()=>p("checks")),m.addEventListener("click",()=>p("bom")),l.addEventListener("click",()=>p("comments"));function b(f){let g=O("div","bp-review-md"),w=f.split(` `),k=0;while(k{B.preventDefault();let H=L.value.trim();if(!H)return;M.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:H}).then(()=>{L.value="",M.disabled=!1,y()},()=>{M.disabled=!1})}),d.append(S),k.length===0){d.append(O("div","bp-pane-empty","No review comments yet."));return}for(let B of k){let H=O("div","bp-review-comment"+(B.resolved?" is-resolved":"")),W=[B.by||"review",B.file,B.layer,B.item].filter(Boolean).join(" · ");H.append(O("div","bp-review-comment-meta",W),O("div","bp-review-comment-text",B.text)),d.append(H)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(d.replaceChildren(),g.line||g.gate){let w=O("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));d.append(w)}if(g.err)d.append(O("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let w=O("div","bp-review-tasks");g.tasks.forEach((k,S)=>{let L=O("label","bp-review-task"),M=document.createElement("input");M.type="checkbox",M.checked=!!(k.done??k.checked);let B=typeof k.index==="number"?k.index:S;M.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:B}).then(()=>void y(),()=>{})}),L.append(M,O("span",void 0,k.text||k.label||`Item ${S+1}`)),w.append(L)}),d.append(w)}if(g.md&&g.md.trim())d.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))d.append(O("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;d.replaceChildren(O("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function $i(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class hn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,m=n*0.5,l=this.scale,u=this.cx,d=this.cy,p=u-c/l,b=u+c/l,y=d-m/l,f=d+m/l,{off:g,dim:w,lift:k}=this.masks,S=[],L=[];for(let B=0;B>>H&1)===1)continue;if(H===k)L.push(B);else S.push(B)}let M=S.concat(L);r.lineCap="round",r.lineJoin="round";for(let B=0;B>>W.layer&1)===1,j=W.alpha*(_?0.25:1);if(j<=0.01)continue;this.drawChunk(r,W,j,p,y,b,f,u,d,l,c,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let B=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let H=0;Ha||f.y1r)continue;if(f.n<3)continue;let g=(d[f.at]-o)*m+l,w=(d[f.at+1]-c)*m+u;e.moveTo(g,w);for(let k=1;k0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=p,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let w=(d[g.at]-o)*m+l,k=(d[g.at+1]-c)*m+u;e.moveTo(w+b,k),e.arc(w,k,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=p,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(d[f.at]-o)*m+l,w=(d[f.at+1]-c)*m+u;if(f.n===1)e.moveTo(g,w),e.lineTo(g+0.01,w);else{e.moveTo(g,w);for(let k=1;k0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,c,m,l,u,d){let p=t.pts,b=$i(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(p[f.at]-c)*l+u,w=(p[f.at+1]-m)*l+d;if(f.kind===2){let k=Math.max(1.5,t.r*l);e.fillStyle=b,e.beginPath(),e.arc(g,w,k,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,w);for(let k=1;k=0;l--){let u=n.chunks[l];if(u.layer<32&&(m>>>u.layer&1)===1)continue;for(let d=0;dp.x1+r||ap.y1+r)continue;let b=(p.x1-p.x0+1)*(p.y1-p.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),c=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,u=s-c.left-c.width*0.5,d=a-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Gi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Ui(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function un(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function _e(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Fs=[_e(77),_e(83),_e(94)],$s=[_e(53),_e(58),_e(67)],Gs=[_e(245),_e(246),_e(248)],Us=[_e(225),_e(228),_e(233)];function Oi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function Vi(e,t,n){let i=Oi(e,e.VERTEX_SHADER,t),s=Oi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Os(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Vs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Wi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function _i(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function gn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class fn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=Vi(n,Rs,js),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=Vi(n,Hs,Ds),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Pi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,c=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,l=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,p=0,b=0;for(let g=0;g>>24&255,S=1-k/255,L=(w>>>16&255)/255,M=(w>>>8&255)/255,B=(w&255)/255,H=g*9;if(k===0&&o&&c&&m){let W=p*9;for(let j=0;j<9;j++)o[W+j]=e[H+j],c[W+j]=t[H+j];let _=p*12;for(let j=0;j<3;j++)m[_+j*4]=L,m[_+j*4+1]=M,m[_+j*4+2]=B,m[_+j*4+3]=1;p++}else if(l&&u&&d){let W=b*9;for(let j=0;j<9;j++)l[W+j]=e[H+j],u[W+j]=t[H+j];let _=b*12;for(let j=0;j<3;j++)d[_+j*4]=L,d[_+j*4+1]=M,d[_+j*4+2]=B,d[_+j*4+3]=S;b++}}let y=o&&c&&m?this.createSubBatch(o,c,m,a*3):null,f=l&&u&&d?this.createSubBatch(l,u,d,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Ui(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Gs:Fs,_=this.lightTheme?Us:$s;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),l=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*u,this.target[1]-this.dist*c*l,this.target[2]+this.dist*m],p=Wi([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),b=Math.abs(p[2])>0.99?[0,1,0]:[0,0,1],y=Wi(_i(p,b)),f=_i(y,p),g=new Float32Array([y[0],f[0],-p[0],0,y[1],f[1],-p[1],0,y[2],f[2],-p[2],0,-gn(y,d),-gn(f,d),gn(p,d),1]),w=Math.max(0.05,this.dist*0.01),k=Math.max(this.dist*10,this.radius*20),S=Vs(35*Math.PI/180,r/o,w,k),L=Os(S,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,p[0],p[1],p[2]);let M=!1,B=[],H=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,j=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(j<1){if(M=!0,j>0)H.push({batch:W,fade:j})}else B.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of B)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of B)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of H)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),M}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var qi=64,Ws=16777216;function _s(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ki(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function vn(e){return e==="board"||e==="schematic"||e==="gerbers"}function qs(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function yn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let p=document.createElement("div");p.className="bp-v-layers",p.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,l.append(u,d,p,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,c,m,l,y);let f="",g="",w=0,k=!1,S=new Set,L=[],M=0,B=new Map,H=new Map,W={},_=[],j="",pe="",le=!1,ie=!1,ye=0,ke=!1,Ne=0,ve="",Me=0,T=null,re=null,ae=null,J=null,ce=null,x=new bn,C=0,I=!1,G="",z="",me="",N="";document.addEventListener("click",(R)=>{if(!I)return;if(R.target instanceof Node&&y.contains(R.target))return;I=!1,de()}),document.addEventListener("keydown",(R)=>{if(I&&R.key==="Escape")I=!1,de()});function Y(){if(C)window.clearInterval(C),C=0;x.playing=!1}function Ie(){let R=g==="3d"||g==="mech";if(c.hidden=!R,!R)return;if(c.childElementCount>0)return;for(let U of Gi){let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent=U.label,F.setAttribute("data-testid",`solid-view-${U.id}`),F.addEventListener("click",()=>{ae?.setView(U.id)}),c.append(F)}let D=document.createElement("button");D.type="button",D.className="bp-v-btn",D.textContent="Snap view",D.setAttribute("data-testid","solid-snap"),D.addEventListener("click",()=>{if(!ae)return;ae.snapPng().then((U)=>{if(!U)return;let F=URL.createObjectURL(U),q=document.createElement("a");q.href=F;let X=(je()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");q.download=`${X}-snap.png`,q.click(),setTimeout(()=>URL.revokeObjectURL(F),1000)})}),c.append(D)}async function Ae(){if(!f||g!=="board"&&g!=="schematic")return;de();let R=x.compareRequest();if(!R){G="",z="",me="",N="",await $e(!1);return}let D=`${g}|${R.commit}|${R.bits}|${pe}`;if(D===N&&S.size>0){te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1);return}let U=++w;S.clear(),B.clear(),Ye(),k=!0,G="",z=R.commit,me="",N=D;try{let F=pe||(g==="schematic"?W.sch:W.pcb)||"";if(!F){let ge=await t.hub.rpc("viewer.files",{thread:f});if(U!==w)return;W=ge||{},Z(),F=(g==="schematic"?W.sch:W.pcb)||""}if(!F)throw Error(`Unable to resolve ${g} file path for compare`);let q=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:R.commit,bits:R.bits,...pe?{path:pe}:{}});if(U!==w)return;let X=typeof q?.root==="string"?q.root:"",Q=g==="schematic"?"1":"0";G=X?`${Q}|${X}|diff -`:`${Q}|`,z=R.commit,me=F.startsWith("/")||/^[A-Za-z]:[\\/]/.test(F)||!X?F:`${X.replace(/\/+$/,"")}/${F.replace(/^\/+/,"")}`,k=!1;let he=L;Ye();for(let ge of he)if(ge.kind==="bin")Ge(ge.buf);else Oe(ge.key,ge.none,ge.retryable);te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1)}catch(F){if(U!==w)return;k=!1,G="",z="",me="",N="",Ye(),te(F instanceof Error?F.message:String(F),!0)}}function de(){let R=g==="board"||g==="schematic";if(y.hidden=!R,!R)return;let D=document.createElement("div");D.className="bp-history-group";let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="<",U.title="Older snapshot",U.disabled=x.refs.length===0||x.index>=x.refs.length-1,U.setAttribute("data-testid","history-prev"),U.addEventListener("click",()=>{if(Y(),x.step(1))Ae()});let F=document.createElement("button");F.type="button",F.className="bp-v-btn"+(x.playing?" is-on":""),F.textContent=x.playing?"⏸":"▶",F.title=x.playing?"Pause history":"Play history",F.disabled=x.refs.length===0,F.setAttribute("data-testid","history-play"),F.addEventListener("click",()=>{if(x.playing){Y(),de();return}if(x.refs.length===0)return;if(x.playing=!0,x.isLive())x.index=x.refs.length-1,Ae();else de();C=window.setInterval(()=>{if(!x.playing||g!=="board"&&g!=="schematic"){Y(),de();return}if(x.step(-1))Ae();else Y(),de()},1400)});let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent=">",q.title="Newer snapshot",q.disabled=x.isLive(),q.setAttribute("data-testid","history-next"),q.addEventListener("click",()=>{if(Y(),x.step(-1))Ae()});let X=document.createElement("button");X.type="button",X.className="bp-v-btn"+(x.isLive()?" is-on":""),X.textContent="Live",X.setAttribute("data-testid","history-live"),X.addEventListener("click",()=>{if(Y(),x.goLive())te("",!1),Ae()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let he=x.activeRef();Q.textContent=he?he.label||he.commit.slice(0,7):x.refs.length>0?`Live (${x.refs.length} saved)`:"Live",D.append(U,F,q,X,Q);let ge=document.createElement("div");ge.className="bp-history-group";let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(x.highlightEdits?" is-on":""),Le.textContent="Highlight edits",Le.disabled=x.refs.length===0,Le.setAttribute("data-testid","history-highlight"),Le.addEventListener("click",()=>{Y(),x.toggleHighlight(),Ae()});let we=document.createElement("div");we.className="bp-history-menu-wrap";let Be=document.createElement("button");if(Be.type="button",Be.className="bp-v-btn"+(I||!x.isLive()?" is-on":""),Be.disabled=x.refs.length===0,Be.setAttribute("data-testid","history-compare"),Be.setAttribute("aria-haspopup","menu"),Be.setAttribute("aria-expanded",String(I)),Be.textContent=he?`Compare: ${he.label||he.commit.slice(0,7)} ▾`:"Compare ▾",Be.addEventListener("click",(Re)=>{Re.stopPropagation(),I=!I,de()}),we.append(Be),I&&x.refs.length>0){let Re=document.createElement("div");Re.className="bp-history-menu",Re.setAttribute("role","menu"),Re.setAttribute("data-testid","history-compare-menu");let We=(De,Xe,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Xe),Ve.textContent=De,Ve.addEventListener("click",()=>{if(I=!1,Y(),x.selectCommit(Xe)){if(x.isLive())te("",!1);Ae()}else de()}),Re.append(Ve)};We("Live (working tree)","",x.isLive());for(let De of x.refs)We(De.label||De.commit.slice(0,7),De.commit,he?.commit===De.commit);we.append(Re)}ge.append(Le,we),y.replaceChildren(D,ge)}async function ee(R){if(!R)return;try{let D=await t.hub.rpc("viewer.refs",{thread:R});if(R!==f)return;x.setRefs(Array.isArray(D?.refs)?D.refs:[]),de()}catch{if(R!==f)return;x.setRefs([]),de()}}function be(){return document.documentElement.classList.contains("light")}let Te=new MutationObserver(()=>{let R=be();re?.setTheme(R),ae?.setTheme(R),ce?.setTheme(R)});Te.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ue(R,D="",U=!1){if(R==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${R}`;let F=document.createElement("div");F.className="bp-v-state-card";let q=document.createElement("div");if(q.className="bp-v-state-msg",q.textContent=D,F.append(q),U){let X=document.createElement("button");X.type="button",X.className="bp-v-btn is-primary",X.textContent=h("tools.retry","Retry"),X.addEventListener("click",()=>void $e(!0)),F.append(X)}d.replaceChildren(F)}function te(R,D){m.textContent=R,m.hidden=!R,m.classList.toggle("is-warn",D)}function je(){if(pe)return xt(pe);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(j);return""}function Z(){s.textContent=Ki(g);let R=je();if(a.hidden=!R,r.hidden=!R,r.textContent=R,o.replaceChildren(),g==="mech"&&_.length>1){let U=document.createElement("select");U.className="bp-v-select",U.setAttribute("aria-label",h("viewer.mech","Mech"));for(let F of _){let q=document.createElement("option");q.value=F,q.textContent=xt(F),q.selected=F===j,U.append(q)}U.addEventListener("change",()=>{j=U.value,Z(),$e(!1)}),o.append(U)}if(vn(g)){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(ke?" is-on":""),U.textContent=T?.layerHead||"Layers",U.setAttribute("data-testid","viewer-layers-btn"),U.addEventListener("click",()=>{if(ke=!ke,p.hidden=!ke,U.classList.toggle("is-on",ke),ke)Ue("","")}),o.append(U)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Fit",U.setAttribute("data-testid","viewer-fit-btn"),U.addEventListener("click",()=>{re?.fit(),ae?.fit()}),o.append(U)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(le&&!ie?" is-on":""),U.textContent=le?ie?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",U.setAttribute("data-testid","viewer-follow-btn"),U.addEventListener("click",()=>void nt()),o.append(U)}let D=document.createElement("button");D.type="button",D.className="bp-v-btn bp-v-close",D.textContent="✕",D.title=h("common.close","Close"),D.setAttribute("aria-label",h("common.close","Close")),D.setAttribute("data-testid","viewer-close-btn"),D.addEventListener("click",()=>t.closeViewer()),o.append(D)}function Ce(){if(!T){p.replaceChildren();return}let R=document.createDocumentFragment(),D=document.createElement("div");D.className="bp-v-layers-head";let U=document.createElement("span");if(U.textContent=T.layerHead||"Layers",D.append(U),T.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void Ue("reset","")),D.append(Q)}if(R.append(D),T.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((he,ge)=>{let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(T?.layerMode===ge?" is-on":""),Le.textContent=he,Le.addEventListener("click",()=>void Ue("mode",String(ge))),Q.append(Le)}),R.append(Q)}let F=re?.presentColors()??new Map,q=(T.layerList||[]).concat(T.layerMarks||[]),X=document.createElement("div");X.className="bp-v-layers-list";for(let Q of q){let he=F.get(Q.layer);if(he===void 0)continue;let ge=document.createElement("div");ge.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Le=document.createElement("input");Le.type="checkbox",Le.checked=Q.on!==!1,Le.addEventListener("change",()=>void Ue("toggle",String(Q.layer)));let we=document.createElement("span");we.className="bp-v-layer-swatch";let Be=he>>>16&255,Re=he>>>8&255,We=he&255;we.style.background=Q.on!==!1?`rgb(${Be},${Re},${We})`:`rgba(${Be},${Re},${We},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=Q.name,De.addEventListener("click",()=>void Ue("pick",String(Q.layer))),ge.append(Le,we,De),X.append(ge)}R.append(X),p.replaceChildren(R)}async function Ue(R,D){if(!vn(g))return;let U=w;try{let F=await t.hub.rpc("viewer.layers",{kind:g,present:Me,off:Ne,focus:ve,...R?{action:R,value:D}:{}});if(U!==w||!F)return;Ne=Number(F.own)||0,ve=typeof F.focus==="string"?F.focus:"",T=F;let q={off:Number(F.off)||0,dim:Number(F.dim)||0,lift:typeof F.lift==="number"?F.lift:255};if(re?.setLayers(q),Z(),ke)Ce()}catch{}}async function ze(){if(!le||ie||!f||!t.hub.hasFeature("follow"))return;ie=!0,Z();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function nt(){if(!f||!t.hub.hasFeature("follow"))return;let R=!le?"on":ie?"resume":"off";try{let D=await t.hub.rpc("viewer.follow",{thread:f,action:R});if(le=!!D.on,ie=!!D.paused,Z(),D.on&&!D.paused&&D.focus&&Array.isArray(D.focus.box)&&D.focus.box.length===4&&(D.seq||0)>ye)ye=D.seq||ye,re?.zoomToBoxMm([D.focus.box[0],D.focus.box[1],D.focus.box[2],D.focus.box[3]])}catch{}}function oe(){b.hidden=!0,b.replaceChildren(),re?.setHighlights([])}function lt(R){let D=R.split(";").filter(Boolean),U=D.shift()||R,F=[],q="",X="";for(let we of D){if(we.startsWith("g="))continue;let Be=we.indexOf("=");if(Be>0){let Re=we.slice(0,Be),We=we.slice(Be+1);if((Re==="ref"||Re==="symbol")&&!q)q=We;if(Re==="net"&&!X)X=We;F.push([Re,We])}else F.push([we,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let he=document.createElement("span");he.className="bp-v-info-title",he.textContent=U;let ge=document.createElement("button");ge.type="button",ge.className="bp-v-info-x",ge.textContent="×",ge.setAttribute("aria-label","Clear selection"),ge.addEventListener("click",oe),Q.append(he,ge);let Le=document.createElement("div");Le.className="bp-v-info-rows";for(let[we,Be]of F){let Re=document.createElement("span");Re.className="bp-v-info-chip",Re.textContent=Be?`${we}: ${Be}`:we,Le.append(Re)}return b.replaceChildren(Q,...F.length>0?[Le]:[]),b.hidden=!1,{ref:q||void 0,net:X||void 0}}async function Je(R){if(!R){oe();return}let D=Array.from(S)[0]||"";if(!D)return;let U=w;try{let F=await t.hub.rpc("viewer.info",{key:D,at:R.at,idx:R.idx});if(U!==w)return;let q=typeof F.info==="string"?F.info:"";if(!q){oe();return}let{ref:X,net:Q}=lt(q),he=[];if(X)he.push(["ref",X]);if(Q)he.push(["net",Q]);let ge=[[R.at,R.idx]];for(let[Le,we]of he){let Be=await t.hub.rpc("viewer.probe",{key:D,name:Le,value:we});if(U!==w)return;if(Array.isArray(Be.matches))for(let Re of Be.matches)ge.push(Re)}re?.setHighlights(ge)}catch{oe()}}function ct(){J?.destroy(),J=null,ce?.destroy(),ce=null,re?.destroy(),re=null,ae?.destroy(),ae=null,u.replaceChildren(),ke=!1,p.hidden=!0,b.hidden=!0,b.replaceChildren(),te("",!1),ue("none")}function Ye(){L=[],M=0}async function $e(R){if(!f||!g)return;let D=++w;if(S.clear(),k=!1,Ye(),ct(),Z(),Ie(),de(),(g==="board"||g==="schematic")&&f)ee(f);if(qs(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")J=Hi(u,t,f,(q,X)=>{if(g=q,pe=X,q==="mech")j=X;$e(!1)});else if(g==="diff")J=Di(u,t,f);else if(g==="review")J=Fi(u,t,f);else if(g==="browser")J=Ii(u,t,f);else if(g==="terminal")ue("loading","Loading terminal…"),import("/assets/terminal.js").then((X)=>{if(D!==w)return;if(ue("none"),X?.mountTerminalPane)ce=X.mountTerminalPane(u,t,f,be());else ue("error","Terminal chunk missing",!0)},(X)=>{if(D!==w)return;ue("error",X instanceof Error?X.message:String(X),!0)});return}if(ue("loading","Loading…"),!W.root)try{let q=await t.hub.rpc("viewer.files",{thread:f});if(D!==w)return;W=q||{},Z()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){ue("empty","No Gerbers in this project",!1);return}let U=be();if(g==="3d"||g==="mech")ae=new fn(u,{onStatus:(q,X)=>{if(X)ue("none"),te(q,!1);else if(q)ue("loading",q);else ue("none"),te("",!1)},onUserMove:()=>void ze()}),ae.setTheme(U);else if(g==="board"||g==="schematic"||g==="gerbers")re=new hn(u,{onPick:(q)=>void Je(q),onUserMove:()=>void ze()}),re.setTheme(U);else{ue("empty",`${Ki(g)} is not available in this viewer`,!1);return}let F={thread:f};if(R)F.force=!0;if(g==="mech"){if(_.length===0)try{let q=await t.hub.rpc("mech.list",{thread:f});if(D!==w)return;if(_=Array.isArray(q.parts)?q.parts:[],!j)j=q.primary||_[0]||"";Z()}catch(q){if(D!==w)return;ue("error",q instanceof Error?q.message:String(q),!0);return}if(!j){ue("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}F.kind="3d",F.path=j}else{if(F.kind=g,pe&&(g==="board"||g==="schematic"))F.path=pe;if(g==="3d"&&!R&&ae){let q=ae.keptToken();if(q)F.kept=q}if((g==="board"||g==="schematic"||g==="gerbers")&&!R&&t.hub.hasFeature("keptChunks"))F.keptChunks=Array.from(H.keys())}k=!0,G="",z="",me="",N="";try{let q=await t.hub.rpc("viewer.watch",F);if(D!==w)return;S=new Set(Array.isArray(q.keys)?q.keys:[]),k=!1;let X=L;Ye();for(let Q of X)if(Q.kind==="bin")Ge(Q.buf);else Oe(Q.key,Q.none,Q.retryable)}catch(q){if(D!==w)return;k=!1,S.clear(),Ye();let X=q instanceof Error?q.message:String(q),Q=/no gerbers|not in this project|another machine/i.test(X);ue(Q?"empty":"error",X,!Q)}}function Oe(R,D,U){if(k){if(L.length{if(R.t==="plot"&&typeof R.none==="string"&&typeof R.key==="string")Oe(R.key,R.none,R.retryable===!0)}),Dt=Lt(()=>{if(g)Z()}),kt=(R)=>{if(R.key==="Escape"&&g&&!b.hidden)oe()};return window.addEventListener("keydown",kt),{open(R,D){if(D!==f){if(f=D,W={},_=[],j="",B.clear(),le=!1,ie=!1,ye=0,Ne=0,ve="",Me=0,T=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:D}).then((U)=>{if(D!==f)return;if(le=!!U.on,ie=!!U.paused,ye=Number(U.seq)||0,g)Z()}).catch(()=>{})}if(R!==g)Y(),x.goLive(),Ne=0,ve="",Me=0,T=null;g=R,pe="",$e(!1)},reconcileHas(R){if(g&&!_s(g,R))t.closeViewer()},close(){if(w++,k=!1,Y(),I=!1,G="",z="",me="",N="",x.goLive(),c.hidden=!0,y.hidden=!0,Ye(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",S.clear(),ct()}}}var zi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(zi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(zi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ks(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ji(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Yi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function zs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Xi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,c,m,l);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let p=document.createElement("span");p.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(d,p,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let k=document.createElement("span");k.textContent=h("menu.settle","Settle"),w.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),k);let S=document.createElement("div");S.className="bp-menu-wrap";let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost bp-top-act",L.textContent="▾",L.title="Thread menu",L.setAttribute("aria-label","Thread menu"),L.setAttribute("data-testid","thread-menu-btn");let M=document.createElement("div");M.className="bp-popover bp-hidden",M.setAttribute("data-testid","thread-menu"),S.append(L,M),y.append(f,w,S);let B=document.createElement("div");B.className="bp-top-right";let H=document.createElement("button");H.type="button",H.className="bp-btn-ghost bp-top-act bp-hide-tablet",H.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=h("gpui.improvements","Improvements"),H.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let j=document.createElement("button");j.type="button",j.className="icon bp-top-icon",j.title="Search",j.setAttribute("aria-label","Search"),j.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let pe=document.createElement("button");pe.type="button",pe.className="icon bp-top-icon",pe.title=h("palette.settings","Settings"),pe.setAttribute("aria-label",h("palette.settings","Settings")),pe.setAttribute("data-testid","settings-btn"),pe.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),B.append(H,_,j,pe),t.append(n,i,u,y,B);let le=document.createElement("div");le.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let ke=document.createElement("div");ke.className="bp-right-area bp-hidden",ke.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let ve=document.createElement("section");ve.className="bp-viewer-pane bp-hidden",ve.setAttribute("data-testid","viewer-pane"),Ne.appendChild(ve),ke.appendChild(Ne);let Me=document.createElement("nav");Me.className="bp-rail",Me.setAttribute("aria-label","Viewer rail"),Me.setAttribute("data-testid","viewer-rail"),le.append(ie,ye,ke,Me),e.append(t,le);let T=new pn,re=null,ae=new Set,J=0,ce=null,x=[],C=[],I=[],G=[],z=[],me=[],N="",Y=0,Ie=0,Ae=null,de=null,ee="",be=null,Te=20,ue={},te=new Map;function je(v,E){te.delete(v),te.set(v,E);while(te.size>Te){let A=te.keys().next().value;if(A!==void 0)te.delete(A);else break}}let Z=new ln(ie,{onSelectThread:(v)=>{if(v===N&&Ae!==null){ie.classList.remove("bp-sidebar-open");return}we(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{we(v.thread)},onThreadAct:(v,E)=>{Qe(v,E)},onToggleSection:(v)=>{if(ae.has(v))ae.delete(v);else ae.add(v);he()},onToggleProjectFold:(v)=>{T.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>he()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let E=Rt(v,!1);if(!E)return;if(E.kind==="thread"){we(E.id);return}if(E.kind!=="call")return;let A=fi(await T.rpc(E.method,E.params));if(A?.kind==="thread")we(A.id);he()},hasRoomView:!1,onAddProject:()=>Oe.open({mode:"folder"})}),Ce=new qt(ye,{onLoadOlder:()=>{We()},onGoToEntry:(v)=>{Re(v)},onAnswerAsk:(v,E)=>{T.rpc("ask.answer",{ask:v,answer:E}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not send answer")})},onToggleReview:(v)=>{if(!N)return;let E=Y;T.rpc("thread.review",{thread:N,on:v}).then((A)=>{if(E===Y)Ce.setReview(A.review??null)}).catch(()=>{})},onUnansweredAction:(v,E)=>{if(!N)return;if(v==="again"||v==="thread-again")T.rpc("thread.again",{thread:N,value:E}).catch(()=>{});else T.rpc("thread.act",{thread:N,action:v,value:E}).catch(()=>{})},onReplyEntry:(v)=>{if(!T.hasFeature("reply")){let E=(v.text||"").split(` +`;function _e(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Fs=[_e(77),_e(83),_e(94)],$s=[_e(53),_e(58),_e(67)],Gs=[_e(245),_e(246),_e(248)],Us=[_e(225),_e(228),_e(233)];function Oi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function Vi(e,t,n){let i=Oi(e,e.VERTEX_SHADER,t),s=Oi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Os(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Vs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Wi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function _i(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function gn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class fn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=Vi(n,Rs,js),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=Vi(n,Hs,Ds),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Pi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,c=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,l=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,p=0,b=0;for(let g=0;g>>24&255,S=1-k/255,L=(w>>>16&255)/255,M=(w>>>8&255)/255,B=(w&255)/255,H=g*9;if(k===0&&o&&c&&m){let W=p*9;for(let j=0;j<9;j++)o[W+j]=e[H+j],c[W+j]=t[H+j];let _=p*12;for(let j=0;j<3;j++)m[_+j*4]=L,m[_+j*4+1]=M,m[_+j*4+2]=B,m[_+j*4+3]=1;p++}else if(l&&u&&d){let W=b*9;for(let j=0;j<9;j++)l[W+j]=e[H+j],u[W+j]=t[H+j];let _=b*12;for(let j=0;j<3;j++)d[_+j*4]=L,d[_+j*4+1]=M,d[_+j*4+2]=B,d[_+j*4+3]=S;b++}}let y=o&&c&&m?this.createSubBatch(o,c,m,a*3):null,f=l&&u&&d?this.createSubBatch(l,u,d,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Ui(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Gs:Fs,_=this.lightTheme?Us:$s;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),l=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*u,this.target[1]-this.dist*c*l,this.target[2]+this.dist*m],p=Wi([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),b=Math.abs(p[2])>0.99?[0,1,0]:[0,0,1],y=Wi(_i(p,b)),f=_i(y,p),g=new Float32Array([y[0],f[0],-p[0],0,y[1],f[1],-p[1],0,y[2],f[2],-p[2],0,-gn(y,d),-gn(f,d),gn(p,d),1]),w=Math.max(0.05,this.dist*0.01),k=Math.max(this.dist*10,this.radius*20),S=Vs(35*Math.PI/180,r/o,w,k),L=Os(S,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,p[0],p[1],p[2]);let M=!1,B=[],H=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,j=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(j<1){if(M=!0,j>0)H.push({batch:W,fade:j})}else B.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of B)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of B)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of H)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),M}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var qi=64,Ws=16777216;function _s(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ki(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function vn(e){return e==="board"||e==="schematic"||e==="gerbers"}function qs(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function yn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let p=document.createElement("div");p.className="bp-v-layers",p.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,l.append(u,d,p,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,c,m,l,y);let f="",g="",w=0,k=!1,S=new Set,L=[],M=0,B=new Map,H=new Map,W={},_=[],j="",me="",ce=!1,ie=!1,ye=0,ke=!1,Ne=0,ge="",Me=0,T=null,re=null,se=null,J=null,de=null,x=new bn,C=0,I=!1,D="",K="",le="",N="";document.addEventListener("click",(R)=>{if(!I)return;if(R.target instanceof Node&&y.contains(R.target))return;I=!1,pe()}),document.addEventListener("keydown",(R)=>{if(I&&R.key==="Escape")I=!1,pe()});function Y(){if(C)window.clearInterval(C),C=0;x.playing=!1}function Ie(){let R=g==="3d"||g==="mech";if(c.hidden=!R,!R)return;if(c.childElementCount>0)return;for(let U of Gi){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=U.label,G.setAttribute("data-testid",`solid-view-${U.id}`),G.addEventListener("click",()=>{se?.setView(U.id)}),c.append(G)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent="Snap view",F.setAttribute("data-testid","solid-snap"),F.addEventListener("click",()=>{if(!se)return;se.snapPng().then((U)=>{if(!U)return;let G=URL.createObjectURL(U),q=document.createElement("a");q.href=G;let X=(je()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");q.download=`${X}-snap.png`,q.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),c.append(F)}async function Ae(){if(!f||g!=="board"&&g!=="schematic")return;pe();let R=x.compareRequest();if(!R){D="",K="",le="",N="",await $e(!1);return}let F=`${g}|${R.commit}|${R.bits}|${me}`;if(F===N&&S.size>0){te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1);return}let U=++w;S.clear(),B.clear(),Ye(),k=!0,D="",K=R.commit,le="",N=F;try{let G=me||(g==="schematic"?W.sch:W.pcb)||"";if(!G){let fe=await t.hub.rpc("viewer.files",{thread:f});if(U!==w)return;W=fe||{},Z(),G=(g==="schematic"?W.sch:W.pcb)||""}if(!G)throw Error(`Unable to resolve ${g} file path for compare`);let q=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:R.commit,bits:R.bits,...me?{path:me}:{}});if(U!==w)return;let X=typeof q?.root==="string"?q.root:"",Q=g==="schematic"?"1":"0";D=X?`${Q}|${X}|diff +`:`${Q}|`,K=R.commit,le=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!X?G:`${X.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,k=!1;let he=L;Ye();for(let fe of he)if(fe.kind==="bin")Ge(fe.buf);else Oe(fe.key,fe.none,fe.retryable);te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1)}catch(G){if(U!==w)return;k=!1,D="",K="",le="",N="",Ye(),te(G instanceof Error?G.message:String(G),!0)}}function pe(){let R=g==="board"||g==="schematic";if(y.hidden=!R,!R)return;let F=document.createElement("div");F.className="bp-history-group";let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="<",U.title="Older snapshot",U.disabled=x.refs.length===0||x.index>=x.refs.length-1,U.setAttribute("data-testid","history-prev"),U.addEventListener("click",()=>{if(Y(),x.step(1))Ae()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(x.playing?" is-on":""),G.textContent=x.playing?"⏸":"▶",G.title=x.playing?"Pause history":"Play history",G.disabled=x.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(x.playing){Y(),pe();return}if(x.refs.length===0)return;if(x.playing=!0,x.isLive())x.index=x.refs.length-1,Ae();else pe();C=window.setInterval(()=>{if(!x.playing||g!=="board"&&g!=="schematic"){Y(),pe();return}if(x.step(-1))Ae();else Y(),pe()},1400)});let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent=">",q.title="Newer snapshot",q.disabled=x.isLive(),q.setAttribute("data-testid","history-next"),q.addEventListener("click",()=>{if(Y(),x.step(-1))Ae()});let X=document.createElement("button");X.type="button",X.className="bp-v-btn"+(x.isLive()?" is-on":""),X.textContent="Live",X.setAttribute("data-testid","history-live"),X.addEventListener("click",()=>{if(Y(),x.goLive())te("",!1),Ae()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let he=x.activeRef();Q.textContent=he?he.label||he.commit.slice(0,7):x.refs.length>0?`Live (${x.refs.length} saved)`:"Live",F.append(U,G,q,X,Q);let fe=document.createElement("div");fe.className="bp-history-group";let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(x.highlightEdits?" is-on":""),Le.textContent="Highlight edits",Le.disabled=x.refs.length===0,Le.setAttribute("data-testid","history-highlight"),Le.addEventListener("click",()=>{Y(),x.toggleHighlight(),Ae()});let we=document.createElement("div");we.className="bp-history-menu-wrap";let Be=document.createElement("button");if(Be.type="button",Be.className="bp-v-btn"+(I||!x.isLive()?" is-on":""),Be.disabled=x.refs.length===0,Be.setAttribute("data-testid","history-compare"),Be.setAttribute("aria-haspopup","menu"),Be.setAttribute("aria-expanded",String(I)),Be.textContent=he?`Compare: ${he.label||he.commit.slice(0,7)} ▾`:"Compare ▾",Be.addEventListener("click",(Re)=>{Re.stopPropagation(),I=!I,pe()}),we.append(Be),I&&x.refs.length>0){let Re=document.createElement("div");Re.className="bp-history-menu",Re.setAttribute("role","menu"),Re.setAttribute("data-testid","history-compare-menu");let We=(De,Xe,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Xe),Ve.textContent=De,Ve.addEventListener("click",()=>{if(I=!1,Y(),x.selectCommit(Xe)){if(x.isLive())te("",!1);Ae()}else pe()}),Re.append(Ve)};We("Live (working tree)","",x.isLive());for(let De of x.refs)We(De.label||De.commit.slice(0,7),De.commit,he?.commit===De.commit);we.append(Re)}fe.append(Le,we),y.replaceChildren(F,fe)}async function ee(R){if(!R)return;try{let F=await t.hub.rpc("viewer.refs",{thread:R});if(R!==f)return;x.setRefs(Array.isArray(F?.refs)?F.refs:[]),pe()}catch{if(R!==f)return;x.setRefs([]),pe()}}function be(){return document.documentElement.classList.contains("light")}let Te=new MutationObserver(()=>{let R=be();re?.setTheme(R),se?.setTheme(R),de?.setTheme(R)});Te.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ue(R,F="",U=!1){if(R==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${R}`;let G=document.createElement("div");G.className="bp-v-state-card";let q=document.createElement("div");if(q.className="bp-v-state-msg",q.textContent=F,G.append(q),U){let X=document.createElement("button");X.type="button",X.className="bp-v-btn is-primary",X.textContent=h("tools.retry","Retry"),X.addEventListener("click",()=>void $e(!0)),G.append(X)}d.replaceChildren(G)}function te(R,F){m.textContent=R,m.hidden=!R,m.classList.toggle("is-warn",F)}function je(){if(me)return xt(me);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(j);return""}function Z(){s.textContent=Ki(g);let R=je();if(a.hidden=!R,r.hidden=!R,r.textContent=R,o.replaceChildren(),g==="mech"&&_.length>1){let U=document.createElement("select");U.className="bp-v-select",U.setAttribute("aria-label",h("viewer.mech","Mech"));for(let G of _){let q=document.createElement("option");q.value=G,q.textContent=xt(G),q.selected=G===j,U.append(q)}U.addEventListener("change",()=>{j=U.value,Z(),$e(!1)}),o.append(U)}if(vn(g)){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(ke?" is-on":""),U.textContent=T?.layerHead||"Layers",U.setAttribute("data-testid","viewer-layers-btn"),U.addEventListener("click",()=>{if(ke=!ke,p.hidden=!ke,U.classList.toggle("is-on",ke),ke)Ue("","")}),o.append(U)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Fit",U.setAttribute("data-testid","viewer-fit-btn"),U.addEventListener("click",()=>{re?.fit(),se?.fit()}),o.append(U)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(ce&&!ie?" is-on":""),U.textContent=ce?ie?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",U.setAttribute("data-testid","viewer-follow-btn"),U.addEventListener("click",()=>void nt()),o.append(U)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn bp-v-close",F.textContent="✕",F.title=h("common.close","Close"),F.setAttribute("aria-label",h("common.close","Close")),F.setAttribute("data-testid","viewer-close-btn"),F.addEventListener("click",()=>t.closeViewer()),o.append(F)}function Ce(){if(!T){p.replaceChildren();return}let R=document.createDocumentFragment(),F=document.createElement("div");F.className="bp-v-layers-head";let U=document.createElement("span");if(U.textContent=T.layerHead||"Layers",F.append(U),T.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void Ue("reset","")),F.append(Q)}if(R.append(F),T.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((he,fe)=>{let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(T?.layerMode===fe?" is-on":""),Le.textContent=he,Le.addEventListener("click",()=>void Ue("mode",String(fe))),Q.append(Le)}),R.append(Q)}let G=re?.presentColors()??new Map,q=(T.layerList||[]).concat(T.layerMarks||[]),X=document.createElement("div");X.className="bp-v-layers-list";for(let Q of q){let he=G.get(Q.layer);if(he===void 0)continue;let fe=document.createElement("div");fe.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Le=document.createElement("input");Le.type="checkbox",Le.checked=Q.on!==!1,Le.addEventListener("change",()=>void Ue("toggle",String(Q.layer)));let we=document.createElement("span");we.className="bp-v-layer-swatch";let Be=he>>>16&255,Re=he>>>8&255,We=he&255;we.style.background=Q.on!==!1?`rgb(${Be},${Re},${We})`:`rgba(${Be},${Re},${We},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=Q.name,De.addEventListener("click",()=>void Ue("pick",String(Q.layer))),fe.append(Le,we,De),X.append(fe)}R.append(X),p.replaceChildren(R)}async function Ue(R,F){if(!vn(g))return;let U=w;try{let G=await t.hub.rpc("viewer.layers",{kind:g,present:Me,off:Ne,focus:ge,...R?{action:R,value:F}:{}});if(U!==w||!G)return;Ne=Number(G.own)||0,ge=typeof G.focus==="string"?G.focus:"",T=G;let q={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(re?.setLayers(q),Z(),ke)Ce()}catch{}}async function ze(){if(!ce||ie||!f||!t.hub.hasFeature("follow"))return;ie=!0,Z();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function nt(){if(!f||!t.hub.hasFeature("follow"))return;let R=!ce?"on":ie?"resume":"off";try{let F=await t.hub.rpc("viewer.follow",{thread:f,action:R});if(ce=!!F.on,ie=!!F.paused,Z(),F.on&&!F.paused&&F.focus&&Array.isArray(F.focus.box)&&F.focus.box.length===4&&(F.seq||0)>ye)ye=F.seq||ye,re?.zoomToBoxMm([F.focus.box[0],F.focus.box[1],F.focus.box[2],F.focus.box[3]])}catch{}}function oe(){b.hidden=!0,b.replaceChildren(),re?.setHighlights([])}function lt(R){let F=R.split(";").filter(Boolean),U=F.shift()||R,G=[],q="",X="";for(let we of F){if(we.startsWith("g="))continue;let Be=we.indexOf("=");if(Be>0){let Re=we.slice(0,Be),We=we.slice(Be+1);if((Re==="ref"||Re==="symbol")&&!q)q=We;if(Re==="net"&&!X)X=We;G.push([Re,We])}else G.push([we,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let he=document.createElement("span");he.className="bp-v-info-title",he.textContent=U;let fe=document.createElement("button");fe.type="button",fe.className="bp-v-info-x",fe.textContent="×",fe.setAttribute("aria-label","Clear selection"),fe.addEventListener("click",oe),Q.append(he,fe);let Le=document.createElement("div");Le.className="bp-v-info-rows";for(let[we,Be]of G){let Re=document.createElement("span");Re.className="bp-v-info-chip",Re.textContent=Be?`${we}: ${Be}`:we,Le.append(Re)}return b.replaceChildren(Q,...G.length>0?[Le]:[]),b.hidden=!1,{ref:q||void 0,net:X||void 0}}async function Je(R){if(!R){oe();return}let F=Array.from(S)[0]||"";if(!F)return;let U=w;try{let G=await t.hub.rpc("viewer.info",{key:F,at:R.at,idx:R.idx});if(U!==w)return;let q=typeof G.info==="string"?G.info:"";if(!q){oe();return}let{ref:X,net:Q}=lt(q),he=[];if(X)he.push(["ref",X]);if(Q)he.push(["net",Q]);let fe=[[R.at,R.idx]];for(let[Le,we]of he){let Be=await t.hub.rpc("viewer.probe",{key:F,name:Le,value:we});if(U!==w)return;if(Array.isArray(Be.matches))for(let Re of Be.matches)fe.push(Re)}re?.setHighlights(fe)}catch{oe()}}function ct(){J?.destroy(),J=null,de?.destroy(),de=null,re?.destroy(),re=null,se?.destroy(),se=null,u.replaceChildren(),ke=!1,p.hidden=!0,b.hidden=!0,b.replaceChildren(),te("",!1),ue("none")}function Ye(){L=[],M=0}async function $e(R){if(!f||!g)return;let F=++w;if(S.clear(),k=!1,Ye(),ct(),Z(),Ie(),pe(),(g==="board"||g==="schematic")&&f)ee(f);if(qs(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")J=Hi(u,t,f,(q,X)=>{if(g=q,me=X,q==="mech")j=X;$e(!1)});else if(g==="diff")J=Di(u,t,f);else if(g==="review")J=Fi(u,t,f);else if(g==="browser")J=Ii(u,t,f);else if(g==="terminal")ue("loading","Loading terminal…"),import("/assets/terminal.js").then((X)=>{if(F!==w)return;if(ue("none"),X?.mountTerminalPane)de=X.mountTerminalPane(u,t,f,be());else ue("error","Terminal chunk missing",!0)},(X)=>{if(F!==w)return;ue("error",X instanceof Error?X.message:String(X),!0)});return}if(ue("loading","Loading…"),!W.root)try{let q=await t.hub.rpc("viewer.files",{thread:f});if(F!==w)return;W=q||{},Z()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){ue("empty","No Gerbers in this project",!1);return}let U=be();if(g==="3d"||g==="mech")se=new fn(u,{onStatus:(q,X)=>{if(X)ue("none"),te(q,!1);else if(q)ue("loading",q);else ue("none"),te("",!1)},onUserMove:()=>void ze()}),se.setTheme(U);else if(g==="board"||g==="schematic"||g==="gerbers")re=new hn(u,{onPick:(q)=>void Je(q),onUserMove:()=>void ze()}),re.setTheme(U);else{ue("empty",`${Ki(g)} is not available in this viewer`,!1);return}let G={thread:f};if(R)G.force=!0;if(g==="mech"){if(_.length===0)try{let q=await t.hub.rpc("mech.list",{thread:f});if(F!==w)return;if(_=Array.isArray(q.parts)?q.parts:[],!j)j=q.primary||_[0]||"";Z()}catch(q){if(F!==w)return;ue("error",q instanceof Error?q.message:String(q),!0);return}if(!j){ue("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=j}else{if(G.kind=g,me&&(g==="board"||g==="schematic"))G.path=me;if(g==="3d"&&!R&&se){let q=se.keptToken();if(q)G.kept=q}if((g==="board"||g==="schematic"||g==="gerbers")&&!R&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(H.keys())}k=!0,D="",K="",le="",N="";try{let q=await t.hub.rpc("viewer.watch",G);if(F!==w)return;S=new Set(Array.isArray(q.keys)?q.keys:[]),k=!1;let X=L;Ye();for(let Q of X)if(Q.kind==="bin")Ge(Q.buf);else Oe(Q.key,Q.none,Q.retryable)}catch(q){if(F!==w)return;k=!1,S.clear(),Ye();let X=q instanceof Error?q.message:String(q),Q=/no gerbers|not in this project|another machine/i.test(X);ue(Q?"empty":"error",X,!Q)}}function Oe(R,F,U){if(k){if(L.length{if(R.t==="plot"&&typeof R.none==="string"&&typeof R.key==="string")Oe(R.key,R.none,R.retryable===!0)}),Dt=Lt(()=>{if(g)Z()}),kt=(R)=>{if(R.key==="Escape"&&g&&!b.hidden)oe()};return window.addEventListener("keydown",kt),{open(R,F){if(F!==f){if(f=F,W={},_=[],j="",B.clear(),ce=!1,ie=!1,ye=0,Ne=0,ge="",Me=0,T=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:F}).then((U)=>{if(F!==f)return;if(ce=!!U.on,ie=!!U.paused,ye=Number(U.seq)||0,g)Z()}).catch(()=>{})}if(R!==g)Y(),x.goLive(),Ne=0,ge="",Me=0,T=null;g=R,me="",$e(!1)},reconcileHas(R){if(g&&!_s(g,R))t.closeViewer()},close(){if(w++,k=!1,Y(),I=!1,D="",K="",le="",N="",x.goLive(),c.hidden=!0,y.hidden=!0,Ye(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",S.clear(),ct()}}}var zi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(zi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(zi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ks(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ji(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Yi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function zs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Xi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,c,m,l);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let p=document.createElement("span");p.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(d,p,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let k=document.createElement("span");k.textContent=h("menu.settle","Settle"),w.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),k);let S=document.createElement("div");S.className="bp-menu-wrap";let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost bp-top-act",L.textContent="▾",L.title="Thread menu",L.setAttribute("aria-label","Thread menu"),L.setAttribute("data-testid","thread-menu-btn");let M=document.createElement("div");M.className="bp-popover bp-hidden",M.setAttribute("data-testid","thread-menu"),S.append(L,M),y.append(f,w,S);let B=document.createElement("div");B.className="bp-top-right";let H=document.createElement("button");H.type="button",H.className="bp-btn-ghost bp-top-act bp-hide-tablet",H.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=h("gpui.improvements","Improvements"),H.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let j=document.createElement("button");j.type="button",j.className="icon bp-top-icon",j.title="Search",j.setAttribute("aria-label","Search"),j.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let me=document.createElement("button");me.type="button",me.className="icon bp-top-icon",me.title=h("palette.settings","Settings"),me.setAttribute("aria-label",h("palette.settings","Settings")),me.setAttribute("data-testid","settings-btn"),me.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),B.append(H,_,j,me),t.append(n,i,u,y,B);let ce=document.createElement("div");ce.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let ke=document.createElement("div");ke.className="bp-right-area bp-hidden",ke.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let ge=document.createElement("section");ge.className="bp-viewer-pane bp-hidden",ge.setAttribute("data-testid","viewer-pane"),Ne.appendChild(ge),ke.appendChild(Ne);let Me=document.createElement("nav");Me.className="bp-rail",Me.setAttribute("aria-label","Viewer rail"),Me.setAttribute("data-testid","viewer-rail"),ce.append(ie,ye,ke,Me),e.append(t,ce);let T=new pn,re=null,se=new Set,J=0,de=null,x=[],C=[],I=[],D=[],K=[],le=[],N="",Y=0,Ie=0,Ae=null,pe=null,ee="",be=null,Te=20,ue={},te=new Map;function je(v,E){te.delete(v),te.set(v,E);while(te.size>Te){let A=te.keys().next().value;if(A!==void 0)te.delete(A);else break}}let Z=new ln(ie,{onSelectThread:(v)=>{if(v===N&&Ae!==null){ie.classList.remove("bp-sidebar-open");return}we(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{we(v.thread)},onThreadAct:(v,E)=>{Qe(v,E)},onToggleSection:(v)=>{if(se.has(v))se.delete(v);else se.add(v);he()},onToggleProjectFold:(v)=>{T.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>he()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let E=Rt(v,!1);if(!E)return;if(E.kind==="thread"){we(E.id);return}if(E.kind!=="call")return;let A=fi(await T.rpc(E.method,E.params));if(A?.kind==="thread")we(A.id);he()},hasRoomView:!1,onAddProject:()=>Oe.open({mode:"folder"})}),Ce=new qt(ye,{onLoadOlder:()=>{We()},onGoToEntry:(v)=>{Re(v)},onAnswerAsk:(v,E)=>{T.rpc("ask.answer",{ask:v,answer:E}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not send answer")})},onToggleReview:(v)=>{if(!N)return;let E=Y;T.rpc("thread.review",{thread:N,on:v}).then((A)=>{if(E===Y)Ce.setReview(A.review??null)}).catch(()=>{})},onUnansweredAction:(v,E)=>{if(!N)return;if(v==="again"||v==="thread-again")T.rpc("thread.again",{thread:N,value:E}).catch(()=>{});else T.rpc("thread.act",{thread:N,action:v,value:E}).catch(()=>{})},onReplyEntry:(v)=>{if(!T.hasFeature("reply")){let E=(v.text||"").split(` `)[0]?.slice(0,100)??"";if(E)oe.prependDraft(`> ${E} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,E)=>{try{let A={entry:v,path:E};if(T.hasFeature("blobs"))A.metaOnly=!0;let P=await T.rpc("message.image",A);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function Ue(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function ze(v,E){if(!N)return;let A=Y,P=N;T.rpc(v,E).then((V)=>{if(A!==Y||N!==P)return;if(V.thread){let ne=C.findIndex((fe)=>fe.id===V.thread.id);if(ne>=0)C[ne]=V.thread;else C.unshift(V.thread);Z.setData(x,C,I,G),Ce.updateThreadMeta(V.thread),R(),oe.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(A===Y&&N===P)oe.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let nt,oe=new zt(ye,{onSend:(v,E)=>{wn(v,E)},onRunCommand:(v)=>{En(v)},onInterrupt:()=>{if(N)T.rpc("turn.interrupt",{thread:N}).catch(()=>{})},onQueryMentions:async(v,E)=>{try{return(await T.rpc("mentions.list",{q:v,kind:E,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=C.find((A)=>A.id===N)??null,E=Ue(v);if(!E||!N)return;if(E.interaction!=="plan")ze("thread.planonce",{thread:N,on:!0});else if(E.once)ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!N)return;if(v==="once")ze("thread.planonce",{thread:N,on:!0});else if(v==="always")ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})}});nt=new cn(T,{getThreadId:()=>N,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function lt(){let v=ee!=="",E=Je.isOpen();ke.classList.toggle("bp-hidden",!v&&!E),ke.classList.toggle("bp-has-viewer",v),ke.classList.toggle("bp-has-mgmt",E)}let Je=new tn(Ne,ke,{hub:T,getThreadId:()=>N,getThreadGen:()=>Y,onSendText:(v)=>{wn(v)},onOpenChange:()=>lt()});function ct(v){let E=window.prompt("Rename thread",v.title||"");if(!E||!E.trim())return;T.rpc("thread.act",{thread:v.id,action:"rename",title:E.trim()}).then((A)=>{if(A.thread)C=C.map((P)=>P.id===A.thread.id?A.thread:P),R(),he()}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":we(v.id);break;case"rail":if(!N&&v.id!=="terminal")break;if(ee===v.id)D();else U(v.id);break;case"thread-act":if(N)Qe(N,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let E=C.find((A)=>A.id===N);if(E)ct(E);break}case"prev-thread":case"next-thread":{let E=C.filter((ne)=>!ne.archived&&!ne.swarm);if(E.length<2)break;let A=E.findIndex((ne)=>ne.id===N),P=v.type==="next-thread"?1:-1,V=E[(A<0?0:A+P+E.length)%E.length];if(V)we(V.id);break}case"command":if(v.runDirectly)En(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":kt();break;case"settings":qe.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let $e=new nn(e,{getState:()=>({selectedThreadId:N,threads:C,projects:x,bots:I,railItems:z,commands:me}),onSearch:async(v)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:v,limit:20})},onExecute:Ye}),Oe=new Vt(e,{hub:T,onProjectAdded:(v)=>{if(he(),v.id)De(v.id)},onCloneDone:(v)=>{if(he(),v.thread)we(v.thread)}}),Ge=new sn(Me,(v)=>{if(v==="commands"){$e.open();return}if(!N)return;if(ee===v)D();else U(v)}),it=null,qe=new an(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,E)=>{await T.rpc("devices.page.act",{action:v,value:E})},onGetHome:()=>it,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>Hn(()=>{T.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let Dt=new on(e,(v,E)=>E?T.rpc("thread.context.mcp",{thread:v,...E}):T.rpc("thread.context",{thread:v}));L.addEventListener("click",(v)=>{v.stopPropagation();let E=C.find((V)=>V.id===N);if(!E)return;if(!M.classList.contains("bp-hidden")){M.classList.add("bp-hidden");return}let A=[{label:"Rename…",run:()=>ct(E)},{label:E.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(E.id,E.pinned?"unpin":"pin")}},{label:E.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(E.id,E.settled?"unsettle":"settle")}},{label:E.archived?"Unarchive":"Archive",run:()=>{Qe(E.id,E.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(E.id,"delete")}}];if(T.hasFeature("threadContext"))A.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Dt.open(E.id)});let P=document.createDocumentFragment();for(let V of A){let ne=document.createElement("button");ne.type="button",ne.className="bp-popover-item"+(V.danger?" danger":""),ne.textContent=V.label,ne.addEventListener("click",()=>{M.classList.add("bp-hidden"),V.run()}),P.appendChild(ne)}M.replaceChildren(P),M.classList.remove("bp-hidden")}),document.addEventListener("click",()=>M.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let E=document.createElement("div");E.className="bp-modal";let A=document.createElement("div");A.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),A.append(P,V);let ne=document.createElement("div");ne.className="bp-modal-body",ne.textContent="Loading…",E.append(A,ne),v.appendChild(E),v.addEventListener("click",(fe)=>{if(fe.target===v)v.remove()}),e.appendChild(v);try{let fe=await T.rpc("improvements.projects",{}),He=fe.projects??[];if(He.length===0){ne.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Se of He){let se=document.createElement("div");se.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Se.title||Se.name||Se.id;let tt=document.createElement("button");tt.type="button",tt.className=Se.id===fe.project?"primary":"",tt.textContent=Se.id===fe.project?"Active":"Select",tt.addEventListener("click",()=>{T.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Ze,tt),et.appendChild(se)}ne.replaceChildren(et)}catch(fe){ne.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}H.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>$e.open()),j.addEventListener("click",()=>$e.open()),pe.addEventListener("click",()=>{qe.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function R(){let v=C.find((P)=>P.id===N)??null,E=v?x.find((P)=>P.id===v.project):void 0;o.textContent=E?.title??"",r.classList.toggle("bp-hidden",!E),c.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let A=Ue(v);if(oe.setPlanMode(A),!A||A.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",A.phase==="executing"),l.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=A.phase==="armed"&&A.once?h("gpui.planmode.top.once","Plan (1 turn)"):A.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):A.phase==="planning"?h("gpui.planmode.top.planning","Planning"):A.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){p.className=`bp-dot ${Ks(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),k.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;oe.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function D(v=!0){if(Ie++,ee="",Ge.setActive(""),ve.classList.add("bp-hidden"),be?.close(),lt(),v&&N&&T.getState()==="connected")T.rpc("viewer.watch",{thread:N,kind:""}).catch(()=>{})}function U(v){if(Ie++,ee=v,Ge.setActive(v),ve.classList.remove("bp-hidden"),lt(),!be&&typeof yn==="function")be=yn(ve,{hub:T,getThreadId:()=>N,closeViewer:()=>D(!0)});if(be)be.open(v,N);else{let E=document.createElement("div");E.className="bp-viewer-placeholder";let A=document.createElement("div");A.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>D(!0)),A.append(P,V);let ne=document.createElement("div");ne.className="bp-dim bp-viewer-msg",ne.textContent=`Viewer pane (${v}).`,E.append(A,ne),ve.replaceChildren(E)}}async function F(v,E){if(!v||!T.hasFeature("rail")){if(E===Y)z=[],Ge.setItems([]);return}let A=++Ie;try{let P=await T.rpc("viewer.rail",{thread:v,page:ee});if(E!==Y||A!==Ie)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(z=V,Ge.setItems(V),P.has){if(be?.reconcileHas?.(P.has),ee&&!Ji(P.has,ee))D(!0)}}catch{if(E===Y&&A===Ie)z=[],Ge.setItems([])}}function q(v){for(let E of v)if(E.kind==="threads"){for(let A of E.rows)if(!A.off&&(A.nav||A.id)&&!(A.nav||"").startsWith("@room:"))return A.nav||A.id}else if(E.kind==="projects"){for(let A of E.rows)for(let P of A.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function X(v,E){for(let A of v)if(A.kind==="threads"){if(A.rows.some((P)=>(P.nav||P.id)===E))return!0}else if(A.kind==="projects"){for(let P of A.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===E))return!0}return!1}function Q(v){let E=[];for(let A of v){if(A.kind!=="projects")continue;for(let P of A.rows)E.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(E.length>0)x=E}async function he(){if(!T.hasFeature("sections"))return!1;let v=++J;try{let E=await T.rpc("sidebar.sections",{open:Array.from(ae)});if(v!==J)return!0;let A=Array.isArray(E.sections)?E.sections:[];return re=A,Q(A),Z.setData(x,C,I,G),Z.setSections(A,I,G),R(),!0}catch{return!1}}function ge(){if(!T.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,he()},150)}async function Le(){if(Ae=null,T.hasFeature("bots"))try{let E=await T.rpc("bots.list",{});I=E.bots??[],G=E.rooms??[]}catch{}if(T.hasFeature("shell")){let E=await T.rpc("shell.sync",{have:ue,settled:25}),A=new Set(E.removed??[]),P=new Set((E.projects??[]).map((V)=>V.id));if(A.size>0||P.size>0)x=[...x.filter((V)=>!A.has(V.id)&&!P.has(V.id)),...E.projects??[]],C=[...C.filter((V)=>!A.has(V.project)&&!P.has(V.project)),...E.threads??[]];else if(Array.isArray(E.threads)&&E.threads.length>0){let V=new Map(C.map((ne)=>[ne.id,ne]));for(let ne of E.threads)V.set(ne.id,ne);C=Array.from(V.values())}if(E.sections!==void 0){let V=Array.isArray(E.sections)?E.sections:Array.isArray(E.sections?.sections)?E.sections.sections:null;if(V)re=V,Q(V)}if(E.h)ue=E.h;Z.setData(x,C,I,G),Z.setSections(re,I,G)}else if(T.hasFeature("sections")){let[E,A]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(ae)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(C=A.threads??[],E&&Array.isArray(E.sections)){let P=E.sections;if(!P.some((ne)=>ne.kind==="projects"&&ne.rows.length>0)){let ne=P.find((fe)=>fe.kind==="projects"&&fe.fold&&fe.toggle&&(fe.count??0)>0);if(ne?.toggle&&!ae.has(ne.toggle)){ae.add(ne.toggle);let fe=await T.rpc("sidebar.sections",{open:Array.from(ae)}).catch(()=>null);if(fe&&Array.isArray(fe.sections))P=fe.sections}}re=P,Q(P),Z.setData(x,C,I,G),Z.setSections(P,I,G)}else re=null,x=(await T.rpc("projects.list",{limit:100})).projects??[],Z.setSections(null,I,G),Z.setData(x,C,I,G);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{re=null;let[E,A]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);x=E.projects??[],C=A.threads??[],Z.setSections(null,I,G),Z.setData(x,C,I,G),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=N;if(!v){let E="";try{E=localStorage.getItem("bp.lastThread")||""}catch{}if(E&&(re&&X(re,E)||C.some((A)=>A.id===E)))v=E;else if(re)v=q(re);if(!v)v=(C.find((P)=>!P.archived&&!P.swarm&&!P.settled)??C.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(re&&X(re,v)||C.some((E)=>E.id===v)))await we(v);else N="",z=[],Ge.setItems([]),oe.setState(!1,!1),R()}async function we(v){if(N&&N!==v){nt.cancel();let Se=Ce.getEntries();if(Se.length>0){let se=te.get(N);je(N,{entries:Se,ids:se?.ids??Se.map((Ze)=>Ze.id),olderCursor:de,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??z,hashes:se?.hashes??{}})}}let E=++Y;Ie++,Ve(null);let A=Ae;if(Ae=null,A!==null)T.rpc("unsubscribe",{sub:A}).catch(()=>{});N=v;let P=te.get(v);de=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}Z.setSelected(v),ie.classList.remove("bp-sidebar-open"),R();let V=C.find((Se)=>Se.id===v)??null;if(P)Ce.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),z=P.rail,Ge.setItems(P.rail);else Ce.setLoading(V),z=[],Ge.setItems([]);if(oe.setState(!0,V?.state==="working"),T.hasFeature("open")){let Se={};if(P){for(let[Pe,pt]of Object.entries(P.hashes))Se[Pe]=pt;for(let Pe of P.entries)if(Pe.h)Se[Pe.id]=Pe.h}let se;try{se=await T.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Pe){if(E===Y){let pt=Pe instanceof Error&&Pe.message?Pe.message:"Could not load messages.";Ce.setError(V,pt,()=>{we(v)})}return}if(E!==Y){if(se.sub!==void 0&&se.sub!==null)T.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Ae=se.sub??null,se.thread){V=se.thread;let Pe=C.findIndex((pt)=>pt.id===se.thread.id);if(Pe>=0)C[Pe]=se.thread;else C.unshift(se.thread);R(),oe.setState(!0,V.state==="working")}if("next"in se)de=se.next??null;let Ze=new Map;if(P)for(let Pe of P.entries)Ze.set(Pe.id,Pe);for(let Pe of se.entries??[])Ze.set(Pe.id,Pe);let tt=se.ids??P?.ids??(se.entries??[]).map((Pe)=>Pe.id),Cn=tt.map((Pe)=>Ze.get(Pe)).filter((Pe)=>Boolean(Pe)),dt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))dt=se.rail;else if(dt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(be?.reconcileHas?.(se.rail.has),ee&&!Ji(se.rail.has,ee))D(!0)}}z=dt,Ge.setItems(dt);let Ft=P?.review??null;if(T.hasFeature("reviewmode"))try{let Pe=await T.rpc("thread.review",{thread:v});if(E!==Y)return;Ft=Pe.review??null}catch{}if(E!==Y)return;let kn="unanswered"in se?se.unanswered??null:P?.unanswered??null,Zi=se.h??P?.hashes??{};if(je(v,{entries:Cn,ids:tt,olderCursor:de,review:Ft,unanswered:kn,rail:dt,hashes:Zi}),Ce.setThread(V,Cn,Boolean(de),Ft,kn),Be(v,E),ee)U(ee);return}let ne;try{ne=await T.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(E===Y){let se=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";Ce.setError(V,se,()=>{we(v)})}return}if(E!==Y)return;if(ne.thread){let Se=C.findIndex((se)=>se.id===ne.thread.id);if(Se>=0)C[Se]=ne.thread;else C.unshift(ne.thread);R()}de=ne.next??null;let fe=null;if(T.hasFeature("reviewmode"))try{let Se=await T.rpc("thread.review",{thread:v});if(E!==Y)return;fe=Se.review??null}catch{}if(E!==Y)return;let He=ne.entries??[],et=ne.unanswered??null;je(v,{entries:He,ids:He.map((Se)=>Se.id),olderCursor:de,review:fe,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),Ce.setThread(V,He,Boolean(de),fe,et);try{let se=(await T.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(E!==Y){T.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Ae=se}}catch{}if(E!==Y)return;if(F(v,E),Be(v,E),ee)U(ee)}async function Be(v,E){if(!v||!T.hasFeature("mgmt")){if(E===Y)Je.clear();return}let A=C.find((V)=>V.id===v),P=A?.project?x.find((V)=>V.id===A.project)?.root??"":"";if(!P&&T.hasFeature("viewers"))try{let V=await T.rpc("viewer.files",{thread:v});if(E!==Y)return;P=V.pcb||V.sch||V.root||""}catch{}if(E!==Y)return;if(P)await Je.watchProject(P);else Je.clear()}async function Re(v){let E=Y;for(let A=0;A<25&&E===Y;A++){if(Ce.goTo(v))return;if(!de)return;let P=de;if(await We(),de===P)return}}async function We(){if(!N||!de){Ce.clearLoadingOlder();return}let v=Y,E=N,A=de;try{let P=await T.rpc("thread.entries",{thread:E,limit:40,before:A});if(v!==Y||N!==E)return;de=P.next??null,Ce.prependEntries(P.entries??[],Boolean(de))}catch{if(v===Y)Ce.clearLoadingOlder()}}async function De(v){try{let E=await T.rpc("thread.create",{project:v});if(E.thread)C=[E.thread,...C.filter((A)=>A.id!==E.thread.id)],Z.setData(x,C,I,G),he(),await we(E.thread.id),oe.focus()}catch(E){oe.showError(E instanceof Error?E.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` -`).map((E)=>E.trim()).find((E)=>E.length>0)??"").slice(0,200)}function Ve(v){Xe=v,oe.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Re(Xe.id)},()=>Ve(null))}async function wn(v,E=[]){if(!N)return;let A=Y,P=N,V=zs(),ne=`local-${V}`,fe=Xe&&v.trim()&&T.hasFeature("reply")?Xe:null;if(fe)Ve(null);Ce.upsertEntry({id:ne,kind:"user",text:v,at:Date.now(),clientId:V,...fe?{replyTo:{id:fe.id,quote:St(fe.text)}}:{},attachments:E.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:V};if(E.length>0)He.attachments=E;if(fe)He.replyTo={id:fe.id,text:fe.text};let et=await T.rpc("message.send",He);if(A!==Y||N!==P)return;if(et.entry)Ce.upsertEntry(et.entry)}catch(He){if(A===Y&&N===P){if(Ce.removeEntry(ne),oe.setDraft(v),fe&&!Xe)Ve(fe);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function En(v){if(!N)return;let E=Y,A=N;try{let P=await T.rpc("composer.run",{thread:A,text:v});if(E!==Y||N!==A)return;if(P.error)oe.setDraft(v),oe.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")oe.setDraft(P.text);else if(P.kind==="project")Oe.open({mode:"folder"});else if(P.kind==="clone")Oe.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(E===Y&&N===A)oe.setDraft(v),oe.showError(P instanceof Error?P.message:"Command refused")}}async function Qe(v,E){try{let A=await T.rpc("thread.act",{thread:v,action:E});if(A.thread){if(C=C.map((P)=>P.id===A.thread.id?A.thread:P),Z.setData(x,C,I,G),A.thread.id===N)Ce.updateThreadMeta(A.thread),R()}he()}catch(A){oe.showError(A instanceof Error?A.message:`Action "${E}" not allowed`)}}function xn(v,E){if(!v||!v.text||E-v.at>=300000)return"";let A=v.build.split("-").pop()??"";if(v.reason==="build"&&A)return h("hub.restarting.build",v.text,{build:A});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function At(v){if(v==="connected")Z.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&xn(T.restarting,Date.now()))Z.setConnStatus(xn(T.restarting,Date.now()),"");else if(v==="reconnecting")Z.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")Z.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Z.setConnStatus("Connecting…","")}Lt(()=>{At(T.getState()),W.textContent=h("gpui.improvements","Improvements"),pe.title=h("palette.settings","Settings"),pe.setAttribute("aria-label",h("palette.settings","Settings")),R(),Z.refreshLocale(),Ce.refreshLocale(),oe.refreshLocale(),Ge.render(),qe.refreshLocale(),Oe.refreshLocale()}),T.onState((v,E)=>{if(v==="connected"&&E){if(E.locale)Mn(E.locale);if(E.theme)Yi(E.theme);if(E.name)Z.setHostName(E.name);if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();At(v);let A=typeof E.hubBack==="string"?String(E.hubBack):"";if(A)try{let P=JSON.parse(A);if(P.reason==="crash")Z.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>At(T.getState()),6000)}catch{}if(oe.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(E.commands))me=E.commands,oe.setCommands(me);else me=[];Le(),Oe.reconcile()}else nt.cancel(),At(v)}),T.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let E=v;if(E.k==="clone"||E.k==="clone.repos"||E.k==="clone.signin"){Oe.handleFrame(E);return}switch(E.k){case"project":{let A=E.project;if(!A)break;let P=x.findIndex((V)=>V.id===A.id);if(P>=0)x[P]=A;else x.unshift(A);Z.setData(x,C,I,G),R(),ge();break}case"thread":{let A=E.thread;if(!A)break;let P=C.findIndex((V)=>V.id===A.id);if(P>=0)C[P]=A;else C.unshift(A);if(Z.setData(x,C,I,G),A.id===N)Ce.updateThreadMeta(A),R(),oe.setState(!0,A.state==="working");ge();break}case"thread.removed":{let A=String(E.id??"");C=C.filter((P)=>P.id!==A),Z.setData(x,C,I,G),ge();break}case"entry":{if(E.thread===N&&E.entry)Ce.upsertEntry(E.entry);break}case"text":{if(E.thread===N)Ce.appendLiveText(String(E.entry??""),String(E.append??""),Number(E.at??Date.now()));break}case"turn":{if(E.thread===N){let A=String(E.state??"idle");oe.setState(!0,A==="working"),F(N,Y)}ge();break}case"btw":{if(E.thread===N)Ce.showBtw(String(E.q??""),String(E.a??""));break}case"unanswered":{if(E.thread===N)Ce.setUnanswered(E.unanswered??null);break}case"theme":{if(typeof E.theme==="string")Yi(E.theme);break}case"home":{if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let E=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(E==="k"||v.shiftKey&&E==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Oe.isOpen())Oe.escape();else if(qe.isOpen())qe.close();else if(Ce.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Xi);else Xi(); +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,E)=>{try{let A={entry:v,path:E};if(T.hasFeature("blobs"))A.metaOnly=!0;let P=await T.rpc("message.image",A);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function Ue(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function ze(v,E){if(!N)return;let A=Y,P=N;T.rpc(v,E).then((V)=>{if(A!==Y||N!==P)return;if(V.thread){let ne=C.findIndex((ve)=>ve.id===V.thread.id);if(ne>=0)C[ne]=V.thread;else C.unshift(V.thread);Z.setData(x,C,I,D),Ce.updateThreadMeta(V.thread),R(),oe.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(A===Y&&N===P)oe.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let nt,oe=new zt(ye,{onSend:(v,E)=>{wn(v,E)},onRunCommand:(v)=>{En(v)},onInterrupt:()=>{if(N)T.rpc("turn.interrupt",{thread:N}).catch(()=>{})},onQueryMentions:async(v,E)=>{try{return(await T.rpc("mentions.list",{q:v,kind:E,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=C.find((A)=>A.id===N)??null,E=Ue(v);if(!E||!N)return;if(E.interaction!=="plan")ze("thread.planonce",{thread:N,on:!0});else if(E.once)ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!N)return;if(v==="once")ze("thread.planonce",{thread:N,on:!0});else if(v==="always")ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})}});nt=new cn(T,{getThreadId:()=>N,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function lt(){let v=ee!=="",E=Je.isOpen();ke.classList.toggle("bp-hidden",!v&&!E),ke.classList.toggle("bp-has-viewer",v),ke.classList.toggle("bp-has-mgmt",E)}let Je=new tn(Ne,ke,{hub:T,getThreadId:()=>N,getThreadGen:()=>Y,onSendText:(v)=>{wn(v)},onOpenChange:()=>lt()});function ct(v){let E=window.prompt("Rename thread",v.title||"");if(!E||!E.trim())return;T.rpc("thread.act",{thread:v.id,action:"rename",title:E.trim()}).then((A)=>{if(A.thread)C=C.map((P)=>P.id===A.thread.id?A.thread:P),R(),he()}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":we(v.id);break;case"rail":if(!N&&v.id!=="terminal")break;if(ee===v.id)F();else U(v.id);break;case"thread-act":if(N)Qe(N,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let E=C.find((A)=>A.id===N);if(E)ct(E);break}case"prev-thread":case"next-thread":{let E=C.filter((ne)=>!ne.archived&&!ne.swarm);if(E.length<2)break;let A=E.findIndex((ne)=>ne.id===N),P=v.type==="next-thread"?1:-1,V=E[(A<0?0:A+P+E.length)%E.length];if(V)we(V.id);break}case"command":if(v.runDirectly)En(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":kt();break;case"settings":qe.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let $e=new nn(e,{getState:()=>({selectedThreadId:N,threads:C,projects:x,bots:I,railItems:K,commands:le}),onSearch:async(v)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:v,limit:20})},onExecute:Ye}),Oe=new Vt(e,{hub:T,onProjectAdded:(v)=>{if(he(),v.id)De(v.id)},onCloneDone:(v)=>{if(he(),v.thread)we(v.thread)}}),Ge=new sn(Me,(v)=>{if(v==="commands"){$e.open();return}if(!N)return;if(ee===v)F();else U(v)}),it=null,qe=new an(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,E)=>{await T.rpc("devices.page.act",{action:v,value:E})},onGetHome:()=>it,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>Hn(()=>{T.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let Dt=new on(e,(v,E)=>E?T.rpc("thread.context.mcp",{thread:v,...E}):T.rpc("thread.context",{thread:v}));L.addEventListener("click",(v)=>{v.stopPropagation();let E=C.find((V)=>V.id===N);if(!E)return;if(!M.classList.contains("bp-hidden")){M.classList.add("bp-hidden");return}let A=[{label:"Rename…",run:()=>ct(E)},{label:E.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(E.id,E.pinned?"unpin":"pin")}},{label:E.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(E.id,E.settled?"unsettle":"settle")}},{label:E.archived?"Unarchive":"Archive",run:()=>{Qe(E.id,E.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(E.id,"delete")}}];if(T.hasFeature("threadContext"))A.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Dt.open(E.id)});let P=document.createDocumentFragment();for(let V of A){let ne=document.createElement("button");ne.type="button",ne.className="bp-popover-item"+(V.danger?" danger":""),ne.textContent=V.label,ne.addEventListener("click",()=>{M.classList.add("bp-hidden"),V.run()}),P.appendChild(ne)}M.replaceChildren(P),M.classList.remove("bp-hidden")}),document.addEventListener("click",()=>M.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let E=document.createElement("div");E.className="bp-modal";let A=document.createElement("div");A.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),A.append(P,V);let ne=document.createElement("div");ne.className="bp-modal-body",ne.textContent="Loading…",E.append(A,ne),v.appendChild(E),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await T.rpc("improvements.projects",{}),He=ve.projects??[];if(He.length===0){ne.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Se of He){let ae=document.createElement("div");ae.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Se.title||Se.name||Se.id;let tt=document.createElement("button");tt.type="button",tt.className=Se.id===ve.project?"primary":"",tt.textContent=Se.id===ve.project?"Active":"Select",tt.addEventListener("click",()=>{T.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),ae.append(Ze,tt),et.appendChild(ae)}ne.replaceChildren(et)}catch(ve){ne.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}H.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>$e.open()),j.addEventListener("click",()=>$e.open()),me.addEventListener("click",()=>{qe.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function R(){let v=C.find((P)=>P.id===N)??null,E=v?x.find((P)=>P.id===v.project):void 0;o.textContent=E?.title??"",r.classList.toggle("bp-hidden",!E),c.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let A=Ue(v);if(oe.setPlanMode(A),!A||A.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",A.phase==="executing"),l.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=A.phase==="armed"&&A.once?h("gpui.planmode.top.once","Plan (1 turn)"):A.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):A.phase==="planning"?h("gpui.planmode.top.planning","Planning"):A.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){p.className=`bp-dot ${Ks(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),k.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;oe.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function F(v=!0){if(Ie++,ee="",Ge.setActive(""),ge.classList.add("bp-hidden"),be?.close(),lt(),v&&N&&T.getState()==="connected")T.rpc("viewer.watch",{thread:N,kind:""}).catch(()=>{})}function U(v){if(Ie++,ee=v,Ge.setActive(v),ge.classList.remove("bp-hidden"),lt(),!be&&typeof yn==="function")be=yn(ge,{hub:T,getThreadId:()=>N,closeViewer:()=>F(!0)});if(be)be.open(v,N);else{let E=document.createElement("div");E.className="bp-viewer-placeholder";let A=document.createElement("div");A.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>F(!0)),A.append(P,V);let ne=document.createElement("div");ne.className="bp-dim bp-viewer-msg",ne.textContent=`Viewer pane (${v}).`,E.append(A,ne),ge.replaceChildren(E)}}async function G(v,E){if(!v||!T.hasFeature("rail")){if(E===Y)K=[],Ge.setItems([]);return}let A=++Ie;try{let P=await T.rpc("viewer.rail",{thread:v,page:ee});if(E!==Y||A!==Ie)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(K=V,Ge.setItems(V),P.has){if(be?.reconcileHas?.(P.has),ee&&!Ji(P.has,ee))F(!0)}}catch{if(E===Y&&A===Ie)K=[],Ge.setItems([])}}function q(v){for(let E of v)if(E.kind==="threads"){for(let A of E.rows)if(!A.off&&(A.nav||A.id)&&!(A.nav||"").startsWith("@room:"))return A.nav||A.id}else if(E.kind==="projects"){for(let A of E.rows)for(let P of A.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function X(v,E){for(let A of v)if(A.kind==="threads"){if(A.rows.some((P)=>(P.nav||P.id)===E))return!0}else if(A.kind==="projects"){for(let P of A.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===E))return!0}return!1}function Q(v){let E=[];for(let A of v){if(A.kind!=="projects")continue;for(let P of A.rows)E.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(E.length>0)x=E}async function he(){if(!T.hasFeature("sections"))return!1;let v=++J;try{let E=await T.rpc("sidebar.sections",{open:Array.from(se)});if(v!==J)return!0;let A=Array.isArray(E.sections)?E.sections:[];return re=A,Q(A),Z.setData(x,C,I,D),Z.setSections(A,I,D),R(),!0}catch{return!1}}function fe(){if(!T.hasFeature("sections"))return;if(de!==null)window.clearTimeout(de);de=window.setTimeout(()=>{de=null,he()},150)}async function Le(){if(Ae=null,T.hasFeature("bots"))try{let E=await T.rpc("bots.list",{});I=E.bots??[],D=E.rooms??[]}catch{}if(T.hasFeature("shell")){let E=await T.rpc("shell.sync",{have:ue,settled:25}),A=new Set(E.removed??[]),P=new Set((E.projects??[]).map((V)=>V.id));if(A.size>0||P.size>0)x=[...x.filter((V)=>!A.has(V.id)&&!P.has(V.id)),...E.projects??[]],C=[...C.filter((V)=>!A.has(V.project)&&!P.has(V.project)),...E.threads??[]];else if(Array.isArray(E.threads)&&E.threads.length>0){let V=new Map(C.map((ne)=>[ne.id,ne]));for(let ne of E.threads)V.set(ne.id,ne);C=Array.from(V.values())}if(E.sections!==void 0){let V=Array.isArray(E.sections)?E.sections:Array.isArray(E.sections?.sections)?E.sections.sections:null;if(V)re=V,Q(V)}if(E.h)ue=E.h;Z.setData(x,C,I,D),Z.setSections(re,I,D)}else if(T.hasFeature("sections")){let[E,A]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(se)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(C=A.threads??[],E&&Array.isArray(E.sections)){let P=E.sections;if(!P.some((ne)=>ne.kind==="projects"&&ne.rows.length>0)){let ne=P.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(ne?.toggle&&!se.has(ne.toggle)){se.add(ne.toggle);let ve=await T.rpc("sidebar.sections",{open:Array.from(se)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))P=ve.sections}}re=P,Q(P),Z.setData(x,C,I,D),Z.setSections(P,I,D)}else re=null,x=(await T.rpc("projects.list",{limit:100})).projects??[],Z.setSections(null,I,D),Z.setData(x,C,I,D);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{re=null;let[E,A]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);x=E.projects??[],C=A.threads??[],Z.setSections(null,I,D),Z.setData(x,C,I,D),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=N;if(!v){let E="";try{E=localStorage.getItem("bp.lastThread")||""}catch{}if(E&&(re&&X(re,E)||C.some((A)=>A.id===E)))v=E;else if(re)v=q(re);if(!v)v=(C.find((P)=>!P.archived&&!P.swarm&&!P.settled)??C.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(re&&X(re,v)||C.some((E)=>E.id===v)))await we(v);else N="",K=[],Ge.setItems([]),oe.setState(!1,!1),R()}async function we(v){if(N&&N!==v){nt.cancel();let Se=Ce.getEntries();if(Se.length>0){let ae=te.get(N);je(N,{entries:Se,ids:ae?.ids??Se.map((Ze)=>Ze.id),olderCursor:pe,review:ae?.review??null,unanswered:ae?.unanswered??null,rail:ae?.rail??K,hashes:ae?.hashes??{}})}}let E=++Y;Ie++,Ve(null);let A=Ae;if(Ae=null,A!==null)T.rpc("unsubscribe",{sub:A}).catch(()=>{});N=v;let P=te.get(v);pe=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}Z.setSelected(v),ie.classList.remove("bp-sidebar-open"),R();let V=C.find((Se)=>Se.id===v)??null;if(P)Ce.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),K=P.rail,Ge.setItems(P.rail);else Ce.setLoading(V),K=[],Ge.setItems([]);if(oe.setState(!0,V?.state==="working"),T.hasFeature("open")){let Se={};if(P){for(let[Pe,pt]of Object.entries(P.hashes))Se[Pe]=pt;for(let Pe of P.entries)if(Pe.h)Se[Pe.id]=Pe.h}let ae;try{ae=await T.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Pe){if(E===Y){let pt=Pe instanceof Error&&Pe.message?Pe.message:"Could not load messages.";Ce.setError(V,pt,()=>{we(v)})}return}if(E!==Y){if(ae.sub!==void 0&&ae.sub!==null)T.rpc("unsubscribe",{sub:ae.sub}).catch(()=>{});return}if(Ae=ae.sub??null,ae.thread){V=ae.thread;let Pe=C.findIndex((pt)=>pt.id===ae.thread.id);if(Pe>=0)C[Pe]=ae.thread;else C.unshift(ae.thread);R(),oe.setState(!0,V.state==="working")}if("next"in ae)pe=ae.next??null;let Ze=new Map;if(P)for(let Pe of P.entries)Ze.set(Pe.id,Pe);for(let Pe of ae.entries??[])Ze.set(Pe.id,Pe);let tt=ae.ids??P?.ids??(ae.entries??[]).map((Pe)=>Pe.id),Cn=tt.map((Pe)=>Ze.get(Pe)).filter((Pe)=>Boolean(Pe)),dt=P?.rail??[];if(ae.rail!==void 0){if(Array.isArray(ae.rail))dt=ae.rail;else if(dt=Array.isArray(ae.rail?.rail)?ae.rail.rail:Array.isArray(ae.rail?.items)?ae.rail.items:[],ae.rail?.has){if(be?.reconcileHas?.(ae.rail.has),ee&&!Ji(ae.rail.has,ee))F(!0)}}K=dt,Ge.setItems(dt);let Ft=P?.review??null;if(T.hasFeature("reviewmode"))try{let Pe=await T.rpc("thread.review",{thread:v});if(E!==Y)return;Ft=Pe.review??null}catch{}if(E!==Y)return;let kn="unanswered"in ae?ae.unanswered??null:P?.unanswered??null,Zi=ae.h??P?.hashes??{};if(je(v,{entries:Cn,ids:tt,olderCursor:pe,review:Ft,unanswered:kn,rail:dt,hashes:Zi}),Ce.setThread(V,Cn,Boolean(pe),Ft,kn),Be(v,E),ee)U(ee);return}let ne;try{ne=await T.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(E===Y){let ae=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";Ce.setError(V,ae,()=>{we(v)})}return}if(E!==Y)return;if(ne.thread){let Se=C.findIndex((ae)=>ae.id===ne.thread.id);if(Se>=0)C[Se]=ne.thread;else C.unshift(ne.thread);R()}pe=ne.next??null;let ve=null;if(T.hasFeature("reviewmode"))try{let Se=await T.rpc("thread.review",{thread:v});if(E!==Y)return;ve=Se.review??null}catch{}if(E!==Y)return;let He=ne.entries??[],et=ne.unanswered??null;je(v,{entries:He,ids:He.map((Se)=>Se.id),olderCursor:pe,review:ve,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),Ce.setThread(V,He,Boolean(pe),ve,et);try{let ae=(await T.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(ae!==null){if(E!==Y){T.rpc("unsubscribe",{sub:ae}).catch(()=>{});return}Ae=ae}}catch{}if(E!==Y)return;if(G(v,E),Be(v,E),ee)U(ee)}async function Be(v,E){if(!v||!T.hasFeature("mgmt")){if(E===Y)Je.clear();return}let A=C.find((V)=>V.id===v),P=A?.project?x.find((V)=>V.id===A.project)?.root??"":"";if(!P&&T.hasFeature("viewers"))try{let V=await T.rpc("viewer.files",{thread:v});if(E!==Y)return;P=V.pcb||V.sch||V.root||""}catch{}if(E!==Y)return;if(P)await Je.watchProject(P);else Je.clear()}async function Re(v){let E=Y;for(let A=0;A<25&&E===Y;A++){if(Ce.goTo(v))return;if(!pe)return;let P=pe;if(await We(),pe===P)return}}async function We(){if(!N||!pe){Ce.clearLoadingOlder();return}let v=Y,E=N,A=pe;try{let P=await T.rpc("thread.entries",{thread:E,limit:40,before:A});if(v!==Y||N!==E)return;pe=P.next??null,Ce.prependEntries(P.entries??[],Boolean(pe))}catch{if(v===Y)Ce.clearLoadingOlder()}}async function De(v){try{let E=await T.rpc("thread.create",{project:v});if(E.thread)C=[E.thread,...C.filter((A)=>A.id!==E.thread.id)],Z.setData(x,C,I,D),he(),await we(E.thread.id),oe.focus()}catch(E){oe.showError(E instanceof Error?E.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` +`).map((E)=>E.trim()).find((E)=>E.length>0)??"").slice(0,200)}function Ve(v){Xe=v,oe.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Re(Xe.id)},()=>Ve(null))}async function wn(v,E=[]){if(!N)return;let A=Y,P=N,V=zs(),ne=`local-${V}`,ve=Xe&&v.trim()&&T.hasFeature("reply")?Xe:null;if(ve)Ve(null);Ce.upsertEntry({id:ne,kind:"user",text:v,at:Date.now(),clientId:V,...ve?{replyTo:{id:ve.id,quote:St(ve.text)}}:{},attachments:E.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:V};if(E.length>0)He.attachments=E;if(ve)He.replyTo={id:ve.id,text:ve.text};let et=await T.rpc("message.send",He);if(A!==Y||N!==P)return;if(et.entry)Ce.upsertEntry(et.entry)}catch(He){if(A===Y&&N===P){if(Ce.removeEntry(ne),oe.setDraft(v),ve&&!Xe)Ve(ve);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function En(v){if(!N)return;let E=Y,A=N;try{let P=await T.rpc("composer.run",{thread:A,text:v});if(E!==Y||N!==A)return;if(P.error)oe.setDraft(v),oe.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")oe.setDraft(P.text);else if(P.kind==="project")Oe.open({mode:"folder"});else if(P.kind==="clone")Oe.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(E===Y&&N===A)oe.setDraft(v),oe.showError(P instanceof Error?P.message:"Command refused")}}async function Qe(v,E){try{let A=await T.rpc("thread.act",{thread:v,action:E});if(A.thread){if(C=C.map((P)=>P.id===A.thread.id?A.thread:P),Z.setData(x,C,I,D),A.thread.id===N)Ce.updateThreadMeta(A.thread),R()}he()}catch(A){oe.showError(A instanceof Error?A.message:`Action "${E}" not allowed`)}}function xn(v,E){if(!v||!v.text||E-v.at>=300000)return"";let A=v.build.split("-").pop()??"";if(v.reason==="build"&&A)return h("hub.restarting.build",v.text,{build:A});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function At(v){if(v==="connected")Z.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&xn(T.restarting,Date.now()))Z.setConnStatus(xn(T.restarting,Date.now()),"");else if(v==="reconnecting")Z.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")Z.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Z.setConnStatus("Connecting…","")}Lt(()=>{At(T.getState()),W.textContent=h("gpui.improvements","Improvements"),me.title=h("palette.settings","Settings"),me.setAttribute("aria-label",h("palette.settings","Settings")),R(),Z.refreshLocale(),Ce.refreshLocale(),oe.refreshLocale(),Ge.render(),qe.refreshLocale(),Oe.refreshLocale()}),T.onState((v,E)=>{if(v==="connected"&&E){if(E.locale)Mn(E.locale);if(E.theme)Yi(E.theme);if(E.name)Z.setHostName(E.name);if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();At(v);let A=typeof E.hubBack==="string"?String(E.hubBack):"";if(A)try{let P=JSON.parse(A);if(P.reason==="crash")Z.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>At(T.getState()),6000)}catch{}if(oe.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(E.commands))le=E.commands,oe.setCommands(le);else le=[];Le(),Oe.reconcile()}else nt.cancel(),At(v)}),T.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let E=v;if(E.k==="clone"||E.k==="clone.repos"||E.k==="clone.signin"){Oe.handleFrame(E);return}switch(E.k){case"project":{let A=E.project;if(!A)break;let P=x.findIndex((V)=>V.id===A.id);if(P>=0)x[P]=A;else x.unshift(A);Z.setData(x,C,I,D),R(),fe();break}case"thread":{let A=E.thread;if(!A)break;let P=C.findIndex((V)=>V.id===A.id);if(P>=0)C[P]=A;else C.unshift(A);if(Z.setData(x,C,I,D),A.id===N)Ce.updateThreadMeta(A),R(),oe.setState(!0,A.state==="working");fe();break}case"thread.removed":{let A=String(E.id??"");C=C.filter((P)=>P.id!==A),Z.setData(x,C,I,D),fe();break}case"entry":{if(E.thread===N&&E.entry)Ce.upsertEntry(E.entry);break}case"text":{if(E.thread===N)Ce.appendLiveText(String(E.entry??""),String(E.append??""),Number(E.at??Date.now()));break}case"turn":{if(E.thread===N){let A=String(E.state??"idle");oe.setState(!0,A==="working"),G(N,Y)}fe();break}case"btw":{if(E.thread===N)Ce.showBtw(String(E.q??""),String(E.a??""));break}case"unanswered":{if(E.thread===N)Ce.setUnanswered(E.unanswered??null);break}case"theme":{if(typeof E.theme==="string")Yi(E.theme);break}case"home":{if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let E=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(E==="k"||v.shiftKey&&E==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Oe.isOpen())Oe.escape();else if(qe.isOpen())qe.close();else if(Ce.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Xi);else Xi(); diff --git a/web/dist/manifest.json b/web/dist/manifest.json index cdab82f165..ca32e4880c 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 200377, + "totalAssetGzipBytes": 200464, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -279,7 +279,7 @@ "web/src/logout.ts": "9d29482c4671deee1e868ee477b123e067a4c22f7d8ac30b4c2420cf71b8ebe2", "web/src/md.ts": "c606d1ec598b3ce132c7cc9366383dacafc3fcb71c0fccd97b41ec0e19a96c78", "web/src/mgmt-model.ts": "5135cce33f870d5b45b9fd8c2eb91f62fa7d274cd961cd523ed0df599893c955", - "web/src/mgmt.ts": "c28da4e358ddc0ae1854e7343fb33cdcc89c953f2537ee4a5fee111f687d76fe", + "web/src/mgmt.ts": "29d968b9601dda45a85dd70f378c4e15f2abb3108124f5974c33b02b84c1ce2d", "web/src/pair.html": "cf7b94703316f910718356e9ff8e99e088b68211db39b5200213b623c9275f6e", "web/src/pair.ts": "af07d19224043f8176f8cd2298d00b6806248eee453fd2f287c183e71a08179b", "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", @@ -317,9 +317,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 332727, - "gzipBytes": 93791, - "sha256": "7239bcb9bef8033954fc9426efff1938728f548e8bef177a26496f154e9d3e76" + "bytes": 333026, + "gzipBytes": 93878, + "sha256": "c418ffce805c12fcd0733b3515d603e838904c7558daf32207a781a24b13c63d" }, "assets/favicon-light.svg": { "bytes": 1207, diff --git a/web/src/mgmt.ts b/web/src/mgmt.ts index 2f2ecefa45..75f434bbe1 100644 --- a/web/src/mgmt.ts +++ b/web/src/mgmt.ts @@ -101,6 +101,7 @@ export class MgmtStrip { private planHydratedDraw: { bands?: PlanBand[]; regions?: PlanRegion[] } | null = null; private planNoteOpen = false; private planCanvas: PlanFloorplannerCanvas | null = null; + private planCommitFields: ((id: string, fields: Record) => void) | null = null; private fabStatus = ""; @@ -168,6 +169,7 @@ export class MgmtStrip { this.planNoteOpen = false; this.planCanvas?.destroy(); this.planCanvas = null; + this.planCommitFields = null; this.fabStatus = ""; this.render(); } @@ -1440,9 +1442,21 @@ export class MgmtStrip { this.planShownLayers = activeLayers.length >= 2 ? [activeLayers[0], fields.layer] : [...activeLayers, fields.layer]; } } + const wireFields: Record = { ...fields }; + if ( + Array.isArray(fields.outline) && + Array.isArray((fields.outline as unknown[])[0]) && + typeof ((fields.outline as unknown[])[0] as unknown[])[0] === "number" + ) { + const reg = mergedRegions.find((r) => r.id === id); + if (reg?.holes && reg.holes.length > 0) { + wireFields.outline = [fields.outline, ...reg.holes]; + } + } this.render(); - sendPlan("plan.update", { ops: [{ op: "set", id, fields }] }); + sendPlan("plan.update", { ops: [{ op: "set", id, fields: wireFields }] }); }; + this.planCommitFields = commitItemFields; if (this.planSelectedId) { let selLayer = ""; @@ -1781,7 +1795,7 @@ export class MgmtStrip { this.planOptimistic.set(id, { ...prev, ...fields }); }, onCommitFields: (id, fields) => { - commitItemFields(id, fields); + (this.planCommitFields ?? commitItemFields)(id, fields); }, onApproveLayer: (layer, approve) => { sendPlan("plan.approve", { layer, ids: [], approve }); From 00bc9c17b005be70fe36d44add817afbdd24eb67 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 22:27:14 -0500 Subject: [PATCH 3/5] plan: address review findings on base revisions, budget caps, browser auth, and pointer capture --- native/gpui/src/screens/mgmt_plan.rs | 20 +- native/gpui/src/screens/mgmt_plan_canvas.rs | 104 +++++++++- native/host/src/data/ext.rs | 129 +++++++++++- native/host/src/plan/geom.rs | 31 ++- native/host/src/plan/mod.rs | 217 ++++++++++++++++---- native/host/src/plan/panel.rs | 128 ++++++++++-- web/dist/assets/app.js | 36 ++-- web/dist/manifest.json | 14 +- web/src/mgmt-model.ts | 46 +++++ web/src/mgmt.ts | 61 ++++-- web/src/plan-canvas.ts | 74 ++++--- web/test/mgmt.test.ts | 15 ++ 12 files changed, 729 insertions(+), 146 deletions(-) diff --git a/native/gpui/src/screens/mgmt_plan.rs b/native/gpui/src/screens/mgmt_plan.rs index 163a3ef908..80a9012c83 100644 --- a/native/gpui/src/screens/mgmt_plan.rs +++ b/native/gpui/src/screens/mgmt_plan.rs @@ -303,13 +303,15 @@ pub fn body(app: &mut Backplane, d: &Value, light: bool, cx: &mut Context = mgmt_plan_canvas::visible_layers(&app.screens.mgmt.plan_ui, &all_layers_arr) + let copper_arr = d["copper_layers"].as_array().map(Vec::as_slice).unwrap_or(&[]); + let canvas_layers = mgmt_plan_canvas::all_canvas_layers(&all_layers_arr, copper_arr); + let shown_names: Vec = mgmt_plan_canvas::visible_layers(&app.screens.mgmt.plan_ui, &canvas_layers) .iter() .filter_map(|l| l["layer"].as_str().map(str::to_string)) .collect(); - let layer_bar = (view_mode != ViewMode::List && all_layers_arr.len() > 1).then(|| { + let layer_bar = (view_mode != ViewMode::List && canvas_layers.len() > 1).then(|| { let mut row = div().flex_shrink_0().flex().flex_wrap().items_center().gap(px(4.)).px_2().py(px(3.)).border_b_1().border_color(c("rule")).bg(c("bg")).text_size(crate::scale::tpx(10.)); - for l in &all_layers_arr { + for l in &canvas_layers { let lname = s(l, "layer").to_string(); let title = l["title"].as_str().filter(|x| !x.is_empty()).unwrap_or(&lname).to_string(); let active = shown_names.contains(&lname); @@ -451,7 +453,11 @@ pub fn body(app: &mut Backplane, d: &Value, light: bool, cx: &mut Context, pub optimistic_at: Option, pub last_rev: Option, + pub hydrated_req_key: String, + pub hydrated_req_pro: String, pub hydrated_key: String, pub hydrated_board: Option, pub hydrated_draw: Option, @@ -187,6 +189,8 @@ impl Default for State { optimistic: HashMap::new(), optimistic_at: None, last_rev: None, + hydrated_req_key: String::new(), + hydrated_req_pro: String::new(), hydrated_key: String::new(), hydrated_board: None, hydrated_draw: None, @@ -211,6 +215,8 @@ impl State { self.optimistic.clear(); self.optimistic_at = None; self.last_rev = None; + self.hydrated_req_key.clear(); + self.hydrated_req_pro.clear(); self.hydrated_key.clear(); self.hydrated_board = None; self.hydrated_draw = None; @@ -696,14 +702,31 @@ pub fn resolved_board_and_draw(app: &Backplane, d: &Value) -> (Value, Value) { (board, merge_optimistic_into_draw(&raw_draw, &ui.optimistic)) } +pub fn unwrap_board_panel(reply: &Value) -> Option<&Value> { + if reply["ok"] == false { + return None; + } + if reply["result"].is_object() && reply["result"]["panel"].is_object() { + Some(&reply["result"]["panel"]) + } else if reply["panel"].is_object() { + Some(&reply["panel"]) + } else { + None + } +} + pub fn board_answered(app: &mut Backplane, reply: &Value, cx: &mut Context) { + let Some(panel) = unwrap_board_panel(reply).cloned() else { + return; + }; + let pro = app.screens.mgmt.project.clone(); let ui = &mut app.screens.mgmt.plan_ui; - let panel = &reply["panel"]; - if panel.is_null() { + if !ui.hydrated_req_pro.is_empty() && ui.hydrated_req_pro != pro { return; } let rev = panel["revision"].as_u64().unwrap_or(0); - ui.hydrated_key = format!("{}:{rev}", app.screens.mgmt.project); + ui.hydrated_key = format!("{pro}:{rev}"); + ui.hydrated_req_key = ui.hydrated_key.clone(); ui.hydrated_board = Some(panel["board"].clone()); ui.hydrated_draw = Some(panel["draw"].clone()); cx.notify(); @@ -724,8 +747,9 @@ pub fn sync_revision_and_hydrate(app: &mut Backplane, d: &Value) { } } let key = format!("{pro}:{}", rev.unwrap_or(0)); - if d["board_trimmed"] == true && ui.hydrated_key != key && !pro.is_empty() { - ui.hydrated_key = key; + if d["board_trimmed"] == true && ui.hydrated_req_key != key && !pro.is_empty() { + ui.hydrated_req_key = key; + ui.hydrated_req_pro = pro.clone(); let _ = app.tx.try_send(Command::Ask("plan.get".into(), json!({"pro": pro, "board": true}), BOARD_TAG)); } } @@ -743,10 +767,11 @@ pub fn apply_optimistic(app: &mut Backplane, id: &str, patch: Value) { pub fn commit_item_fields(app: &mut Backplane, id: &str, fields: Value, cx: &mut Context) { apply_optimistic(app, id, fields.clone()); + let d = app.screens.mgmt.data("plan"); + let base = d["revision"].as_u64(); let mut wire_fields = fields; if let Some(outer) = wire_fields.get("outline").cloned() { if outer.as_array().and_then(|a| a.first()).and_then(|p| p.as_array()).and_then(|p| p.first()).and_then(Value::as_f64).is_some() { - let d = app.screens.mgmt.data("plan"); let (_, draw) = resolved_board_and_draw(app, &d); if let Some(holes) = draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == id).and_then(|r| r["holes"].as_array()).filter(|h| !h.is_empty()) { let mut rings = Vec::with_capacity(1 + holes.len()); @@ -758,7 +783,11 @@ pub fn commit_item_fields(app: &mut Backplane, id: &str, fields: Value, cx: &mut } } } - mgmt_plan::send(app, "plan.update", json!({"ops": [{"op": "set", "id": id, "fields": wire_fields}]}), cx); + let mut payload = json!({"ops": [{"op": "set", "id": id, "fields": wire_fields}]}); + if let Some(b) = base { + payload["base"] = json!(b); + } + mgmt_plan::send(app, "plan.update", payload, cx); } fn board_bbox_f32(board: &Value) -> [f32; 4] { @@ -1264,6 +1293,44 @@ fn set_cam(ui: &mut State, layer: &str, cam: Camera) { } } +pub fn all_canvas_layers(layers: &[Value], copper_layers: &[Value]) -> Vec { + if copper_layers.is_empty() { + return layers.to_vec(); + } + let mut out = Vec::with_capacity(copper_layers.len().max(layers.len())); + let mut seen: HashSet = HashSet::new(); + for cl in copper_layers { + let Some(name) = cl["layer"].as_str().filter(|s| !s.is_empty()) else { continue }; + seen.insert(name.to_string()); + if let Some(existing) = layers.iter().find(|l| l["layer"].as_str() == Some(name)) { + out.push(existing.clone()); + } else { + let idx = cl["index"].as_u64().unwrap_or((out.len() + 1) as u64); + let title = cl["title"].as_str().filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| format!("L{idx} · {name}")); // i18n-ok: layer stackup code + out.push(json!({ + "layer": name, + "index": idx, + "title": title, + "subtitle": cl["subtitle"].as_str().unwrap_or(""), + "role": cl["role"].as_str().unwrap_or(""), + "status": "proposed", + "done": 0, + "approved": 0, + "total": 0, + "items": [] + })); + } + } + for l in layers { + if let Some(name) = l["layer"].as_str() { + if !seen.contains(name) { + out.push(l.clone()); + } + } + } + out +} + pub fn visible_layers(ui: &State, layers: &[Value]) -> Vec { if layers.is_empty() { return Vec::new(); @@ -1343,7 +1410,9 @@ pub fn view(app: &mut Backplane, d: &Value, light: bool, cx: &mut Context, c: &mut Conn, m: &str, p: &Value, is_browser: rpc(hub, c, "order.buy", json!({"thread":th})).await.map(|r| json!({"thread":r["thread"]})) } // feature "fabprofile": the project's fab profile (fab/mod.rs Fab.view), the same the desktop and the agents' fab_profile read; `action` get, pick or seen // feature "plan": the routing plan's person-side calls (plan/mod.rs): approve, steer/update, stop routing, verify, focus an item, read board geometry, or toggle plan-before-routing - "plan.approve" | "plan.update" | "plan.stop" | "plan.verify" | "plan.focus" | "plan.get" | "plan.enable" => { if m != "plan.enable" && s(p, "pro").is_empty() && s(p, "path").is_empty() { return Some(Err(err("pro (the project's .kicad_pro)"))) } - rpc(hub, c, m, p.clone()).await.map(|r| json!({"result": r["result"]})) } + "plan.approve" | "plan.update" | "plan.stop" | "plan.verify" | "plan.focus" | "plan.get" | "plan.enable" => { + if m != "plan.enable" && s(p, "pro").is_empty() && s(p, "path").is_empty() { + return Some(Err(err("pro (the project's .kicad_pro)"))) + } + match if is_browser { sanitize_browser_plan_params(hub, m, p).await } else { Ok(p.clone()) } { + Ok(q) => rpc(hub, c, m, q).await.map(|r| json!({"result": r["result"]})), + Err(e) => Err(e), + } + } // feature "mgmt": the management panels (docs/MANAGEMENT.md) and the design checks, the same calls the desktop makes; a BOM edit from the // phone is the person's, as the desktop's (kicad/bomedit.rs) "mgmt.watch" | "mgmt.panel" | "mgmt.bom.edit" | "mgmt.bom.alts" | "mgmt.life.part" | "kicad.checks.watch" | "kicad.checks.list" | "kicad.checks.run" | "kicad.checks.focus" | "kicad.checks.fix" => { @@ -732,6 +739,89 @@ async fn review(hub: &Arc, c: &mut Conn, m: &str, p: &Value) -> Option bool { + let home = crate::plat::fs::canonicalize(std::path::Path::new(&crate::plat::dirs::home_or_empty())).ok(); + p.parent().is_none() || home.as_ref().map_or(false, |h| h == p) +} + +fn check_browser_plan_path(roots: &[std::path::PathBuf], home: &std::path::Path, raw: &str) -> Result<(std::path::PathBuf, std::path::PathBuf), &'static str> { + let full = crate::files::share::local_path(raw).ok_or("that path is not in a project")?; + let real = crate::plat::fs::canonicalize(&full).map_err(|_| "no such file or project")?; + let real_home = crate::plat::fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf()); + if real.starts_with(&real_home) || !roots.iter().any(|r| real.starts_with(r)) { + return Err("that path is not in a project"); + } + let pcb_raw = if real.extension().and_then(|e| e.to_str()) == Some("kicad_pcb") { + real.to_string_lossy().into_owned() + } else { + let dir = if real.is_dir() { real.as_path() } else { real.parent().unwrap_or(real.as_path()) }; + crate::files::kicad::project::read(&dir.to_string_lossy()).pcb + }; + if pcb_raw.is_empty() { + return Err("no KiCad board in this project"); + } + let real_pcb = crate::plat::fs::canonicalize(std::path::Path::new(&pcb_raw)).map_err(|_| "no such board")?; + if real_pcb.starts_with(&real_home) || !roots.iter().any(|r| real_pcb.starts_with(r)) { + return Err("that board is not in a project"); + } + if !real_pcb.parent().map_or(false, |p| roots.iter().any(|r| p.starts_with(r))) { + return Err("that board is not in a project"); + } + let sidecar = real_pcb.with_extension("kicad_plan"); + if let Ok(md) = std::fs::symlink_metadata(&sidecar) { + if md.file_type().is_symlink() { + return Err("that routing plan is not shared"); + } + let real_sidecar = crate::plat::fs::canonicalize(&sidecar).map_err(|_| "that routing plan is not shared")?; + if real_sidecar.starts_with(&real_home) || !roots.iter().any(|r| real_sidecar.starts_with(r)) { + return Err("that routing plan is not shared"); + } + } + Ok((real, real_pcb)) +} + +async fn sanitize_browser_plan_params(hub: &Arc, m: &str, p: &Value) -> Result { + let raw = if !s(p, "pro").is_empty() { s(p, "pro") } else { s(p, "path") }; + if raw.is_empty() { + if m == "plan.enable" { + return Ok(p.clone()); + } + return Err(err("pro (the project's .kicad_pro)")); + } + let roots = { + let g = hub.model().await; + let mut raw_roots: Vec = Vec::new(); + for proj in g.projects.values().filter(|pr| !pr.removed && !pr.root.is_empty()) { + raw_roots.push(proj.root.clone()); + raw_roots.push(crate::files::kicad::canonical::design_root(&proj.root)); + } + for t in g.threads.values().filter(|t| !t.deleted && !t.worktree.is_empty()) { + raw_roots.push(crate::files::kicad::canonical::design_root(&t.worktree)); + } + let mut out = Vec::new(); + for r in raw_roots { + if let Ok(c) = crate::plat::fs::canonicalize(std::path::Path::new(&r)) { + if c.is_dir() && !out.contains(&c) && !too_wide_plan_root(&c) { + out.push(c); + } + } + } + out + }; + let (real, real_pcb) = check_browser_plan_path(&roots, &hub.cfg.home, raw).map_err(err)?; + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("pro"); + o.remove("path"); + if real.extension().and_then(|e| e.to_str()) == Some("kicad_pcb") { + o.insert("path".into(), json!(real_pcb.to_string_lossy())); + } else { + o.insert("pro".into(), json!(real.to_string_lossy())); + } + } + Ok(q) +} + #[cfg(test)] mod pick_tests { use super::*; @@ -745,4 +835,39 @@ mod pick_tests { } assert!(!crate::net::far::may("accounts.select"), "a far thread's account is chosen on its own machine: the router refuses it"); } + + #[test] fn browser_plan_path_is_confined_to_authorized_projects() { + let base = std::env::temp_dir().join(format!("bp-ext-plan-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let home = base.join("home"); + let proj = base.join("proj"); + let outside = base.join("outside"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + + let pro = proj.join("demo.kicad_pro"); + let pcb = proj.join("demo.kicad_pcb"); + let out_pcb = outside.join("secret.kicad_pcb"); + std::fs::write(&pro, "{}").unwrap(); + std::fs::write(&pcb, "(kicad_pcb)").unwrap(); + std::fs::write(&out_pcb, "(kicad_pcb)").unwrap(); + + let roots = vec![crate::plat::fs::canonicalize(&proj).unwrap()]; + assert!(check_browser_plan_path(&roots, &home, pro.to_str().unwrap()).is_ok()); + assert!(check_browser_plan_path(&roots, &home, pcb.to_str().unwrap()).is_ok()); + assert!(check_browser_plan_path(&roots, &home, out_pcb.to_str().unwrap()).is_err()); + assert!(check_browser_plan_path(&roots, &home, &format!("{}/../outside/secret.kicad_pcb", proj.display())).is_err()); + assert!(check_browser_plan_path(&roots, &home, home.to_str().unwrap()).is_err()); + + #[cfg(unix)] + { + let sidecar = proj.join("demo.kicad_plan"); + let outside_plan = outside.join("evil.kicad_plan"); + std::fs::write(&outside_plan, "{}").unwrap(); + std::os::unix::fs::symlink(&outside_plan, &sidecar).unwrap(); + assert!(check_browser_plan_path(&roots, &home, pro.to_str().unwrap()).is_err()); + } + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/native/host/src/plan/geom.rs b/native/host/src/plan/geom.rs index 344b0a8c9e..499cfee7c9 100644 --- a/native/host/src/plan/geom.rs +++ b/native/host/src/plan/geom.rs @@ -731,8 +731,8 @@ pub fn guides_for_plan(board: &CachedBoard, plan: &Value) -> HashMap = None; - for a in &from_pads { - for b in &to_pads { + for a in from_pads.iter().take(32) { + for b in to_pads.iter().take(32) { let d = (a.1 - b.1).hypot(a.2 - b.2); if d > 0.05 && best.map_or(true, |x| d < x.0) { best = Some((d, [r2(a.1), r2(a.2), r2(b.1), r2(b.2)])); @@ -747,7 +747,7 @@ pub fn guides_for_plan(board: &CachedBoard, plan: &Value) -> HashMap = pads.iter().take(16).map(|p| (p.1, p.2)).collect(); let mut tree = vec![rem.remove(0)]; - while !rem.is_empty() && segs.len() < MAX_CORRIDOR_GUIDES { + while !rem.is_empty() && segs.len() < MAX_CORRIDOR_GUIDES && total_segs + segs.len() < MAX_TOTAL_GUIDES { let mut best: Option<(usize, [f64; 4], f64)> = None; for a in &tree { for (bi, b) in rem.iter().enumerate() { @@ -771,8 +771,15 @@ pub fn guides_for_plan(board: &CachedBoard, plan: &Value) -> HashMap = from_refs.iter().copied().collect(); + let mut t_sorted: Vec<&str> = to_refs.iter().copied().collect(); + f_sorted.sort_unstable(); + t_sorted.sort_unstable(); + 'fallback: for fr in f_sorted { + for tr in &t_sorted { + if segs.len() >= MAX_CORRIDOR_GUIDES || total_segs + segs.len() >= MAX_TOTAL_GUIDES { + break 'fallback; + } if let (Some(a), Some(b)) = (part_center.get(fr), part_center.get(tr)) { if (a[0] - b[0]).hypot(a[1] - b[1]) > 0.5 { segs.push([a[0], a[1], b[0], b[1]]); @@ -919,5 +926,19 @@ mod tests { }); let guides = guides_for_plan(&cached, &plan); assert_eq!(guides["c1"], vec![[34.0, 40.0, 75.0, 46.0]]); + + // Fallback component-center guides are deterministically sorted and capped at 18 + let parts_many: Vec = (0..10).map(|i| PartBox { r: format!("A{i}"), s: "F".into(), b: [10.0, (i * 5) as f64, 12.0, (i * 5 + 2) as f64], o: false }).chain( + (0..10).map(|i| PartBox { r: format!("B{i}"), s: "F".into(), b: [80.0, (i * 5) as f64, 82.0, (i * 5 + 2) as f64], o: false }) + ).collect(); + let dummy = CachedBoard { + geom: BoardGeom { bbox: [0.0, 0.0, 100.0, 100.0], outline: vec![], parts: parts_many, copper_layers: vec![] }, + pad_nets: HashMap::new(), + }; + let p_many = json!({"corridors": [{"id": "cm", "from": (0..10).map(|i| format!("A{i}")).collect::>(), "to": (0..10).map(|i| format!("B{i}")).collect::>()}]}); + let g1 = guides_for_plan(&dummy, &p_many); + let g2 = guides_for_plan(&dummy, &p_many); + assert_eq!(g1["cm"].len(), 18); + assert_eq!(g1, g2); } } diff --git a/native/host/src/plan/mod.rs b/native/host/src/plan/mod.rs index f59d0558c3..eb87ea6a7f 100644 --- a/native/host/src/plan/mod.rs +++ b/native/host/src/plan/mod.rs @@ -274,33 +274,53 @@ fn norm_ring(v: &Value, min_len: usize) -> Result, String> { if arr.len() < min_len { return Err(format!("need at least {min_len} points")) } arr.iter().map(norm_pt).collect() } -fn norm_outline(v: &Value) -> Result { +fn is_flat_outline(v: &Value) -> bool { + v.as_array() + .filter(|a| !a.is_empty()) + .and_then(|a| a[0].as_array()) + .and_then(|p| p.first()) + .and_then(Value::as_f64) + .is_some() +} +pub(super) fn norm_outline(v: &Value) -> Result { let arr = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| "outline must be a polygon".to_string())?; - let is_flat = arr[0].as_array().and_then(|p| p.first()).and_then(Value::as_f64).is_some(); - if is_flat { + if is_flat_outline(v) { Ok(Value::Array(vec![Value::Array(norm_ring(v, 3)?)])) } else { let mut rings = Vec::with_capacity(arr.len()); - for (i, ring) in arr.iter().enumerate() { - rings.push(Value::Array(norm_ring(ring, if i == 0 { 3 } else { 3 })?)); + for ring in arr.iter() { + rings.push(Value::Array(norm_ring(ring, 3)?)); } Ok(Value::Array(rings)) } } -/// Validate and normalize person steering ops into KiCad `UpdatePlan` JSON ops (`set` uses `"fields"`, `"note"` becomes `add` note). -pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { + +static PLAN_NOTE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +#[derive(Clone)] +struct NormOp { + wire: Value, + preserve_holes: bool, +} + +fn next_note_id() -> String { + let seq = PLAN_NOTE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + format!("note-{}-{seq}", crate::hub::now_ms()) +} + +fn normalize_person_ops_checked(ops: &[Value]) -> Result, String> { if ops.is_empty() { return Err("ops cannot be empty".into()) } let mut out = Vec::with_capacity(ops.len()); - for (idx, op) in ops.iter().enumerate() { + for op in ops.iter() { let kind = op["op"].as_str().unwrap_or(""); match kind { "note" => { let text = op["text"].as_str().unwrap_or("").trim(); if text.is_empty() { return Err("note text cannot be empty".into()) } - let id = op["id"].as_str().filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| format!("note-{}-{idx}", crate::hub::now_ms())); + let id = op["id"].as_str().filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(next_note_id); let mut item = json!({"id": id, "text": text, "author": "person"}); if let Some(t) = op.get("target").filter(|v| !v.is_null()) { item["target"] = t.clone(); } - out.push(json!({"op": "add", "kind": "note", "item": item})); + out.push(NormOp { wire: json!({"op": "add", "kind": "note", "item": item}), preserve_holes: false }); } "add" => { let k = op["kind"].as_str().unwrap_or(""); @@ -308,16 +328,17 @@ pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { let mut item = op["item"].clone(); if k == "note" { if item["text"].as_str().unwrap_or("").trim().is_empty() { return Err("note text cannot be empty".into()) } - if item["id"].as_str().unwrap_or("").is_empty() { item["id"] = json!(format!("note-{}-{idx}", crate::hub::now_ms())); } + if item["id"].as_str().unwrap_or("").is_empty() { item["id"] = json!(next_note_id()); } item["author"] = json!("person"); } - out.push(json!({"op": "add", "kind": k, "item": item})); + out.push(NormOp { wire: json!({"op": "add", "kind": k, "item": item}), preserve_holes: false }); } "set" => { let id = op["id"].as_str().unwrap_or(""); if id.is_empty() { return Err("set op needs id".into()) } let src = op["fields"].as_object().or_else(|| op.as_object()).ok_or_else(|| "set op needs fields".to_string())?; let mut fields = serde_json::Map::new(); + let mut preserve_holes = false; for k in ["path", "width", "outline", "layer", "locked", "vias", "reference", "status"] { let Some(v) = src.get(k) else { continue }; let clean = match k { @@ -327,7 +348,10 @@ pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { if !w.is_finite() || !(0.1..=50.0).contains(&w) { return Err("width must be between 0.1 and 50.0 mm".into()) } json!(round3(w)) } - "outline" => norm_outline(v)?, + "outline" => { + preserve_holes = is_flat_outline(v); + norm_outline(v)? + } "layer" | "reference" | "status" => { let s = v.as_str().map(str::trim).unwrap_or(""); if s.is_empty() && k == "layer" { return Err("layer cannot be empty".into()) } @@ -340,12 +364,12 @@ pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { fields.insert(k.to_string(), clean); } if fields.is_empty() { return Err(format!("set op for {id} has no supported fields")) } - out.push(json!({"op": "set", "id": id, "fields": Value::Object(fields)})); + out.push(NormOp { wire: json!({"op": "set", "id": id, "fields": Value::Object(fields)}), preserve_holes }); } "status" | "delete" => { let id = op["id"].as_str().unwrap_or(""); if id.is_empty() { return Err(format!("{kind} op needs id")) } - out.push(op.clone()); + out.push(NormOp { wire: op.clone(), preserve_holes: false }); } other => return Err(format!("unsupported plan op '{other}'")), } @@ -353,6 +377,11 @@ pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { Ok(out) } +/// Validate and normalize person steering ops into KiCad `UpdatePlan` JSON ops (`set` uses `"fields"`, `"note"` becomes `add` note). +pub fn normalize_person_ops(ops: &[Value]) -> Result, String> { + Ok(normalize_person_ops_checked(ops)?.into_iter().map(|n| n.wire).collect()) +} + fn ensure_layer_entry(plan: &mut Value, layer: &str, role: &str) { if layer.is_empty() { return } let arr = plan.as_object_mut().and_then(|m| { @@ -368,9 +397,37 @@ fn ensure_layer_entry(plan: &mut Value, layer: &str, role: &str) { /// Apply normalized person ops directly to a saved `.kicad_plan` JSON document. pub fn apply_person_ops(plan: &mut Value, ops: &[Value]) -> Result, String> { + let wrapped: Vec = ops.iter().map(|op| { + let mut wire = op.clone(); + let preserve_holes = if wire["op"] == "set" { + let raw_o = wire["fields"].get("outline").or_else(|| wire.get("outline")).cloned(); + if let Some(ov) = raw_o { + let flat = is_flat_outline(&ov); + if flat { + let norm = norm_outline(&ov)?; + if let Some(flds) = wire.get_mut("fields").and_then(Value::as_object_mut) { + flds.insert("outline".into(), norm); + } else if let Some(obj) = wire.as_object_mut() { + obj.insert("outline".into(), norm); + } + } + flat + } else { + false + } + } else { + false + }; + Ok(NormOp { wire, preserve_holes }) + }).collect::, String>>()?; + apply_norm_ops(plan, &wrapped) +} + +fn apply_norm_ops(plan: &mut Value, ops: &[NormOp]) -> Result, String> { if !plan.is_object() { return Err("invalid routing plan JSON".into()) } let mut touched = Vec::new(); - for op in ops { + for nop in ops { + let op = &nop.wire; match op["op"].as_str().unwrap_or("") { "set" => { let id = op["id"].as_str().unwrap_or(""); @@ -392,14 +449,18 @@ pub fn apply_person_ops(plan: &mut Value, ops: &[Value]) -> Result, for (k, v) in fields { if matches!(k.as_str(), "op" | "id" | "fields") { continue } if k == "layer" { if let Some(s) = v.as_str() { new_layer = s.to_string(); } } - if k == "outline" { - if let (Some(new_rings), Some(old_rings)) = (v.as_array(), obj.get("outline").and_then(Value::as_array)) { - if new_rings.len() == 1 && old_rings.len() > 1 { - let mut merged = Vec::with_capacity(old_rings.len()); - merged.push(new_rings[0].clone()); - merged.extend(old_rings[1..].iter().cloned()); - obj.insert(k.clone(), Value::Array(merged)); - continue; + if k == "outline" && nop.preserve_holes { + if let (Some(new_rings), Some(old_raw)) = (v.as_array(), obj.get("outline")) { + if new_rings.len() == 1 { + if let Ok(Value::Array(old_rings)) = norm_outline(old_raw) { + if old_rings.len() > 1 { + let mut merged = Vec::with_capacity(old_rings.len()); + merged.push(new_rings[0].clone()); + merged.extend(old_rings[1..].iter().cloned()); + obj.insert(k.clone(), Value::Array(merged)); + continue; + } + } } } } @@ -512,6 +573,11 @@ static PLAN_TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64 fn write_plan_file(pcb: &str, plan: &Value) -> Result<(), String> { let f = Path::new(pcb).with_extension("kicad_plan"); + if let Ok(md) = std::fs::symlink_metadata(&f) { + if md.file_type().is_symlink() { + return Err("refusing to write routing plan through a symlink".into()); + } + } let seq = PLAN_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let tmp = f.with_extension(format!("kicad_plan.{}.{seq}.tmp", std::process::id())); let txt = serde_json::to_string_pretty(plan).map_err(|e| e.to_string())?; @@ -526,17 +592,39 @@ fn write_plan_file(pcb: &str, plan: &Value) -> Result<(), String> { Ok(()) } +fn update_saved_plan_sync(pcb: &str, base: Option, ops: &[NormOp]) -> Result<(Value, Vec), String> { + let f = Path::new(pcb).with_extension("kicad_plan"); + let _guard = PLAN_FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if let Ok(md) = std::fs::symlink_metadata(&f) { + if md.file_type().is_symlink() { + return Err("refusing to access routing plan through a symlink".into()); + } + } + let raw = std::fs::read_to_string(&f).map_err(|_| "no saved routing plan for this board".to_string())?; + let mut plan: Value = serde_json::from_str(&raw).map_err(|_| "saved routing plan is not valid JSON".to_string())?; + if let Some(want) = base { + let cur = plan["revision"].as_u64().unwrap_or(0); + if cur != want { + return Err(format!("routing plan changed (expected revision {want}, current is {cur}); refresh and try again")); + } + } + let touched = apply_norm_ops(&mut plan, ops)?; + write_plan_file(pcb, &plan)?; + Ok((plan["revision"].clone(), touched)) +} + /// The person's steering edits (the Plan canvas/inspector): sends KiCad's `UpdatePlan` as the person when open, /// else updates `.kicad_plan` atomically on disk and broadcasts the settled panel update. pub async fn update(hub: &Arc, pcb: &str, base: Option, ops: &[Value]) -> Result { - let norm = normalize_person_ops(ops)?; + let norm_ops = normalize_person_ops_checked(ops)?; + let wire_ops: Vec = norm_ops.iter().map(|n| n.wire.clone()).collect(); let pro = crate::files::kicad::project::read(&Path::new(pcb).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()).pro; if let Some(r) = crate::files::kicad::embed::gui_route(&pro) { let rev = match base { Some(b) => b, None => read_plan(hub, None, pcb, false).await.ok().and_then(|p| p["revision"].as_u64()).unwrap_or(0), }; - let msg = json!({"board": spec(pcb), "base": rev, "ops": Value::Array(norm).to_string()}); + let msg = json!({"board": spec(pcb), "base": rev, "ops": Value::Array(wire_ops).to_string()}); let o = crate::files::kicad::embed::gui_call_as(&r, &format!("{NS}UpdatePlan"), msg, &crate::files::kicad::coedit::client_name(&crate::files::kicad::coedit::Who::Person)).await; if o["ok"].as_bool() != Some(true) { return Err(refused(o["error"].as_str().unwrap_or("no answer"))); @@ -549,16 +637,8 @@ pub async fn update(hub: &Arc, pcb: &str, base: Option, ops: &[Value]) events::settle(hub, pcb).await; return Ok(m.clone()); } - let f = Path::new(pcb).with_extension("kicad_plan"); let pcb_s = pcb.to_string(); - let res = tokio::task::spawn_blocking(move || -> Result<(Value, Vec), String> { - let _guard = PLAN_FILE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - let raw = std::fs::read_to_string(&f).map_err(|_| "no saved routing plan for this board".to_string())?; - let mut plan: Value = serde_json::from_str(&raw).map_err(|_| "saved routing plan is not valid JSON".to_string())?; - let touched = apply_person_ops(&mut plan, &norm)?; - write_plan_file(&pcb_s, &plan)?; - Ok((plan["revision"].clone(), touched)) - }).await.map_err(|e| e.to_string())??; + let res = tokio::task::spawn_blocking(move || update_saved_plan_sync(&pcb_s, base, &norm_ops)).await.map_err(|e| e.to_string())??; events::settle(hub, pcb).await; Ok(json!({"revision": res.0, "applied": res.1, "saved": true})) } @@ -783,22 +863,81 @@ mod tests { "layers": [{"layer": "In2.Cu", "role": "power", "status": "proposed"}], "planes": [{"id": "p1", "net": "GND", "layer": "In2.Cu", "outline": [[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]], hole], "status": "proposed"}] }); - let single_ops = normalize_person_ops(&[ + // Flat outline -> edits outer ring only, preserves existing holes + let flat_ops = normalize_person_ops_checked(&[ json!({"op": "set", "id": "p1", "outline": [[0.0, 0.0], [12.0, 0.0], [12.0, 10.0], [0.0, 10.0]]}) ]).unwrap(); - apply_person_ops(&mut p, &single_ops).unwrap(); + assert!(flat_ops[0].preserve_holes); + apply_norm_ops(&mut p, &flat_ops).unwrap(); let rings = p["planes"][0]["outline"].as_array().unwrap(); assert_eq!(rings.len(), 2); assert_eq!(rings[0], json!([[0.0, 0.0], [12.0, 0.0], [12.0, 10.0], [0.0, 10.0]])); assert_eq!(rings[1], hole); + // Explicit 1-ring array -> replaces all rings and clears existing holes + let clear_ops = normalize_person_ops_checked(&[ + json!({"op": "set", "id": "p1", "outline": [[[0.0, 0.0], [13.0, 0.0], [13.0, 10.0]]]}) + ]).unwrap(); + assert!(!clear_ops[0].preserve_holes); + apply_norm_ops(&mut p, &clear_ops).unwrap(); + assert_eq!(p["planes"][0]["outline"], json!([[[0.0, 0.0], [13.0, 0.0], [13.0, 10.0]]])); + + // Flat stored outline must never treat vertices 1..N as holes when edited + let mut p_flat = json!({ + "revision": 1, + "layers": [{"layer": "In2.Cu", "role": "power", "status": "proposed"}], + "planes": [{"id": "p1", "net": "GND", "layer": "In2.Cu", "outline": [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], "status": "proposed"}] + }); + let flat_ops2 = normalize_person_ops_checked(&[ + json!({"op": "set", "id": "p1", "outline": [[0.0, 0.0], [15.0, 0.0], [15.0, 10.0]]}) + ]).unwrap(); + apply_norm_ops(&mut p_flat, &flat_ops2).unwrap(); + assert_eq!(p_flat["planes"][0]["outline"], json!([[[0.0, 0.0], [15.0, 0.0], [15.0, 10.0]]])); + let new_hole = json!([[3.0, 3.0], [5.0, 3.0], [5.0, 5.0]]); - let multi_ops = normalize_person_ops(&[ + let multi_ops = normalize_person_ops_checked(&[ json!({"op": "set", "id": "p1", "outline": [[[0.0, 0.0], [14.0, 0.0], [14.0, 10.0]], new_hole]}) ]).unwrap(); - apply_person_ops(&mut p, &multi_ops).unwrap(); + apply_norm_ops(&mut p, &multi_ops).unwrap(); let rings2 = p["planes"][0]["outline"].as_array().unwrap(); assert_eq!(rings2.len(), 2); assert_eq!(rings2[1], new_hole); } + + #[test] fn saved_plan_update_checks_base_revision_and_unique_note_ids() { + let dir = std::env::temp_dir().join(format!("bp-plan-mod-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let pcb = dir.join("demo.kicad_pcb"); + let plan_f = dir.join("demo.kicad_plan"); + std::fs::write(&pcb, "").unwrap(); + std::fs::write(&plan_f, serde_json::to_string_pretty(&json!({ + "revision": 5, + "corridors": [{"id": "c1", "group": "g1", "layer": "In1.Cu", "path": [[0.0, 0.0], [10.0, 0.0]], "width": 1.0, "status": "proposed"}] + })).unwrap()).unwrap(); + + let nops = normalize_person_ops_checked(&[ + json!({"op": "set", "id": "c1", "width": 2.0}), + json!({"op": "note", "target": "c1", "text": "Note A"}), + json!({"op": "note", "target": "c1", "text": "Note B"}) + ]).unwrap(); + assert_ne!(nops[1].wire["item"]["id"], nops[2].wire["item"]["id"]); + assert_eq!(nops[1].wire["item"]["target"], "c1"); + + let pcb_s = pcb.to_string_lossy().into_owned(); + // Stale base=4 is rejected without overwriting disk + let err = update_saved_plan_sync(&pcb_s, Some(4), &nops).unwrap_err(); + assert!(err.contains("expected revision 4, current is 5"), "{err}"); + let disk_before: Value = serde_json::from_str(&std::fs::read_to_string(&plan_f).unwrap()).unwrap(); + assert_eq!(disk_before["revision"], 5); + + // Matching base=5 succeeds and increments revision + let (rev, _) = update_saved_plan_sync(&pcb_s, Some(5), &nops).unwrap(); + assert_eq!(rev, 6); + let disk_after: Value = serde_json::from_str(&std::fs::read_to_string(&plan_f).unwrap()).unwrap(); + assert_eq!(disk_after["revision"], 6); + assert_eq!(disk_after["notes"].as_array().unwrap().len(), 2); + assert_eq!(disk_after["notes"][0]["target"], "c1"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/native/host/src/plan/panel.rs b/native/host/src/plan/panel.rs index bcb4071c13..1bdb5077b7 100644 --- a/native/host/src/plan/panel.rs +++ b/native/host/src/plan/panel.rs @@ -139,18 +139,30 @@ pub fn draw(plan: &Value, rows: &[(String, Value)]) -> Value { draw_enriched(plan, rows, &std::collections::HashMap::new()) } +fn take_pts(left: &mut usize, pts: &Value) -> Option { + let n = pts.as_array().map_or(0, Vec::len); + if n == 0 || n > *left { return None } + *left -= n; + Some(pts.clone()) +} + fn draw_enriched(plan: &Value, rows: &[(String, Value)], guides: &std::collections::HashMap>) -> Value { let row = |id: &str| rows.iter().find(|(_, v)| v["id"] == id).map(|(_, v)| v); let state = |id: &str| row(id).map(|v| v["state"].clone()).unwrap_or(json!("proposed")); let colour = |id: &str| row(id).map(|v| v["color"].clone()).unwrap_or(json!("#8a8a8a")); let nets = |id: &str| row(id).map(|v| v["nets"].clone()).unwrap_or(json!(0)); let mut left = MAX_POINTS; - let mut take = |pts: &Value| -> Option { let n = pts.as_array().map_or(0, Vec::len); if n == 0 || n > left { return None } left -= n; Some(pts.clone()) }; let bands: Vec = plan["corridors"].as_array().into_iter().flatten().filter_map(|c| { let id = st(c, "id"); let r = row(id); let g = guides.get(id).cloned().unwrap_or_default(); - Some(json!({"id": id, "layer": c["layer"], "width": c["width"].as_f64().unwrap_or(1.0), "path": take(&c["path"])?, "state": state(id), "color": colour(id), "nets": nets(id), "vias": c["vias"], + let path = take_pts(&mut left, &c["path"])?; + let vias = c["vias"].as_array().map(|a| { + let take_n = a.len().min(64).min(left); + left -= take_n; + Value::Array(a.iter().take(take_n).cloned().collect()) + }).unwrap_or_else(|| c["vias"].clone()); + Some(json!({"id": id, "layer": c["layer"], "width": c["width"].as_f64().unwrap_or(1.0), "path": path, "state": state(id), "color": colour(id), "nets": nets(id), "vias": vias, "name": r.map(|v| v["name"].clone()).unwrap_or(json!(id)), "group": c["group"], "locked": c["locked"] == true, "edited": c["edited"] == true, "order": c["order"], "from": c["from"], "to": c["to"], "impedance": r.map(|v| v["impedance"].clone()).unwrap_or(Value::Null), "guides": g, "problem_text": r.map(|v| v["problem_text"].clone()).unwrap_or(json!(""))})) @@ -158,8 +170,20 @@ fn draw_enriched(plan: &Value, rows: &[(String, Value)], guides: &std::collectio let regions: Vec = plan["planes"].as_array().into_iter().flatten().filter_map(|p| { let id = st(p, "id"); let r = row(id); - let holes = p["outline"].as_array().map(|a| a.iter().skip(1).cloned().collect::>()).unwrap_or_default(); - Some(json!({"id": id, "layer": p["layer"], "net": p["net"], "outline": take(&p["outline"][0])?, "holes": holes, "state": state(id), "color": colour(id), + let rings = match super::norm_outline(&p["outline"]) { + Ok(Value::Array(rs)) => rs, + _ => return None, + }; + let outer = take_pts(&mut left, rings.first()?)?; + let mut holes = Vec::new(); + for h in rings.iter().skip(1) { + if let Some(kept) = take_pts(&mut left, h) { + holes.push(kept); + } else { + break; + } + } + Some(json!({"id": id, "layer": p["layer"], "net": p["net"], "outline": outer, "holes": holes, "state": state(id), "color": colour(id), "locked": p["locked"] == true, "edited": p["edited"] == true, "reference": p["reference"], "priority": p["priority"], "problem_text": r.map(|v| v["problem_text"].clone()).unwrap_or(json!(""))})) }).collect(); @@ -170,33 +194,83 @@ fn draw_enriched(plan: &Value, rows: &[(String, Value)], guides: &std::collectio pub fn fit_info_budget(d: &mut Value) { const BUDGET: usize = 58 * 1024; if d.to_string().len() <= BUDGET { return } - let mut trimmed = false; + d["board_trimmed"] = json!(true); + if let Some(bands) = d["draw"]["bands"].as_array_mut() { for b in bands.iter_mut() { if let Some(gs) = b["guides"].as_array_mut() { - if gs.len() > 6 { gs.truncate(6); trimmed = true; } + if gs.len() > 6 { gs.truncate(6); } } } } - if d.to_string().len() <= BUDGET { if trimmed { d["board_trimmed"] = json!(true); } return } + if d.to_string().len() <= BUDGET { return } + if let Some(bands) = d["draw"]["bands"].as_array_mut() { - for b in bands.iter_mut() { - if b["guides"].as_array().is_some_and(|g| !g.is_empty()) { - b["guides"] = json!([]); - trimmed = true; - } + for b in bands.iter_mut() { b["guides"] = json!([]); } + } + if d.to_string().len() <= BUDGET { return } + + for cap in [80usize, 40, 0] { + if let Some(parts) = d["board"]["parts"].as_array_mut() { + if parts.len() > cap { parts.truncate(cap); } } + if d.to_string().len() <= BUDGET { return } } - if d.to_string().len() <= BUDGET { if trimmed { d["board_trimmed"] = json!(true); } return } - if let Some(parts) = d["board"]["parts"].as_array_mut() { - if parts.len() > 80 { parts.truncate(80); trimmed = true; } + + if let Some(regions) = d["draw"]["regions"].as_array_mut() { + for r in regions.iter_mut() { r["holes"] = json!([]); } } - if d.to_string().len() > BUDGET { - if let Some(parts) = d["board"]["parts"].as_array_mut() { - if parts.len() > 40 { parts.truncate(40); trimmed = true; } + if let Some(bands) = d["draw"]["bands"].as_array_mut() { + for b in bands.iter_mut() { b["vias"] = json!([]); } + } + if let Some(board) = d.get_mut("board").and_then(Value::as_object_mut) { + board.insert("outline".into(), json!([])); + } + if d.to_string().len() <= BUDGET { return } + + if let Some(draw) = d.get_mut("draw").and_then(Value::as_object_mut) { + draw.insert("bands".into(), json!([])); + draw.insert("regions".into(), json!([])); + } + if d.to_string().len() <= BUDGET { return } + + if let Some(obj) = d.as_object_mut() { + obj.insert("notes".into(), json!([])); + obj.insert("constraints".into(), json!([])); + obj.insert("impedances".into(), json!([])); + obj.insert("stackup_summary".into(), json!("")); + } + if d.to_string().len() <= BUDGET { return } + + if let Some(layers) = d["layers"].as_array_mut() { + for l in layers.iter_mut() { + if let Some(items) = l["items"].as_array_mut() { + for it in items.iter_mut() { + if let Some(obj) = it.as_object_mut() { + obj.insert("problem_text".into(), json!("")); + } + } + } + } + } + while d.to_string().len() > BUDGET { + let Some(layers) = d["layers"].as_array_mut() else { break }; + let mut shrunk = false; + for l in layers.iter_mut().rev() { + if let Some(items) = l["items"].as_array_mut() { + if !items.is_empty() { + let keep = items.len() / 2; + items.truncate(keep); + shrunk = true; + break; + } + } + } + if !shrunk { + layers.clear(); + break; } } - if trimmed { d["board_trimmed"] = json!(true); } } /// The board of a project's .kicad_pro. @@ -379,5 +453,21 @@ mod tests { fit_info_budget(&mut big); assert!(big.to_string().len() <= 58 * 1024); assert_eq!(big["board_trimmed"], true); + + // Verify holes count against MAX_POINTS and massive notes/holes/items are trimmed <= 58 KiB + let hole_pts: Vec = (0..(MAX_POINTS - 5)).map(|i| json!([i as f64, 1.0])).collect(); + let mut huge_plan = json!({ + "layers": [{"layer": "In1.Cu", "role": "power", "status": "proposed"}], + "planes": [{"id": "p1", "net": "GND", "layer": "In1.Cu", "outline": [[[0, 0], [10, 0], [10, 10], [0, 10]], hole_pts.clone(), hole_pts], "status": "proposed"}] + }); + let dr_holes = data(&huge_plan, &[], false); + assert_eq!(dr_holes["draw"]["regions"][0]["holes"].as_array().unwrap().len(), 1, "second huge hole exceeds MAX_POINTS and is dropped"); + huge_plan["notes"] = json!((0..400).map(|i| json!({"id": format!("n{i}"), "text": "a".repeat(250)})).collect::>()); + huge_plan["corridors"] = json!((0..250).map(|i| json!({"id": format!("c{i}"), "group": "g1", "layer": "F.Cu", "path": [[1, 1], [2, 2]], "status": "proposed"})).collect::>()); + let mut huge_d = data(&huge_plan, &[], false); + assert!(huge_d.to_string().len() > 58 * 1024); + fit_info_budget(&mut huge_d); + assert!(huge_d.to_string().len() <= 58 * 1024); + assert_eq!(huge_d["board_trimmed"], true); } } diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index e105306513..20c3a82a7e 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function $t(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function Sn(e){return e==="done"||e==="failed"||e==="cancelled"}function An(e,t){if(!e||e.id!==t.id)return!0;let n=Sn(e.state),i=Sn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Ln(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Pn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ht=Qi(),Gt=new Set,Ut=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function Qi(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Nn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ht}Nn();function Lt(e){return Gt.add(e),()=>{Gt.delete(e)}}function Mn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ht;if(ht=n,Nn(),i)for(let s of Gt)s(ht);return i}function h(e,t,n){let s=(mt[ht]||mt.en||{})[e]??mt.en?.[e]??t??e;return Pn(s,n)}function Ee(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return h(t,e)}function z(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=z("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function es(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ts(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Ot{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=z("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=z("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=z("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=z("div","bp-fb-list"),this.errEl=z("div","bp-ap-err bp-hidden");let a=z("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(z("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(Ee(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(z("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(ts(this.path,n))});i.append(z("span","bp-fb-icon","▸"),z("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(es(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(Ee(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Vt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=z("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=z("div","bp-modal bp-ap"),n=z("div","bp-modal-head"),i=z("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=z("div","bp-ap-tabs"),this.bodyEl=z("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Ot(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=z("div","bp-ap-form"),n=z("div","bp-ap-repo"),i=z("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=z("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=z("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=z("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=z("label","bp-ap-check"),a=z("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,z("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(z("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=z("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=z("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),r.push(o,c),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(c)=>c.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=z("div","bp-ap-sug-top");if(o.append(z("span","bp-ap-sug-name",s.name)),s.private)o.append(z("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(z("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(z("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=z("div","bp-ap-sug-note");if(s.append(z("span","",Ee(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(Ee(t.error)))}else if(t){let r=z("div","bp-ap-where"),o=z("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),r.append(o,c),n.push(r);let m=z("label","bp-ap-name");m.append(z("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let l=z("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(l),n.push(m),!t.ok&&t.error)n.push(this.errLine(Ee(t.error)));else if(t.same)n.push(z("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=z("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Ot(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=$t();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=Ee(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=$t(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=Ee(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Ln(e))this.goTo(e)}renderJobView(){this.jobEl=z("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=z("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[z("div","bp-ap-job-title",s)];if(t.state==="running"){let r=z("div","bp-ap-phase",Ee(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=z("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=z("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(z("div","bp-ap-detail bp-dim",t.detail));let m=z("div","bp-ap-foot"),l=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),m.append(l),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=z("div","bp-ap-err",Ee(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=z("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let c=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),r.append(c),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let l=z("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let u of r)l.appendChild(z("li","",Ee(u)));a.push(l)}let o=z("div","bp-ap-foot"),c=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=Fe(c,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=z("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(z("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(z("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=z("div","bp-ap-code-row"),s=z("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=z("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(z("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(z("div","bp-ap-err",Ee(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ns(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ut(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ns(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,e.appendChild(c)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i=(e.ended??0)}function Pn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Nn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ut=ts(),Ut=new Set,Ot=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ot.has(t))Ot.set(t,e);function ts(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Mn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ut}Mn();function At(e){return Ut.add(e),()=>{Ut.delete(e)}}function Tn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ut;if(ut=n,Mn(),i)for(let s of Ut)s(ut);return i}function h(e,t,n){let s=(mt[ut]||mt.en||{})[e]??mt.en?.[e]??t??e;return Nn(s,n)}function xe(e){if(!e)return"";let t=Ot.get(e);if(!t)return e;return h(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function ns(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function is(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Vt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let a=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(xe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(is(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(ns(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(xe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Wt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Vt(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),a=J("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,J("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(J("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=J("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(J("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",xe(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(xe(t.error)))}else if(t){let r=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let m=J("label","bp-ap-name");m.append(J("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let c=J("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(c),n.push(m),!t.ok&&t.error)n.push(this.errLine(xe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Vt(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Gt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=xe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Gt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=xe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Pn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let r=J("div","bp-ap-phase",xe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(J("div","bp-ap-detail bp-dim",t.detail));let m=J("div","bp-ap-foot"),c=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),m.append(c),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=J("div","bp-ap-err",xe(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=J("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let l=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=J("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let u of r)c.appendChild(J("li","",xe(u)));a.push(c)}let o=J("div","bp-ap-foot"),l=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=Fe(l,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=J("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(J("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",xe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ss(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ht(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ss(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),d.append(p,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=l,f.appendChild(g),u.append(d,f),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let c=document.createElement(`h${Math.min(4,a[1].length+1)}`);c.className="bp-md-h",ut(c,a[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ut(c,m.join(` -`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));ut(o,r[c])}t.appendChild(o)}return t}var Tn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Tn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Tn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function _t(e){return e<10000000000?e*1000:e}function is(e){if(!e)return"";return new Date(_t(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ss(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Wt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class qt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!Wt(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!Wt(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Wt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=h("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let u=is(e.at);if(t)l.textContent=u,i.append(s,...m?[o]:[],l);else{let d=n&&e.at?ss(_t(e.at)-_t(n)):"",p=u?d?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:d}):h("web.chat.finished","Finished {time}",{time:u}):"";l.textContent=e.live?h("web.chat.streaming","Streaming…"):p,i.append(l,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,l.appendChild(u),a.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=a.tool.summary,l.appendChild(d)}r.appendChild(l),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let l=a.ask;if(l.kind==="plan"){r.appendChild(this.renderPlanAsk(l)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,u.appendChild(d),l.state==="open"){let p=document.createElement("div");if(p.className="bp-ask-opts",l.options&&l.options.length>0)for(let b of l.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,b.id)),p.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=h("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=h("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(l.id,b.value.trim())}),p.append(b,y)}u.appendChild(p)}else{let p=document.createElement("div");p.className="bp-ask-answered",p.textContent=h("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),u.appendChild(p)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),c=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!c&&!m&&!a.live)continue;if(a.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};l.addEventListener("click",d),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"||p.key===" ")p.preventDefault(),d()}),r.appendChild(l)}if(o||a.live){let l=document.createElement("div");if(l.className="bp-entry-body",a.kind==="user")l.textContent=a.text;else l.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,l);r.appendChild(l)}if(m&&a.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=u.previewUrl,d.alt=u.name||"attachment",l.appendChild(d)}else if(u.path||u.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=u.name||u.path||"image",l.appendChild(d)}if(l.childElementCount>0)r.appendChild(l)}if(a.images&&a.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let u of a.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=u;let p=`${a.id}|${u}`,b=this.imageCache.get(p);if(b)d.src=b;else this.cb.onLoadImage(a.id,u).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(p,f),d.src=f});l.appendChild(d)}r.appendChild(l)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):Ee(e.head),s.append(a,r),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let u=h("common.copy","Copy"),d=document.createElement("span");d.textContent=u,l.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=u},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let u=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=u?.label&&u.label!=="Implement"?Ee(u.label):h("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),l.appendChild(d),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(y)}let p=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=p?.label&&p.label!=="Dismiss"?Ee(p.label):h("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"dismiss")}),l.appendChild(b),i.appendChild(l),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=h("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let w=()=>{let L=f.value.trim();if(!L)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${L}`)},k=()=>{this.closePlanRevise()};y.addEventListener("keydown",(L)=>{if(L.key==="Escape")L.preventDefault(),L.stopPropagation(),k()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(L)=>{if(L.key==="Enter"&&!L.shiftKey)L.preventDefault(),w()}),g.addEventListener("click",w);let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost",S.textContent=h("common.cancel","Cancel"),S.addEventListener("click",k),y.append(f,g,S),i.appendChild(y)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Bn="http://www.w3.org/2000/svg",In=4,Rn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Kt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function jn(){return Pt(["M6 4l14 8-14 8z"])}function as(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class zt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Kt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let m=c.clipboardData?.items;if(!m)return;let l=[];for(let u=0;u0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=as(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?jn():Kt()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?jn():Kt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let c=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let l=(u,d,p,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(d?" active":""),y.textContent=u,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(p)),y};m.append(l(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(m)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +`),i=0;while(i{navigator.clipboard?.writeText(c).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),p.append(d,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=c,f.appendChild(g),u.append(p,f),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",ht(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ht(l,m.join(` +`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));ht(o,r[l])}t.appendChild(o)}return t}var Bn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qt(e){return e<10000000000?e*1000:e}function as(e){if(!e)return"";return new Date(qt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function rs(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function _t(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Kt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!_t(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!_t(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(_t(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=h("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let u=as(e.at);if(t)c.textContent=u,i.append(s,...m?[o]:[],c);else{let p=n&&e.at?rs(qt(e.at)-qt(n)):"",d=u?p?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:p}):h("web.chat.finished","Finished {time}",{time:u}):"";c.textContent=e.live?h("web.chat.streaming","Streaming…"):d,i.append(c,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,c.appendChild(u),a.tool.summary){let p=document.createElement("span");p.className="bp-tool-summary",p.textContent=a.tool.summary,c.appendChild(p)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${c.id}`);let p=document.createElement("div");if(p.className="bp-ask-q",p.textContent=c.question,u.appendChild(p),c.state==="open"){let d=document.createElement("div");if(d.className="bp-ask-opts",c.options&&c.options.length>0)for(let b of c.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,b.id)),d.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=h("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=h("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(c.id,b.value.trim())}),d.append(b,y)}u.appendChild(d)}else{let d=document.createElement("div");d.className="bp-ask-answered",d.textContent=h("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),u.appendChild(d)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!m&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let p=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};c.addEventListener("click",p),c.addEventListener("keydown",(d)=>{if(d.key==="Enter"||d.key===" ")d.preventDefault(),p()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.textContent=a.text;else c.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(m&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let p=document.createElement("img");p.className="bp-reply-img",p.src=u.previewUrl,p.alt=u.name||"attachment",c.appendChild(p)}else if(u.path||u.name){let p=document.createElement("span");p.className="bp-tool-pill",p.textContent=u.name||u.path||"image",c.appendChild(p)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.images){let p=document.createElement("img");p.className="bp-reply-img",p.alt=u;let d=`${a.id}|${u}`,b=this.imageCache.get(d);if(b)p.src=b;else this.cb.onLoadImage(a.id,u).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(d,f),p.src=f});c.appendChild(p)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):xe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let u=h("common.copy","Copy"),p=document.createElement("span");p.textContent=u,c.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),p),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),p.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),p.textContent=u},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let u=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),p=document.createElement("button");if(p.type="button",p.className="primary",p.setAttribute("data-testid","plan-implement"),p.textContent=u?.label&&u.label!=="Implement"?xe(u.label):h("approval.implement","Implement"),p.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),c.appendChild(p),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(y)}let d=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=d?.label&&d.label!=="Dismiss"?xe(d.label):h("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,d?.id??"dismiss")}),c.appendChild(b),i.appendChild(c),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=h("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let E=()=>{let A=f.value.trim();if(!A)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${A}`)},C=()=>{this.closePlanRevise()};y.addEventListener("keydown",(A)=>{if(A.key==="Escape")A.preventDefault(),A.stopPropagation(),C()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(A)=>{if(A.key==="Enter"&&!A.shiftKey)A.preventDefault(),E()}),g.addEventListener("click",E);let k=document.createElement("button");k.type="button",k.className="bp-btn-ghost",k.textContent=h("common.cancel","Cancel"),k.addEventListener("click",C),y.append(f,g,k),i.appendChild(y)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var In="http://www.w3.org/2000/svg",Rn=4,jn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(In,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(In,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function zt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Hn(){return Pt(["M6 4l14 8-14 8z"])}function os(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Jt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let m=l.clipboardData?.items;if(!m)return;let c=[];for(let u=0;u0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=os(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?Hn():zt()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?Hn():zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let c=(u,p,d,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(p?" active":""),y.textContent=u,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(d)),y};m.append(c(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(m)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} ${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Rn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=In){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:In}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Hn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var rs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&rs.has(t.id))}function Gn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var os=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ls=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Un(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(os.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ls.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function On(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Vn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function Wn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Jt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function _n(e){return e.state==="routed"||e.state==="verified"}function qn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Kn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function zn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Jn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Yn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Yt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Xn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Xt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Dn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Fn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Zn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Dn[Zn(i)%Dn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Fn[Zn(e)%Fn.length]}function Qn(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ke(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ei(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ti(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(r,Math.min(o,e.scale*t)),[m,l]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/c,cy:l-(i-a*0.5)/c,scale:c,touched:!0}}function ni(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function ii(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Zt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function cs(e,t,n,i,s,a){let r=s-n,o=a-i,c=r*r+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/c)),l=n+m*r,u=i+m*o;return(e-l)*(e-l)+(t-u)*(t-u)}function $n(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(c-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function Qt(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let p=d.path??[];for(let b=0;b=3)for(let b=0;b=0;d--){let p=t[d];if(p.layer!==n)continue;let b=p.outline??[];if(!$n(l,u,b))continue;if(!(p.holes??[]).some((f)=>$n(l,u,f)))return{kind:"region",id:p.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,c=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((c>0||a.role==="power"||a.role==="plane")&&(!n||c>n.count))n={count:c,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function si(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[l,u]=Ke(t,m.b[0],m.b[1],n,i),[d,p]=Ke(t,m.b[2],m.b[3],n,i),b=Math.abs(d-l),y=Math.abs(p-u);if(b<13||y<9)continue;let f=(l+d)*0.5,g=(u+p)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,l)=>l.score-m.score);let o=[],c=[];for(let m of r){let l=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((d)=>!(l[2]<=d[0]||l[0]>=d[2]||l[3]<=d[1]||l[1]>=d[3])))o.push(l),c.push({text:m.text,cx:m.cx,cy:m.cy})}return c}var ai="#111917",ds="#16201d",ps="rgba(212, 224, 219, 0.92)",ms="rgba(61, 80, 73, 0.72)",hs="rgba(82, 107, 97, 0.85)",us="rgba(143, 163, 155, 0.88)",ri="#f59e0b",bs="#eef5f2",oi="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function gs(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function fs(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function vs(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class en{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){if(e.layers.length===0)return[];if(e.gridMode==="all")return e.layers;if(e.gridMode==="single"){let i=e.shownLayers.find((a)=>e.layers.some((r)=>r.layer===a))??rt(e.layers)[0]??e.layers[0]?.layer,s=e.layers.find((a)=>a.layer===i);return s?[s]:[]}let t=e.shownLayers.length>0&&e.shownLayers.every((i)=>e.layers.some((s)=>s.layer===i))?e.shownLayers.slice(0,2):rt(e.layers),n=[];for(let i of t){let s=e.layers.find((a)=>a.layer===i);if(s)n.push(s)}return n.length>0?n:e.layers.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return Qn(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=h("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,c,m);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let p=document.createElement("div");p.className="bp-plan-hover-hud bp-hidden",u.append(d,p);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=d.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(d,e.layer);let g={layer:e.layer,el:t,canvas:d,ctx:y,legendEl:b,okBtn:c,noBtn:m,statusEl:o,titleEl:r,subtitleEl:l,hoverHudEl:p,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=vs(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let c=document.createElement("button");c.type="button";let m=this.state?.selectedId===o.id;c.className="bp-plan-legend-chip"+(m?" active":"");let l=document.createElement("span");l.className="bp-plan-legend-sw",l.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,c.append(l,u),c.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(c)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(n)=>n.preventDefault()),e.addEventListener("pointerdown",(n)=>{let i=this.state;if(!i)return;this.root.focus();let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r);if(n.button===2){if(l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane),d=Zt(u,l.idx,l.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(l.id,{[l.isPlane?"outline":"path"]:d})}return}if(n.button!==0)return;if(e.setPointerCapture(n.pointerId),this.downPos={x:n.clientX,y:n.clientY},l?.kind==="vertex"){let u=this.getItemPts(l.id,l.isPlane);this.selectedVertex={id:l.id,idx:l.idx},this.cb.onSelect(l.id),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:l.idx,pts:u.map((d)=>[d[0],d[1]])},this.scheduleDraw()}else if(l?.kind==="midpoint"){let u=this.getItemPts(l.id,l.isPlane),d=ii(u,l.segIdx,l.pos,l.isPlane),p=l.isPlane&&l.segIdx+1>=u.length?d.length-1:Math.min(l.segIdx+1,d.length-1);this.cb.onSelect(l.id),this.selectedVertex={id:l.id,idx:p},this.patchLocalItem(l.id,l.isPlane,d),this.cb.onOptimisticPatch(l.id,{[l.isPlane?"outline":"path"]:d}),this.drag={layer:t,kind:"vertex",id:l.id,isPlane:l.isPlane,idx:p,pts:d},this.scheduleDraw()}else{if(l&&(l.kind==="band"||l.kind==="region"))this.cb.onSelect(l.id);this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:r}}}),e.addEventListener("pointermove",(n)=>{let i=this.state;if(!i)return;let s=e.getBoundingClientRect(),a=n.clientX-s.left,r=n.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let w=this.getCam(t,o,c);this.setCam(t,ei(w,a-this.drag.lastX,r-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=r,this.scheduleDraw();return}let p=this.getCam(t,o,c),[b,y]=Bt(p,a,r,o,c),f=[Math.round(b*1000)/1000,Math.round(y*1000)/1000];this.drag.pts[this.drag.idx]=f;let g=this.drag.pts.map((w)=>[w[0],w[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,g),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:g}),this.scheduleDraw();return}let m=this.getCam(t,o,c),l=It(i.bands,i.regions,t,i.selectedId,m,o,c,a,r),u=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=l?l.id:"";if(this.hover=l?{layer:t,hit:l}:null,e.style.cursor=l?.kind==="vertex"||l?.kind==="midpoint"?"pointer":l?"pointer":"crosshair",u!==d||l?.kind!==this.hover?.hit.kind)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerup",(n)=>{let i=this.state,s=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(n.pointerId))e.releasePointerCapture(n.pointerId);if(s&&s.kind==="vertex"&&s.layer===t){this.cb.onCommitFields(s.id,{[s.isPlane?"outline":"path"]:s.pts});return}if(n.detail>=2){this.fitAll();return}if(i&&a&&Math.hypot(n.clientX-a.x,n.clientY-a.y)<4.5){let r=e.getBoundingClientRect(),o=n.clientX-r.left,c=n.clientY-r.top,m=Math.max(1,r.width),l=Math.max(1,r.height),u=this.getCam(t,m,l),d=It(i.bands,i.regions,t,i.selectedId,u,m,l,o,c);if(d&&(d.kind==="band"||d.kind==="region"))this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);else if(!d)this.cb.onSelect("")}}),e.addEventListener("wheel",(n)=>{n.preventDefault();let i=e.getBoundingClientRect(),s=n.clientX-i.left,a=n.clientY-i.top,r=Math.max(1,i.width),o=Math.max(1,i.height),c=this.getCam(t,r,o),m=Math.max(0.65,Math.min(1.55,1-n.deltaY*0.002));this.setCam(t,ti(c,m,s,a,r,o)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),c=Zt(o,this.selectedVertex.idx,r);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),c=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(p,b)=>Ke(a,p,b,n,i);e.fillStyle=ai,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((p)=>p.length>=3);if(e.fillStyle=ds,o.length>0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let p of c){let b=p.outline??[];if(b.length<3)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=fs(p.state||"proposed",y,f),w=ft(p.net||p.id,p.color||"");e.beginPath();for(let k=0;k0){e.beginPath();for(let p of o){for(let b=0;bp.layer===t),d=[];for(let p of u){for(let b of p.from??[])d.push(b);for(let b of p.to??[])d.push(b)}e.fillStyle=us,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let p of si(l,a,n,i,d))e.fillText(p.text,p.cx,p.cy);for(let p of u){let b=p.guides??[];if(b.length===0)continue;let y=s.selectedId===p.id||m?.id===p.id,f=vt(p.name||p.id,p.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[w,k]=r(g[0],g[1]),[S,L]=r(g[2],g[3]);e.moveTo(w,k),e.lineTo(S,L)}e.stroke()}for(let p of u){let b=p.path??[];if(b.length<2)continue;let y=s.selectedId===p.id,f=m?.id===p.id,g=gs(p.state||"proposed",y,f),w=vt(p.name||p.id,p.color||""),k=Qt(p.width??1.5,a.scale),S=()=>{e.beginPath();for(let M=0;M0){let M=ni(b);if(M){let[B,H]=r(M[0],M[1]),W=String(L),_=Math.max(16,W.length*6.5+8),j=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(B-_*0.5,H-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":w,e.strokeRect(B-_*0.5,H-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,B,H+0.5)}}}if(s.selectedId){let p=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let r=document.createElement("button");r.type="button";let o=this.openPanel===a.id;r.className="bp-mgmt-tab"+(o?" active":""),r.setAttribute("data-testid",`mgmt-tab-${a.id}`),r.setAttribute("aria-pressed",o?"true":"false");let c=document.createElement("span");c.textContent=Ee(a.label),r.appendChild(c);let m=this.getPanelData(a.id),l=Gn(m);if(l){let u=document.createElement("span");u.className=`bp-mgmt-badge bp-tone-${l.tone}`,u.textContent=l.text,r.appendChild(u)}r.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(r)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=h("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,s.appendChild(a)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=Ee(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),m.appendChild(l),e.appendChild(m)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Vn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),c.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),c.appendChild(y)}else{let y=On(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,c.appendChild(f)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",Un(a.footprint??"")].filter(Boolean).join(" · "),p=document.createElement("span");p.className="bp-dim",p.textContent=d;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(p,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=Ee(a.stock.class),u.appendChild(y)}o.append(c,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,p=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Yt(b,o()))return;this.bomLastUndo=!p&&(y.changed??0)>0?{project:d.project,editId:b.editId,refs:d.refs.slice(),field:d.field,was:typeof y.was==="string"?y.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=p?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Yt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(l,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn",p.textContent="Undo",p.addEventListener("click",()=>{c(Xn(d),!0)}),m.appendChild(p)}if(t.append(i,r,m),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),p.textContent=s(d)+(a(d)?" · judged":""),p.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(p)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let d=this.watchGen,p=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:p}).then(()=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(d!==this.watchGen||p!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(c,m),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let u=Wn(n,this.checksSource);if(u.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let p=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${p}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(d.source)} · ${d.rule}`;let g=document.createElement("span");g.className=`bp-tone-${p}`,g.textContent=String(d.n),b.append(y,f,g),l.appendChild(b);for(let w of d.rows??[]){let k=document.createElement("div");k.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=Ee(w.title??""),k.appendChild(S),w.names||this.checksSelectedId===w.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let M=document.createElement("span");if(M.className="bp-dim bp-mgmt-flex1",M.textContent=w.names??"",L.appendChild(M),this.checksSelectedId===w.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(H)=>{H.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:w.id}).then((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Xt(W,j))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),L.appendChild(B)}k.appendChild(L)}k.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(k)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let m=i[c]??0,l=Jt(c),u=document.createElement("span");u.className=m>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",u.textContent=`${l.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(c,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=a[a.length-1],m=r[r.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${at(c[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,l=Jt(c.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let p=document.createElement("span");p.className="bp-mgmt-strong",p.textContent=Mt(c.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=c.mpn||c.key;let y=document.createElement("span");if(y.className=`bp-tone-${l.tone}`,y.textContent=l.label,d.append(p,b,y),typeof c.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(c.stock),d.appendChild(f)}if(u.appendChild(d),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((f)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(x,C)=>{let I=this.watchGen,D=this.project;this.planStatus="",this.cb.hub.rpc(x,{pro:D,...C}).catch((K)=>{if(I!==this.watchGen||D!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydratedKey!==i&&this.project){this.planHydratedKey=i;let x=this.watchGen,C=this.project;this.cb.hub.rpc("plan.get",{pro:C,board:!0}).then((I)=>{if(x!==this.watchGen||C!==this.project||!I?.panel)return;this.planHydratedBoard=I.panel.board??null,this.planHydratedDraw=I.panel.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),c.setAttribute("data-testid","mgmt-plan-off"),c.setAttribute("aria-pressed",!a?"true":"false"),c.textContent=h("gpui.bots.recall.off","Off"),c.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,c),e.appendChild(s);for(let x of t.elsewhere??[]){let C=document.createElement("div");C.className="bp-plan-elsewhere";let I=document.createElement("span");I.className="bp-tone-warn bp-mgmt-flex1",I.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:x.name||x.rel||""}),C.appendChild(I),e.appendChild(C)}if(t.empty){let x=document.createElement("div");x.className="bp-mgmt-note";let C=document.createElement("div");C.className="bp-dim",C.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let I=document.createElement("div");return I.className="bp-mgmt-faint",I.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),x.append(C,I),e.appendChild(x),e}let m=t.awaiting??0,l=t.blocked??0,u=t.done??0,d=t.total??0,p=t.revision??0,b=Kn(t),y=zn(t),f=y.reduce((x,C)=>x+C.count,0),g=document.createElement("div");g.className="bp-plan-status";let w=document.createElement("div");w.className="bp-plan-status-top";let k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${b.tone}`,k.textContent=h(b.key,b.label),w.appendChild(k),p>0){let x=document.createElement("span");x.className="bp-dim",x.textContent=`v${p}`,w.appendChild(x)}let S=document.createElement("span");if(S.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":l>0?"bp-tone-bad":"bp-dim"),S.textContent=d>0?`${u}/${d} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),w.appendChild(S),!t.live){let x=document.createElement("span");x.className="bp-mgmt-pill",x.textContent=h("gpui.mgmt.plan.saved","saved plan"),w.appendChild(x)}if(g.appendChild(w),f>0){let x=document.createElement("div");x.className="bp-plan-segbar";for(let C of y){if(C.count<=0)continue;let I=document.createElement("div");I.className=`bp-plan-seg bp-tone-bg-${C.tone}`,I.style.flexGrow=String(C.count),x.appendChild(I)}g.appendChild(x)}e.appendChild(g);let L=document.createElement("div");if(L.className="bp-mgmt-head",m>0){let x=document.createElement("button");x.type="button",x.className="primary bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-approve-all"),x.textContent=h("gpui.mgmt.plan.all","Approve all"),x.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(x)}if(t.routing){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-stop"),x.textContent=h("gpui.mgmt.plan.stop","Stop routing"),x.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(x)}if(t.live&&u>0){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-verify"),x.textContent=h("gpui.mgmt.plan.verify","Verify"),x.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(x)}let M=document.createElement("span");M.className="bp-mgmt-flex1";let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.setAttribute("data-testid","mgmt-plan-hide"),B.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),B.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.append(M,B),e.appendChild(L);let H=Array.isArray(t.asks)?t.asks:[];if(H.length>0){let x=H.map((le)=>le.what||"").filter(Boolean).join(", "),C=H[0]?.note||"",I=document.createElement("div");I.className="bp-plan-elsewhere";let D=document.createElement("div");D.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=x?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:x}):h("gpui.mgmt.plan.reqplain","Approval requested"),D.appendChild(K),C){let le=document.createElement("div");le.className="bp-dim",le.textContent=C,D.appendChild(le)}I.appendChild(D),e.appendChild(I)}if(this.planStatus){let x=document.createElement("div");x.className="bp-mgmt-note bp-plan-err bp-tone-bad";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):Ee(this.planStatus);let I=document.createElement("button");I.type="button",I.className="icon",I.textContent="×",I.title=h("common.close","Close"),I.addEventListener("click",()=>{this.planStatus="",this.render()}),x.append(C,I),e.appendChild(x)}if(t.keys_note){let x=document.createElement("div");x.className="bp-mgmt-note bp-dim";let C="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";x.textContent=t.keys_note===C?h("gpui.mgmt.plan.keysnote",C):Ee(t.keys_note),e.appendChild(x)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let x=document.createElement("div");x.className="bp-plan-stackup";let C=document.createElement("button");C.type="button",C.className="bp-plan-stackup-head",C.setAttribute("data-testid","mgmt-plan-stackup-toggle"),C.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let I=document.createElement("span");I.className="bp-plan-chev",I.textContent=this.planStackupOpen?"▾":"▸";let D=document.createElement("span");if(D.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),C.append(I,D),C.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),x.appendChild(C),this.planStackupOpen){let K=document.createElement("div");if(K.className="bp-plan-stackup-body",K.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let le=document.createElement("div");le.className="bp-dim",le.textContent=W,K.appendChild(le)}for(let le of _){let N=document.createElement("div");N.className="bp-mgmt-faint",N.textContent=`· ${le}`,K.appendChild(N)}x.appendChild(K)}e.appendChild(x)}let j=(x,C,I,D)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(C?" active":""),K.setAttribute("data-testid",I),K.setAttribute("aria-pressed",C?"true":"false"),K.textContent=x,K.addEventListener("click",D),K},me=document.createElement("div");if(me.className="bp-plan-viewbar",me.append(j(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),j(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),j(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let x=document.createElement("span");x.className="bp-plan-sep";let C=document.createElement("span");C.className="bp-plan-sep";let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn bp-plan-mini-btn",I.setAttribute("data-testid","mgmt-plan-fit"),I.textContent=h("gpui.mgmt.plan.fit","Fit"),I.addEventListener("click",()=>this.planCanvas?.fitAll()),me.append(x,j(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),j(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),j(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),C,j(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),I)}let ce=document.createElement("span");ce.className="bp-mgmt-flex1";let ie=document.createElement("button");ie.type="button",ie.className="bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-expand"),ie.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),ie.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),me.append(ce,ie),e.appendChild(me);let ye=this.planHydratedKey===i&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ke=this.planHydratedKey===i&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Ne=(ke.bands??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),ge=(ke.regions??[]).map((x)=>{let C=this.planOptimistic.get(x.id);if(!C)return{...x};return{...x,...C,edited:!0,state:x.state==="proposed"?"edited":x.state}}),Me=[],T=(t.layers??[]).map((x)=>{let C=[];for(let I of x.items??[]){let D=this.planOptimistic.get(I.id);if(!D){C.push(I);continue}let K={...I,width:typeof D.width==="number"?D.width:I.width,locked:typeof D.locked==="boolean"?D.locked:I.locked,edited:!0,state:I.state==="proposed"?"edited":I.state};if(typeof D.layer==="string"&&D.layer!==x.layer)Me.push({target:D.layer,item:K});else C.push(K)}return{...x,items:C}});for(let x of Me){let C=T.find((I)=>I.layer===x.target);if(C)C.items=[...C.items??[],x.item]}let re=this.planGridMode==="all"?T.map((x)=>x.layer):this.planGridMode==="single"?[this.planShownLayers.find((x)=>T.some((C)=>C.layer===x))??rt(T)[0]??T[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((x)=>T.some((C)=>C.layer===x))?this.planShownLayers.slice(0,2):rt(T);if(this.planViewMode!=="list"&&T.length>1){let x=document.createElement("div");x.className="bp-plan-layerbar";for(let C of T){let I=re.includes(C.layer);x.appendChild(j(C.title||C.layer,I,`mgmt-plan-layerpill-${C.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"){if(!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}else this.planGridMode="single",this.planShownLayers=[C.layer];this.render()}))}e.appendChild(x)}let se=(x,C)=>{let I=this.planOptimistic.get(x)??{};if(this.planOptimistic.set(x,{...I,...C}),typeof C.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[C.layer];else if(this.planGridMode==="pair"&&!re.includes(C.layer))this.planShownLayers=re.length>=2?[re[0],C.layer]:[...re,C.layer]}let D={...C};if(Array.isArray(C.outline)&&Array.isArray(C.outline[0])&&typeof C.outline[0][0]==="number"){let K=ge.find((le)=>le.id===x);if(K?.holes&&K.holes.length>0)D.outline=[C.outline,...K.holes]}this.render(),n("plan.update",{ops:[{op:"set",id:x,fields:D}]})};if(this.planCommitFields=se,this.planSelectedId){let x="",C=null;for(let I of T){let D=(I.items??[]).find((K)=>K.id===this.planSelectedId);if(D){x=I.layer,C=D;break}}if(C){let I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let D=document.createElement("div");D.className="bp-plan-ins-row";let K=document.createElement("span");K.className="bp-plan-ins-sw",K.style.background=C.kind==="corridor"?vt(C.name||C.id,C.color||""):ft(C.name||C.id,C.color||"");let le=document.createElement("span");le.className="bp-mgmt-strong",le.textContent=C.name||C.id;let N=document.createElement("span");if(N.className="bp-dim",N.textContent=x,D.append(K,le,N),C.edited||C.state==="edited"){let ee=document.createElement("span");ee.className="bp-plan-ins-pill warn",ee.textContent=h("gpui.mgmt.plan.edited","Edited"),D.appendChild(ee)}if(C.locked){let ee=document.createElement("span");ee.className="bp-plan-ins-pill",ee.textContent=h("gpui.mgmt.plan.locked","Locked"),D.appendChild(ee)}let Y=document.createElement("span");Y.className="bp-mgmt-flex1",D.appendChild(Y);let Ie=document.createElement("button");if(Ie.type="button",Ie.className="bp-mgmt-btn bp-plan-mini-btn",Ie.setAttribute("data-testid","mgmt-plan-lock"),Ie.textContent=C.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),Ie.addEventListener("click",()=>se(C.id,{locked:!C.locked})),D.appendChild(Ie),C.state==="proposed"||C.state==="edited"){let ee=document.createElement("button");ee.type="button",ee.className="primary bp-mgmt-btn bp-plan-mini-btn",ee.textContent=h("android.hub.machines.approve","Approve"),ee.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!0}));let be=document.createElement("button");be.type="button",be.className="bp-mgmt-btn bp-plan-mini-btn",be.textContent=h("gpui.mgmt.plan.reject","Reject"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[C.id],approve:!1})),D.append(ee,be)}let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-note-toggle"),Ae.textContent=h("gpui.mgmt.plan.addnote","Add note"),Ae.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let pe=document.createElement("button");if(pe.type="button",pe.className="icon",pe.textContent="×",pe.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),D.append(Ae,pe),I.appendChild(D),!C.locked){let ee=document.createElement("div");if(ee.className="bp-plan-ins-row",C.kind==="corridor"){let Te=typeof C.width==="number"?C.width:1.5,ue=document.createElement("span");ue.className="bp-dim",ue.textContent=h("gpui.mgmt.plan.width","Width");let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn bp-plan-mini-btn",te.setAttribute("data-testid","mgmt-plan-w-down"),te.textContent="-",te.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,Te-0.25)*100)/100;se(C.id,{width:Ue})});let je=document.createElement("span");je.className="bp-plan-ins-val",je.textContent=`${Te.toFixed(2)}mm`;let Z=document.createElement("button");Z.type="button",Z.className="bp-mgmt-btn bp-plan-mini-btn",Z.setAttribute("data-testid","mgmt-plan-w-up"),Z.textContent="+",Z.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,Te+0.25)*100)/100;se(C.id,{width:Ue})});let Ce=document.createElement("span");Ce.className="bp-plan-sep",ee.append(ue,te,je,Z,Ce)}let be=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((Te)=>Te.layer):T.map((Te)=>Te.layer);if(be.length>0){let Te=document.createElement("span");Te.className="bp-dim",Te.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),ee.appendChild(Te);for(let ue of be)ee.appendChild(j(ue,ue===x,`mgmt-plan-move-${ue}`,()=>{if(ue!==x)se(C.id,{layer:ue})}))}I.appendChild(ee)}if(this.planNoteOpen){let ee=document.createElement("form");ee.className="bp-plan-note-form";let be=document.createElement("input");be.type="text",be.className="bp-plan-note-input",be.setAttribute("data-testid","mgmt-plan-note-input"),be.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let Te=document.createElement("button");Te.type="submit",Te.className="primary bp-mgmt-btn bp-plan-mini-btn",Te.setAttribute("data-testid","mgmt-plan-note-submit"),Te.textContent=h("gpui.mgmt.plan.addnote","Add note"),ee.append(be,Te),ee.addEventListener("submit",(ue)=>{ue.preventDefault();let te=be.value.trim();if(!te)return;be.value="",this.planNoteOpen=!1,this.render(),n("plan.update",{ops:[{op:"note",id:C.id,text:te}]})}),I.appendChild(ee)}if(this.planViewMode!=="list"&&!C.locked){let ee=document.createElement("div");ee.className="bp-plan-hint",ee.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(ee)}e.appendChild(I)}}let J=document.createElement("div");J.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),J.setAttribute("data-testid","mgmt-plan-rows");let de=h("gpui.mgmt.plan.done","done");for(let x of T){let C=x.items??[],I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let D=document.createElement("div");D.className="bp-mgmt-row-line";let K=document.createElement("span");K.className="bp-mgmt-strong",K.textContent=x.layer;let le=document.createElement("span");if(le.className="bp-dim bp-mgmt-flex1",le.textContent=`${x.role?`${x.role} · `:""}${x.done??0}/${C.length} ${de}`,D.append(K,le),x.status!=="approved"&&C.length>0){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.plan.layer","Approve layer"),N.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!0}));let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent=h("gpui.mgmt.plan.reject","Reject"),Y.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!1})),D.append(N,Y)}if(I.appendChild(D),x.stackup){let N=document.createElement("div");N.className="bp-plan-layer-stackup",N.textContent=x.stackup,I.appendChild(N)}J.appendChild(I);for(let N of C){if(this.planHideDone&&_n(N))continue;let Y=this.planSelectedId===N.id,Ie=document.createElement("div");Ie.className="bp-mgmt-row bp-plan-row"+(Y?" active":""),Ie.setAttribute("data-testid",`mgmt-plan-row-${N.id}`);let Ae=document.createElement("div");Ae.className="bp-mgmt-row-line";let pe=document.createElement("span");pe.className=`bp-plan-swatch bp-plan-st-${N.state||"proposed"}`,pe.style.setProperty("--swatch-color",N.color||"#8a8a8a");let ee=document.createElement("span");ee.className="bp-mgmt-flex1"+(N.state==="blocked"||N.state==="failed"?" bp-tone-bad":N.state==="edited"?" bp-tone-warn":N.state==="rejected"||N.state==="routed"||N.state==="verified"?" bp-dim":""),ee.textContent=`${N.name||N.id}${N.locked?" \uD83D\uDD12":""}`;let be=[];if(N.kind==="plane"){if(N.reference)be.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:N.reference}))}else{let te=N.nets??0;be.push(te===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:te}))}if(typeof N.width==="number"&&Number.isFinite(N.width))be.push(`${N.width.toFixed(2)}mm`);if(N.impedance)be.push(N.impedance);let Te=be.join(" · "),ue=document.createElement("span");if(ue.className="bp-plan-mark "+(N.state==="blocked"||N.state==="failed"?"bp-tone-bad":N.state==="verified"||N.state==="routed"?"bp-tone-ok":N.state==="approved"?"bp-tone-accent":"bp-dim"),ue.textContent=qn(N),Ae.append(pe,ee,ue),N.state==="proposed"||N.state==="edited"){let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn",te.textContent="✓",te.title=h("gpui.mgmt.plan.layer","Approve layer"),te.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!0})});let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent="✗",je.title=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",(Z)=>{Z.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!1})}),Ae.append(te,je)}if(Ie.appendChild(Ae),Te){let te=document.createElement("div");te.className="bp-mgmt-row-sub bp-plan-detail bp-dim",te.textContent=Te,Ie.appendChild(te)}if(N.state==="routing"&&typeof N.total==="number"&&N.total>0){let te=document.createElement("div");te.className="bp-plan-microbar";let je=document.createElement("div");je.className="bp-plan-microbar-fill";let Z=Math.max(0,Math.min(100,Math.round((N.routed??0)/N.total*100)));je.style.width=`${Z}%`,te.appendChild(je),Ie.appendChild(te)}if(N.problem_text){let te=document.createElement("div");te.className="bp-plan-problem",te.textContent=N.problem_text,Ie.appendChild(te)}Ie.addEventListener("click",()=>{this.planSelectedId=N.id,n("plan.focus",{id:N.id}),this.render()}),J.appendChild(Ie)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new en({onSelect:(D)=>{if(this.planSelectedId=D,!D)this.planNoteOpen=!1;this.render()},onFocusItem:(D)=>{n("plan.focus",{id:D})},onOptimisticPatch:(D,K)=>{let le=this.planOptimistic.get(D)??{};this.planOptimistic.set(D,{...le,...K})},onCommitFields:(D,K)=>{(this.planCommitFields??se)(D,K)},onApproveLayer:(D,K)=>{n("plan.approve",{layer:D,ids:[],approve:K})},onQuickApprove:(D,K)=>{n("plan.approve",{layer:"",ids:D,approve:K})}});let x=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,C=this.planExpanded||this.panelEl.clientWidth>=540||x;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:re,selectedId:this.planSelectedId,board:ye,bands:Ne,regions:ge,layers:T},C);let I=document.createElement("div");I.className="bp-plan-canvas-scroll",I.appendChild(this.planCanvas.root),e.appendChild(I)}if(this.planViewMode!=="canvas")e.appendChild(J);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let x=document.createElement("div");x.className="bp-plan-footer",x.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(x)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,k={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:w,...k}).catch((M)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=M instanceof Error?M.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Yn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(c?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(u),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}m.appendChild(l),o.appendChild(m);let p=Jn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(p.button?"bp-tone-warn":"bp-dim"),f.textContent=p.text,y.appendChild(f),p.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=p.button,w.addEventListener("click",()=>n("drc")),y.appendChild(w)}b.appendChild(y),o.appendChild(b);for(let w of t.conflicts??[]){let k=document.createElement("div");k.className="bp-mgmt-row bp-tone-bad",k.textContent=w,o.appendChild(k)}for(let w of t.suggestions??[]){let k=document.createElement("div");k.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.apply","Apply"),M.addEventListener("click",()=>n("apply",{key:w.key})),S.append(L,M),k.appendChild(S),o.appendChild(k)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,k.appendChild(L),S){let M=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=h("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:M})),k.appendChild(B)}w.appendChild(k),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=h("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),k.append(S,L),w.appendChild(k);for(let M of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=M,w.appendChild(B)}o.appendChild(w)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=h("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=h("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=h("gpui.mgmt.fab.extra","Costs more");let M=document.createElement("span");M.className="bp-mgmt-col bp-mgmt-col-read",M.textContent=h("gpui.mgmt.fab.readcol","Read"),w.append(k,S,L,M),o.appendChild(w);for(let H of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let j=document.createElement("span");j.className="bp-mgmt-flex1"+(H.changed?" bp-tone-warn":H.inherited?" bp-dim":""),j.textContent=`${H.changed?"• ":""}${H.label??""}`;let me=document.createElement("span");me.className="bp-mgmt-col",me.textContent=H.free?.text||"—";let ce=document.createElement("span");ce.className="bp-mgmt-col bp-dim",ce.textContent=H.extra?.text||"—";let ie=H.free&&typeof H.free==="object"?H.free:H.extra,ye=ie?.fetched??"",ke=Boolean(ye)&&ie?.confidence!=="published",Ne=ye?ke?`${ye}*`:ye:"—",ge=ie?.source??"",Me;if(ge.startsWith("https://")&&ye){let T=document.createElement("a");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",T.href=ge,T.target="_blank",T.rel="noopener noreferrer",T.textContent=Ne,Me=T}else{let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",T.textContent=Ne,Me=T}_.append(j,me,ce,Me),W.appendChild(_),o.appendChild(W)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(B)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var ys={trs:(e)=>e,t:(e,t)=>t},ws=new Set(["/settle"]);function li(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function di(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function pi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function mi(e,t=ys){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let c=ws.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:m}=ci(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:di(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function hi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let b of i)d.set(b.id,b.title||b.id);let p=new Set;for(let b of c)if(b.action.type==="thread")p.add(b.action.id);for(let b of n.threads){if(!b.id||p.has(b.id))continue;p.add(b.id);let{urgency:y,want:f}=ci(b);c.push({label:b.title||"Untitled thread",place:b.project?d.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:di(b),action:{type:"thread",id:b.id}})}}let m=[];for(let d=0;d0)m.push({score:f,index:d,item:p})}m.sort((d,p)=>{if(o){let f=(p.item.urgency??0)-(d.item.urgency??0);if(f!==0)return f}if(p.score!==d.score)return p.score-d.score;let b=d.item.kind==="thread"?0:1,y=p.item.kind==="thread"?0:1;if(b!==y)return b-y;return d.index-p.index});let l=new Set,u=[];for(let d of m){let p=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(p))continue;if(l.add(p),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=mi(t,{t:h,trs:Ee}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=hi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,d)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(d,p),m.appendChild(b),p{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var xs=new Set(["resume","raise","retry","move","signin"]);function gi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Rt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(xs.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function fi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class an{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";p.textContent=b,d.appendChild(p);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(d.appendChild(y),u.appendChild(d),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(l,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let c=document.createElement("div");c.className="bp-set-head",c.textContent="Paired devices",o.appendChild(c);try{let m=await this.cb.onLoadDevices();if(m.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",o.appendChild(l)}else for(let l of m){let u=document.createElement("div");u.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let p=document.createElement("div");if(p.textContent=l.title||l.head||"",d.appendChild(p),l.text||l.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=l.text||l.detail||"",d.appendChild(b)}if(u.appendChild(d),l.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of l.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let l=document.createElement("div");l.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";l.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(l)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function rn(e){return xe("pre","bp-context-code",e)}function Cs(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,Ee(e))}function jt(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),Cs(t)),n}class on{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(jt(t.path,t.status),xe("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,rn(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),rn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,Ee(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(jt(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(jt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(jt(s.name,s.status),rn(a)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=xe("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var vi="http://www.w3.org/2000/svg";function yi(){let e=document.createElementNS(vi,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(vi,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function ks(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function wi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class ln{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=h("thread.new","New thread"),c.setAttribute("aria-label",h("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),r.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${ks(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?gi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,c.appendChild(m);for(let u of r.actions){if(!Rt(u,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=u.label,d.setAttribute("data-testid",`need-${u.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(p)=>{p.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=l,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),c.appendChild(m);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(r.kind==="projects"){let o=r.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!c&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,d=r.open?"▾":"▸";if(l.textContent=`${r.title.toUpperCase()} (${u}) ${d}`,r.hint)l.title=r.hint;l.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(l)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!c||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",m.appendChild(l)}for(let l of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(l.off?" bp-dim":""),u.setAttribute("data-project-id",l.id),l.nav||l.key)u.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let p=document.createElement("button");p.type="button",p.className="bp-proj-toggle";let b=yi();if(l.css)b.style.color=l.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=l.title||l.id,p.append(b,y),l.fold==="project-fold"&&l.nav)p.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${l.id}`),l.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(p,f),u.appendChild(d),!l.folded||Boolean(t)){let g=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:wi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,m=yi();if(i.css)m.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(m,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!c)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:wi(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let l of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`@${l.name}`,u.append(d,p),u.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(c,m),r.appendChild(o);for(let l of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,u.appendChild(d),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ss(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function As(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?c/m:0));s[a]=l<0?l*32768:l*32767}return s}class cn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ss(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),c=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=As(r.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var Ei=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],xi=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ci=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ki=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ls=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[c]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ps=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Ns=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class dn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},r=(u)=>{let d=0,p=0,b=0;for(let y=1;y<=u.maxBits;y++){d|=a(1);let f=u.counts[y];if(d-f{let d=c+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let p=o.length;while(p{m(1),o[c++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let p=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(p^65535)!==b)throw Error("invalid stored block length");if(n+p>e.length)throw Error("truncated stored payload");m(p);for(let y=0;y=e.length)break}else if(d===1||d===2){let p=Ps,b=Ns;if(d===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,w=new Uint8Array(19);for(let B=0;BS)throw Error("code length overflow");for(let _=0;_S)throw Error("code length overflow");M+=H}else if(B===18){let H=a(7)+11;if(M+H>S)throw Error("code length overflow");M+=H}else throw Error("invalid code length symbol")}p=Et(L,y),b=Et(L.subarray(y),f)}while(!0){let y=r(p);if(y<256)l(y);else if(y===256)break;else{let f=y-257;if(f>=Ei.length)throw Error("invalid length symbol");let g=Ei[f]+(xi[f]?a(xi[f]):0),w=r(b);if(w>=Ci.length)throw Error("invalid distance symbol");let k=Ci[w]+(ki[w]?a(ki[w]):0);m(g);let S=this.winPos-k&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new dn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(c))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ms=new TextDecoder;function Si(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ai(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,m=i(o&31);if(m===null)return null;switch(c){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let l=e.subarray(t,t+m);return t+=m,l}case 3:{if(t+m>e.length)return null;let l=Ms.decode(e.subarray(t,t+m));return t+=m,l}case 4:{if(m>e.length)return null;let l=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Pi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,c=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Li(m),u=[],d=[],p=0,b=0;while(l.more()){let y=l.nextU32(),f=u.length,g=1/0,w=1/0,k=-1/0,S=-1/0;if(a===2)p=p+l.nextI32()|0,b=b+l.nextI32()|0,u.push(p,b),g=k=p,w=S=b;else{let M=Math.min(l.nextU32(),1048576);for(let B=0;Bk)k=p;if(bS)S=b}}let L=(u.length-f)/2;if(L>0){let M=a===2||L===1?2:a===0?0:1,B=a===0?0:o;d.push({info:y,x0:g-B,y0:w-B,x1:k+B,y1:S+B,at:f,n:L,kind:M})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:c,pts:new Float32Array(u),pieces:d}}function Ni(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Mi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,c=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,l=(t-c)/r;if(m<0||m>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ti=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Bi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class mn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Ii(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,c=!1,m=-1,l=null,u=new mn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let p=document.createElement("div");p.className="bp-pane-bar bp-browser-nav";function b(J,de,x){let C=document.createElement("button");if(C.type="button",C.className="bp-v-btn",C.textContent=J,C.setAttribute("data-testid",de),x)C.title=x;return C}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let k=document.createElement("input");k.type="text",k.className="bp-browser-input",k.placeholder="https://…",k.autocomplete="off",k.spellcheck=!1,k.setAttribute("data-testid","browser-url");let S=b("Go","browser-go","Navigate");S.type="submit",w.append(k,S);let L=b("Take over","browser-takeover");L.classList.add("is-primary"),p.append(y,f,g,w,L);let M=document.createElement("div");M.className="bp-browser-drive-bar",M.hidden=!0;let B=document.createElement("div");B.className="bp-browser-keys-row";let H=document.createElement("input");H.type="text",H.className="bp-browser-input",H.placeholder="Type text or press Enter/Tab/Arrows…",H.autocomplete="off",H.spellcheck=!1,H.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");B.append(H,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[J,de]of Ti){let x=b(J,`browser-key-${de}`);x.addEventListener("click",()=>ge("press",{key:de})),_.append(x)}M.append(B,_);let j=document.createElement("div");j.className="bp-browser-err",j.setAttribute("data-testid","browser-error"),j.hidden=!0;let me=document.createElement("div");me.className="bp-browser-stage",me.setAttribute("data-testid","browser-stage");let ce=document.createElement("img");ce.className="bp-browser-img",ce.alt="Hub browser screen",ce.draggable=!1,ce.hidden=!0,ce.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",me.append(ce,ie);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,d.append(p,M,j,me,ye),e.replaceChildren(d);function ke(J){j.textContent=J,j.hidden=!J}function Ne(){M.hidden=!s,ye.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),ce.classList.toggle("is-driving",s)}function ge(J,de={},x){u.enqueue(async()=>{if(!i)return;ke("");try{if(await t.hub.rpc("browser",{thread:n,op:J,...de}),!i)return;x?.(),re()}catch(C){if(!i)return;ke(C instanceof Error?C.message:String(C))}})}function Me(J){ge("toolbar",{command:J},()=>{s=!0,Ne()})}y.addEventListener("click",()=>Me("back")),f.addEventListener("click",()=>Me("forward")),g.addEventListener("click",()=>Me("reload")),w.addEventListener("submit",(J)=>{J.preventDefault();let de=Bi(k.value);if(!de)return;if(k.value=de,!s)ge("takeover",{},()=>{s=!0,Ne()});ge("navigate",{url:de},()=>{s=!0,Ne()})}),L.addEventListener("click",()=>{if(s)ge("handback",{},()=>{s=!1,Ne()});else ge("takeover",{},()=>{s=!0,Ne(),H.focus()})});function T(){let J=H.value;if(!J)return;H.value="",ge("type",{text:J})}W.addEventListener("click",T),H.addEventListener("keydown",(J)=>{if(!s)return;if(J.key==="Enter"){if(J.preventDefault(),H.value)T();ge("press",{key:"Enter"});return}if(J.key==="Tab"||J.key==="Escape"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="ArrowLeft"||J.key==="ArrowRight"||J.key==="Backspace"&&H.value==="")J.preventDefault(),ge("press",{key:J.key})}),ce.addEventListener("click",(J)=>{if(!s||!a)return;let de=ce.getBoundingClientRect(),x=Mi(J.clientX,J.clientY,{left:de.left,top:de.top,width:de.width,height:de.height,naturalWidth:ce.naturalWidth,naturalHeight:ce.naturalHeight});if(!x)return;ge("click",x)}),ce.addEventListener("wheel",(J)=>{if(!s||!a)return;J.preventDefault();let de=Math.round(J.deltaX),x=Math.round(J.deltaY);if(de===0&&x===0)return;ge("scroll",{dx:de,dy:x})},{passive:!1});async function re(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let J=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(J.ok){let de=await J.blob();if(!i)return;let x=URL.createObjectURL(de),C=r;if(r=x,ce.src=x,ce.hidden=!1,ie.hidden=!0,a=!0,C)URL.revokeObjectURL(C)}else if(!a)ce.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!a)ce.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let se=t.hub.onFrame((J)=>{if(!i)return;if(J.t==="shot"&&J.bot===n){if(typeof J.n==="number"){if(J.n===m)return;m=J.n}re()}});return re(),{destroy(){if(i=!1,se(),l?.abort(),r)URL.revokeObjectURL(r),r=""}}}function O(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ht(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function ji(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Bs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ri(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Is(e){let t=ji(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Hi(e,t,n,i){let s=!0,a="",r="",o=O("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=O("div","bp-pane-bar"),m=O("div","bp-files-crumbs"),l=O("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void f(a)),c.append(m,l);let u=O("div","bp-files-split"),d=O("div","bp-files-list");d.setAttribute("data-testid","files-list");let p=O("div","bp-files-preview");p.setAttribute("data-testid","files-preview"),p.append(O("div","bp-pane-empty","Select a file to preview")),u.append(d,p),o.append(c,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=O("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let w=a.split("/").filter(Boolean),k="";for(let S of w){k=k?`${k}/${S}`:S;let L=k;m.append(O("span","bp-vh-sep","/"));let M=O("button","bp-crumb-btn",S);M.type="button",M.addEventListener("click",()=>void f(L)),m.append(M)}}async function y(g,w,k){r=g,p.replaceChildren();let S=O("div","bp-files-prev-head");S.append(O("span","bp-files-prev-name",g));let L=O("div","bp-files-prev-acts"),M=Is(w);if(M){let _=O("button","bp-v-btn is-primary",`Open in ${M}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(M,g)),L.append(_)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,H=O("a","bp-v-btn","Download");H.href=B,H.download=w,L.append(H),S.append(L),p.append(S);let W=ji(w);if(Bs(W)){let _=O("div","bp-files-img-wrap"),j=document.createElement("img");j.className="bp-files-img",j.alt=w,j.src=B,_.append(j),p.append(_);return}if(k>524288&&!Ri(W)){p.append(O("div","bp-pane-empty",`Binary file (${Ht(k)}). Use Download to save.`));return}if(Ri(W)||k<=65536){let _=O("div","bp-pane-empty","Loading…");p.append(_);try{let j=await fetch(B,{credentials:"same-origin"});if(!s||r!==g)return;if(!j.ok){_.textContent=`Could not load file (${j.status})`;return}if((j.headers.get("content-type")||"").startsWith("image/")){_.remove();let se=document.createElement("img");se.className="bp-files-img",se.alt=w,se.src=B,p.append(se);return}let ce=262144,ie=[],ye=0,ke=!1;if(j.body){let se=j.body.getReader();try{while(!0){let{done:J,value:de}=await se.read();if(J||!de)break;if(ye+de.byteLength>ce){let x=ce-ye;if(x>0)ie.push(de.subarray(0,x)),ye+=x;ke=!0,await se.cancel();break}ie.push(de),ye+=de.byteLength}}finally{se.releaseLock()}}if(!s||r!==g)return;let Ne=new Uint8Array(ye),ge=0;for(let se of ie)Ne.set(se,ge),ge+=se.byteLength;let Me=!1;for(let se=0;seS.dir===L.dir?S.name.localeCompare(L.name):S.dir?-1:1),d.replaceChildren(),g){let S=O("button","bp-file-row is-dir");S.type="button",S.append(O("span","bp-file-icon","↰"),O("span","bp-file-name",".."));let L=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";S.addEventListener("click",()=>void f(L)),d.append(S)}if(k.length===0){d.append(O("div","bp-pane-empty","Empty folder"));return}for(let S of k){let L=g?`${g}/${S.name}`:S.name,M=O("button","bp-file-row"+(S.dir?" is-dir":"")+(L===r?" is-sel":""));M.type="button",M.setAttribute("data-testid",`file-row-${S.name}`),M.append(O("span","bp-file-icon",S.dir?"▸":"·"),O("span","bp-file-name",S.name),O("span","bp-file-size",S.dir?"":Ht(S.size))),M.addEventListener("click",()=>{if(S.dir)f(L);else d.querySelectorAll(".bp-file-row.is-sel").forEach((B)=>B.classList.remove("is-sel")),M.classList.add("is-sel"),y(L,S.name,S.size)}),d.append(M)}}catch(w){if(!s)return;d.replaceChildren(O("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return f(""),{destroy(){s=!1}}}function Di(e,t,n){let i=!0,s=O("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=O("div","bp-pane-bar"),r=O("span","bp-diff-summary","Loading diff…"),o=O("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let c=O("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(a,c),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){r.textContent="Not a git repository",c.append(O("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof l?.diff==="string"?l.diff:"";if(!u.trim()){r.textContent="Clean working tree",c.append(O("div","bp-pane-empty","No uncommitted changes."));return}let d=u.split(` -`),p=0,b=0,y=0,f=document.createDocumentFragment(),g=O("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=O("div","bp-diff-file"),p++;let k=w.match(/ b\/(.+)$/);g.append(O("div","bp-diff-file-head",k?k[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))g.append(O("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))g.append(O("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))b++,g.append(O("div","bp-diff-line is-add",w));else if(w.startsWith("-"))y++,g.append(O("div","bp-diff-line is-del",w));else g.append(O("div","bp-diff-line",w))}if(g.childNodes.length>0)f.append(g);r.textContent=`${p||1} file${p===1?"":"s"} · +${b} -${y}`,c.append(f)}catch(l){if(!i)return;r.textContent="Diff unavailable",c.append(O("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return m(),{destroy(){i=!1}}}function Fi(e,t,n){let i=!0,s="checks",a=O("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=O("div","bp-pane-bar"),o=O("div","bp-review-tabs"),c=O("button","bp-v-btn is-on","Checks"),m=O("button","bp-v-btn","BOM"),l=O("button","bp-v-btn","Comments");c.type=m.type=l.type="button",o.append(c,m,l);let u=O("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void y()),r.append(o,u);let d=O("div","bp-review-body");d.setAttribute("data-testid","review-body"),a.append(r,d),e.replaceChildren(a);function p(f){s=f,c.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),y()}c.addEventListener("click",()=>p("checks")),m.addEventListener("click",()=>p("bom")),l.addEventListener("click",()=>p("comments"));function b(f){let g=O("div","bp-review-md"),w=f.split(` -`),k=0;while(k{B.preventDefault();let H=L.value.trim();if(!H)return;M.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:H}).then(()=>{L.value="",M.disabled=!1,y()},()=>{M.disabled=!1})}),d.append(S),k.length===0){d.append(O("div","bp-pane-empty","No review comments yet."));return}for(let B of k){let H=O("div","bp-review-comment"+(B.resolved?" is-resolved":"")),W=[B.by||"review",B.file,B.layer,B.item].filter(Boolean).join(" · ");H.append(O("div","bp-review-comment-meta",W),O("div","bp-review-comment-text",B.text)),d.append(H)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(d.replaceChildren(),g.line||g.gate){let w=O("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));d.append(w)}if(g.err)d.append(O("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let w=O("div","bp-review-tasks");g.tasks.forEach((k,S)=>{let L=O("label","bp-review-task"),M=document.createElement("input");M.type="checkbox",M.checked=!!(k.done??k.checked);let B=typeof k.index==="number"?k.index:S;M.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:B}).then(()=>void y(),()=>{})}),L.append(M,O("span",void 0,k.text||k.label||`Item ${S+1}`)),w.append(L)}),d.append(w)}if(g.md&&g.md.trim())d.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))d.append(O("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;d.replaceChildren(O("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function $i(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class hn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,m=n*0.5,l=this.scale,u=this.cx,d=this.cy,p=u-c/l,b=u+c/l,y=d-m/l,f=d+m/l,{off:g,dim:w,lift:k}=this.masks,S=[],L=[];for(let B=0;B>>H&1)===1)continue;if(H===k)L.push(B);else S.push(B)}let M=S.concat(L);r.lineCap="round",r.lineJoin="round";for(let B=0;B>>W.layer&1)===1,j=W.alpha*(_?0.25:1);if(j<=0.01)continue;this.drawChunk(r,W,j,p,y,b,f,u,d,l,c,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let B=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let H=0;Ha||f.y1r)continue;if(f.n<3)continue;let g=(d[f.at]-o)*m+l,w=(d[f.at+1]-c)*m+u;e.moveTo(g,w);for(let k=1;k0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=p,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let w=(d[g.at]-o)*m+l,k=(d[g.at+1]-c)*m+u;e.moveTo(w+b,k),e.arc(w,k,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=p,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(d[f.at]-o)*m+l,w=(d[f.at+1]-c)*m+u;if(f.n===1)e.moveTo(g,w),e.lineTo(g+0.01,w);else{e.moveTo(g,w);for(let k=1;k0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,c,m,l,u,d){let p=t.pts,b=$i(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(p[f.at]-c)*l+u,w=(p[f.at+1]-m)*l+d;if(f.kind===2){let k=Math.max(1.5,t.r*l);e.fillStyle=b,e.beginPath(),e.arc(g,w,k,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,w);for(let k=1;k=0;l--){let u=n.chunks[l];if(u.layer<32&&(m>>>u.layer&1)===1)continue;for(let d=0;dp.x1+r||ap.y1+r)continue;let b=(p.x1-p.x0+1)*(p.y1-p.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),c=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,u=s-c.left-c.width*0.5,d=a-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Gi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Ui(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function un(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class bn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Rs=`#version 300 es +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!jn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Rn){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:Rn}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Dn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var ls=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&ls.has(t.id))}function Un(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var cs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ds=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function On(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(cs.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ds.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function Vn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Wn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function _n(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Yt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function qn(e){return e.state==="routed"||e.state==="verified"}function Kn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function zn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Jn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Yn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Xn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Xt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Zn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Zt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Fn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],$n=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Qn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Fn[Qn(i)%Fn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return $n[Qn(e)%$n.length]}function ei(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function ze(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ti(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ni(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[m,c]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function ii(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function si(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Qt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ps(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+m*r,u=i+m*o;return(e-c)*(e-c)+(t-u)*(t-u)}function Gn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(l-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function en(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,l){if(i){for(let p of e){if(p.layer!==n||p.id!==i||p.locked)continue;let d=p.path??[];for(let b=0;b=3)for(let b=0;b=0;p--){let d=t[p];if(d.layer!==n)continue;let b=d.outline??[];if(!Gn(c,u,b))continue;if(!(d.holes??[]).some((f)=>Gn(c,u,f)))return{kind:"region",id:d.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,l=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function ai(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[c,u]=ze(t,m.b[0],m.b[1],n,i),[p,d]=ze(t,m.b[2],m.b[3],n,i),b=Math.abs(p-c),y=Math.abs(d-u);if(b<13||y<9)continue;let f=(c+p)*0.5,g=(u+d)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,c)=>c.score-m.score);let o=[],l=[];for(let m of r){let c=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((p)=>!(c[2]<=p[0]||c[0]>=p[2]||c[3]<=p[1]||c[1]>=p[3])))o.push(c),l.push({text:m.text,cx:m.cx,cy:m.cy})}return l}function ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Rt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}var oi="#111917",ms="#16201d",us="rgba(212, 224, 219, 0.92)",hs="rgba(61, 80, 73, 0.72)",bs="rgba(82, 107, 97, 0.85)",gs="rgba(143, 163, 155, 0.88)",li="#f59e0b",fs="#eef5f2",ci="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function vs(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function ys(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function ws(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class tn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Rt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??rt(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):rt(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ei(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=h("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,m);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let p=document.createElement("canvas");p.className="bp-plan-card-canvas",p.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let d=document.createElement("div");d.className="bp-plan-hover-hud bp-hidden",u.append(p,d);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=p.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(p,e.layer);let g={layer:e.layer,el:t,canvas:p,ctx:y,legendEl:b,okBtn:l,noBtn:m,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:d,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=ws(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let l=document.createElement("button");l.type="button";let m=this.state?.selectedId===o.id;l.className="bp-plan-legend-chip"+(m?" active":"");let c=document.createElement("span");c.className="bp-plan-legend-sw",c.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,l.append(c,u),l.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(l)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height),c=this.getCam(t,l,m),u=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o);if(i.button===2){if(u?.kind==="vertex"){let p=this.getItemPts(u.id,u.isPlane),d=Qt(p,u.idx,u.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(u.id,{[u.isPlane?"outline":"path"]:d})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},u?.kind==="vertex"){let p=this.getItemPts(u.id,u.isPlane),d=p.map((b)=>[b[0],b[1]]);this.selectedVertex={id:u.id,idx:u.idx},this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:u.idx,pts:p.map((b)=>[b[0],b[1]]),origPts:d,moved:!1},this.scheduleDraw()}else if(u?.kind==="midpoint"){let p=this.getItemPts(u.id,u.isPlane),d=p.map((f)=>[f[0],f[1]]),b=si(p,u.segIdx,u.pos,u.isPlane),y=u.isPlane&&u.segIdx+1>=p.length?b.length-1:Math.min(u.segIdx+1,b.length-1);this.selectedVertex={id:u.id,idx:y},this.patchLocalItem(u.id,u.isPlane,b),this.cb.onOptimisticPatch(u.id,{[u.isPlane?"outline":"path"]:b}),this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:y,pts:b,origPts:d,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let k=this.getCam(t,l,m);this.setCam(t,ti(k,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let y=this.getCam(t,l,m),[f,g]=Bt(y,r,o,l,m),E=[Math.round(f*1000)/1000,Math.round(g*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let C=this.drag.pts.map((k)=>[k[0],k[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:C}),this.scheduleDraw();return}let c=this.getCam(t,l,m),u=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o),p=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=this.hover?.hit.kind??"",b=u?u.id:"";if(this.hover=u?{layer:t,hit:u}:null,e.style.cursor=u?"pointer":"crosshair",p!==b||(u?.kind??"")!==d)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=(i)=>{let s=this.drag;if(!s||s.layer!==t)return;if(this.drag=null,this.downPos=null,i&&s.kind==="vertex"){let a=s.origPts.map((r)=>[r[0],r[1]]);this.patchLocalItem(s.id,s.isPlane,a),this.cb.onOptimisticPatch(s.id,{[s.isPlane?"outline":"path"]:a})}this.scheduleDraw()};e.addEventListener("pointercancel",()=>n(!0)),e.addEventListener("lostpointercapture",()=>n(!1)),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,m=i.clientY-o.top,c=Math.max(1,o.width),u=Math.max(1,o.height),p=this.getCam(t,c,u),d=It(s.bands,s.regions,t,s.selectedId,p,c,u,l,m);if(d&&(d.kind==="band"||d.kind==="region"))this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);else if(!d)this.cb.onSelect("")}}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),m=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ni(m,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=Qt(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(d,b)=>ze(a,d,b,n,i);e.fillStyle=oi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((d)=>d.length>=3);if(e.fillStyle=ms,o.length>0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let d of l){let b=d.outline??[];if(b.length<3)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ys(d.state||"proposed",y,f),E=ft(d.net||d.id,d.color||"");e.beginPath();for(let C=0;C0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),p=[];for(let d of u){for(let b of d.from??[])p.push(b);for(let b of d.to??[])p.push(b)}e.fillStyle=gs,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let d of ai(c,a,n,i,p))e.fillText(d.text,d.cx,d.cy);for(let d of u){let b=d.guides??[];if(b.length===0)continue;let y=s.selectedId===d.id||m?.id===d.id,f=vt(d.name||d.id,d.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[E,C]=r(g[0],g[1]),[k,A]=r(g[2],g[3]);e.moveTo(E,C),e.lineTo(k,A)}e.stroke()}for(let d of u){let b=d.path??[];if(b.length<2)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=vs(d.state||"proposed",y,f),E=vt(d.name||d.id,d.color||""),C=en(d.width??1.5,a.scale),k=()=>{e.beginPath();for(let N=0;N0){let N=ii(b);if(N){let[M,D]=r(N[0],N[1]),q=String(A),K=Math.max(16,q.length*6.5+8),H=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(M-K*0.5,D-7.5,K,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":E,e.strokeRect(M-K*0.5,D-7.5,K,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(q,M,D+0.5)}}}if(s.selectedId){let d=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let m=document.createElement("span");m.textContent=xe(r.label),o.appendChild(m);let c=this.getPanelData(r.id),u=Un(c);if(u){let p=document.createElement("span");p.className=`bp-mgmt-badge bp-tone-${u.tone}`,p.textContent=u.text,o.appendChild(p)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=h("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,s.appendChild(r)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}let a=this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&this.planCanvas.root.contains(document.activeElement);if(this.panelEl.replaceChildren(s),a)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=xe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),m.appendChild(c),e.appendChild(m)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=Wn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),l.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),l.appendChild(y)}else{let y=Vn(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,l.appendChild(f)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let p=[`${a.qty??r.length}×`,a.value??"",On(a.footprint??"")].filter(Boolean).join(" · "),d=document.createElement("span");d.className="bp-dim",d.textContent=p;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(d,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=xe(a.stock.class),u.appendChild(y)}o.append(l,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(p,d=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!Xt(b,o()))return;this.bomLastUndo=!d&&(y.changed??0)>0?{project:p.project,editId:b.editId,refs:p.refs.slice(),field:p.field,was:typeof y.was==="string"?y.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=d?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Xt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(c,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn",d.textContent="Undo",d.addEventListener("click",()=>{l(Zn(p),!0)}),m.appendChild(d)}if(t.append(i,r,m),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),a=(p)=>t.sources?.[p]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let p of i){let d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),d.textContent=s(p)+(a(p)?" · judged":""),d.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),r.appendChild(d)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let p=this.watchGen,d=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:d}).then(()=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(l,m),e.appendChild(r),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let u=_n(n,this.checksSource);if(u.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let p of u){let d=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${d}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(p.source)} · ${p.rule}`;let g=document.createElement("span");g.className=`bp-tone-${d}`,g.textContent=String(p.n),b.append(y,f,g),c.appendChild(b);for(let E of p.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let k=document.createElement("div");if(k.textContent=xe(E.title??""),C.appendChild(k),E.names||this.checksSelectedId===E.id){let A=document.createElement("div");A.className="bp-mgmt-row-sub";let N=document.createElement("span");if(N.className="bp-dim bp-mgmt-flex1",N.textContent=E.names??"",A.appendChild(N),this.checksSelectedId===E.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(D)=>{D.stopPropagation();let q={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:q.project,id:E.id}).then((K)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(q,H))return;if(K.text)this.cb.onSendText(K.text),this.checksStatus="Sent to agent",this.render()}).catch((K)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(q,H))return;this.checksStatus=K instanceof Error?K.message:"Could not send finding",this.render()})}),A.appendChild(M)}C.appendChild(A)}C.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),c.appendChild(C)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let m=i[l]??0,c=Yt(l),u=document.createElement("span");u.className=m>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",u.textContent=`${c.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(l,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],m=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${at(l[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let m=this.lifeSelectedKey===l.key,c=Yt(l.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let d=document.createElement("span");d.className="bp-mgmt-strong",d.textContent=Mt(l.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=l.mpn||l.key;let y=document.createElement("span");if(y.className=`bp-tone-${c.tone}`,y.textContent=c.label,p.append(d,b,y),typeof l.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(l.stock),p.appendChild(f)}if(u.appendChild(p),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((f)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(x,S)=>{let I=this.watchGen,V=this.project;this.planStatus="",this.cb.hub.rpc(x,{pro:V,...S}).catch((X)=>{if(I!==this.watchGen||V!==this.project)return;this.planOptimistic.clear(),this.planStatus=X instanceof Error?X.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let x=this.watchGen,S=this.project;this.cb.hub.rpc("plan.get",{pro:S,board:!0}).then((I)=>{let V=ri(I);if(x!==this.watchGen||S!==this.project||!V)return;this.planHydratedKey=i,this.planHydratedBoard=V.board??null,this.planHydratedDraw=V.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),l.setAttribute("data-testid","mgmt-plan-off"),l.setAttribute("aria-pressed",!a?"true":"false"),l.textContent=h("gpui.bots.recall.off","Off"),l.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,l),e.appendChild(s);for(let x of t.elsewhere??[]){let S=document.createElement("div");S.className="bp-plan-elsewhere";let I=document.createElement("span");I.className="bp-tone-warn bp-mgmt-flex1",I.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:x.name||x.rel||""}),S.appendChild(I),e.appendChild(S)}if(t.empty){let x=document.createElement("div");x.className="bp-mgmt-note";let S=document.createElement("div");S.className="bp-dim",S.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let I=document.createElement("div");return I.className="bp-mgmt-faint",I.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),x.append(S,I),e.appendChild(x),e}let m=t.awaiting??0,c=t.blocked??0,u=t.done??0,p=t.total??0,d=t.revision??0,b=zn(t),y=Jn(t),f=y.reduce((x,S)=>x+S.count,0),g=document.createElement("div");g.className="bp-plan-status";let E=document.createElement("div");E.className="bp-plan-status-top";let C=document.createElement("span");if(C.className=`bp-plan-status-badge tone-${b.tone}`,C.textContent=h(b.key,b.label),E.appendChild(C),d>0){let x=document.createElement("span");x.className="bp-dim",x.textContent=`v${d}`,E.appendChild(x)}let k=document.createElement("span");if(k.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":c>0?"bp-tone-bad":"bp-dim"),k.textContent=p>0?`${u}/${p} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),E.appendChild(k),!t.live){let x=document.createElement("span");x.className="bp-mgmt-pill",x.textContent=h("gpui.mgmt.plan.saved","saved plan"),E.appendChild(x)}if(g.appendChild(E),f>0){let x=document.createElement("div");x.className="bp-plan-segbar";for(let S of y){if(S.count<=0)continue;let I=document.createElement("div");I.className=`bp-plan-seg bp-tone-bg-${S.tone}`,I.style.flexGrow=String(S.count),x.appendChild(I)}g.appendChild(x)}e.appendChild(g);let A=document.createElement("div");if(A.className="bp-mgmt-head",m>0){let x=document.createElement("button");x.type="button",x.className="primary bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-approve-all"),x.textContent=h("gpui.mgmt.plan.all","Approve all"),x.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(x)}if(t.routing){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-stop"),x.textContent=h("gpui.mgmt.plan.stop","Stop routing"),x.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(x)}if(t.live&&u>0){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-verify"),x.textContent=h("gpui.mgmt.plan.verify","Verify"),x.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(x)}let N=document.createElement("span");N.className="bp-mgmt-flex1";let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.setAttribute("data-testid","mgmt-plan-hide"),M.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),M.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.append(N,M),e.appendChild(A);let D=Array.isArray(t.asks)?t.asks:[];if(D.length>0){let x=D.map((j)=>j.what||"").filter(Boolean).join(", "),S=D[0]?.note||"",I=document.createElement("div");I.className="bp-plan-elsewhere";let V=document.createElement("div");V.className="bp-plan-ask-col";let X=document.createElement("div");if(X.className="bp-tone-warn",X.textContent=x?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:x}):h("gpui.mgmt.plan.reqplain","Approval requested"),V.appendChild(X),S){let j=document.createElement("div");j.className="bp-dim",j.textContent=S,V.appendChild(j)}I.appendChild(V),e.appendChild(I)}if(this.planStatus){let x=document.createElement("div");x.className="bp-mgmt-note bp-plan-err bp-tone-bad";let S=document.createElement("span");S.className="bp-mgmt-flex1",S.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):xe(this.planStatus);let I=document.createElement("button");I.type="button",I.className="icon",I.textContent="×",I.title=h("common.close","Close"),I.addEventListener("click",()=>{this.planStatus="",this.render()}),x.append(S,I),e.appendChild(x)}if(t.keys_note){let x=document.createElement("div");x.className="bp-mgmt-note bp-dim";let S="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";x.textContent=t.keys_note===S?h("gpui.mgmt.plan.keysnote",S):xe(t.keys_note),e.appendChild(x)}let q=t.stackup_summary??"",K=Array.isArray(t.impedances)?t.impedances:[];if(q||K.length>0){let x=document.createElement("div");x.className="bp-plan-stackup";let S=document.createElement("button");S.type="button",S.className="bp-plan-stackup-head",S.setAttribute("data-testid","mgmt-plan-stackup-toggle"),S.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let I=document.createElement("span");I.className="bp-plan-chev",I.textContent=this.planStackupOpen?"▾":"▸";let V=document.createElement("span");if(V.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),S.append(I,V),S.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),x.appendChild(S),this.planStackupOpen){let X=document.createElement("div");if(X.className="bp-plan-stackup-body",X.setAttribute("data-testid","mgmt-plan-stackup-body"),q){let j=document.createElement("div");j.className="bp-dim",j.textContent=q,X.appendChild(j)}for(let j of K){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=`· ${j}`,X.appendChild(B)}x.appendChild(X)}e.appendChild(x)}let H=(x,S,I,V)=>{let X=document.createElement("button");return X.type="button",X.className="bp-mgmt-btn bp-plan-chip-btn"+(S?" active":""),X.setAttribute("data-testid",I),X.setAttribute("aria-pressed",S?"true":"false"),X.textContent=x,X.addEventListener("click",V),X},he=document.createElement("div");if(he.className="bp-plan-viewbar",he.append(H(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),H(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),H(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let x=document.createElement("span");x.className="bp-plan-sep";let S=document.createElement("span");S.className="bp-plan-sep";let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn bp-plan-mini-btn",I.setAttribute("data-testid","mgmt-plan-fit"),I.textContent=h("gpui.mgmt.plan.fit","Fit"),I.addEventListener("click",()=>this.planCanvas?.fitAll()),he.append(x,H(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),H(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),H(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),S,H(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),I)}let me=document.createElement("span");me.className="bp-mgmt-flex1";let ie=document.createElement("button");ie.type="button",ie.className="bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-expand"),ie.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),ie.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),he.append(me,ie),e.appendChild(he);let we=this.planHydratedKey===i&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},Se=this.planHydratedKey===i&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Te=(Se.bands??[]).map((x)=>{let S=this.planOptimistic.get(x.id);if(!S)return{...x};return{...x,...S,edited:!0,state:x.state==="proposed"?"edited":x.state}}),ge=(Se.regions??[]).map((x)=>{let S=this.planOptimistic.get(x.id);if(!S)return{...x};return{...x,...S,edited:!0,state:x.state==="proposed"?"edited":x.state}}),Be=[],T=(t.layers??[]).map((x)=>{let S=[];for(let I of x.items??[]){let V=this.planOptimistic.get(I.id);if(!V){S.push(I);continue}let X={...I,width:typeof V.width==="number"?V.width:I.width,locked:typeof V.locked==="boolean"?V.locked:I.locked,edited:!0,state:I.state==="proposed"?"edited":I.state};if(typeof V.layer==="string"&&V.layer!==x.layer)Be.push({target:V.layer,item:X});else S.push(X)}return{...x,items:S}});for(let x of Be){let S=T.find((I)=>I.layer===x.target);if(S)S.items=[...S.items??[],x.item]}let re=Rt(T,t.copper_layers),ee=this.planGridMode==="all"?re.map((x)=>x.layer):this.planGridMode==="single"?[this.planShownLayers.find((x)=>re.some((S)=>S.layer===x))??rt(re)[0]??re[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((x)=>re.some((S)=>S.layer===x))?this.planShownLayers.slice(0,2):rt(re);if(this.planViewMode!=="list"&&re.length>1){let x=document.createElement("div");x.className="bp-plan-layerbar";for(let S of re){let I=ee.includes(S.layer);x.appendChild(H(S.title||S.layer,I,`mgmt-plan-layerpill-${S.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"){if(!ee.includes(S.layer))this.planShownLayers=ee.length>=2?[ee[0],S.layer]:[...ee,S.layer]}else this.planGridMode="single",this.planShownLayers=[S.layer];this.render()}))}e.appendChild(x)}let Y=(x,S)=>{let I=this.planOptimistic.get(x)??{};if(this.planOptimistic.set(x,{...I,...S}),typeof S.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"&&!ee.includes(S.layer))this.planShownLayers=ee.length>=2?[ee[0],S.layer]:[...ee,S.layer]}let V={...S};if(Array.isArray(S.outline)&&Array.isArray(S.outline[0])&&typeof S.outline[0][0]==="number"){let j=ge.find((B)=>B.id===x);if(j?.holes&&j.holes.length>0)V.outline=[S.outline,...j.holes]}let X=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:x,fields:V}],...X!==void 0?{base:X}:{}})};if(this.planCommitFields=Y,this.planSelectedId){let x="",S=null;for(let I of T){let V=(I.items??[]).find((X)=>X.id===this.planSelectedId);if(V){x=I.layer,S=V;break}}if(S){let I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let V=document.createElement("div");V.className="bp-plan-ins-row";let X=document.createElement("span");X.className="bp-plan-ins-sw",X.style.background=S.kind==="corridor"?vt(S.name||S.id,S.color||""):ft(S.name||S.id,S.color||"");let j=document.createElement("span");j.className="bp-mgmt-strong",j.textContent=S.name||S.id;let B=document.createElement("span");if(B.className="bp-dim",B.textContent=x,V.append(X,j,B),S.edited||S.state==="edited"){let ae=document.createElement("span");ae.className="bp-plan-ins-pill warn",ae.textContent=h("gpui.mgmt.plan.edited","Edited"),V.appendChild(ae)}if(S.locked){let ae=document.createElement("span");ae.className="bp-plan-ins-pill",ae.textContent=h("gpui.mgmt.plan.locked","Locked"),V.appendChild(ae)}let je=document.createElement("span");je.className="bp-mgmt-flex1",V.appendChild(je);let ke=document.createElement("button");if(ke.type="button",ke.className="bp-mgmt-btn bp-plan-mini-btn",ke.setAttribute("data-testid","mgmt-plan-lock"),ke.textContent=S.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),ke.addEventListener("click",()=>Y(S.id,{locked:!S.locked})),V.appendChild(ke),S.state==="proposed"||S.state==="edited"){let ae=document.createElement("button");ae.type="button",ae.className="primary bp-mgmt-btn bp-plan-mini-btn",ae.textContent=h("android.hub.machines.approve","Approve"),ae.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!0}));let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.textContent=h("gpui.mgmt.plan.reject","Reject"),Ae.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!1})),V.append(ae,Ae)}let ce=document.createElement("button");ce.type="button",ce.className="bp-mgmt-btn bp-plan-mini-btn",ce.setAttribute("data-testid","mgmt-plan-note-toggle"),ce.textContent=h("gpui.mgmt.plan.addnote","Add note"),ce.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Pe=document.createElement("button");if(Pe.type="button",Pe.className="icon",Pe.textContent="×",Pe.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),V.append(ce,Pe),I.appendChild(V),!S.locked){let ae=document.createElement("div");if(ae.className="bp-plan-ins-row",S.kind==="corridor"){let de=typeof S.width==="number"?S.width:1.5,fe=document.createElement("span");fe.className="bp-dim",fe.textContent=h("gpui.mgmt.plan.width","Width");let ue=document.createElement("button");ue.type="button",ue.className="bp-mgmt-btn bp-plan-mini-btn",ue.setAttribute("data-testid","mgmt-plan-w-down"),ue.textContent="-",ue.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,de-0.25)*100)/100;Y(S.id,{width:Ue})});let Z=document.createElement("span");Z.className="bp-plan-ins-val",Z.textContent=`${de.toFixed(2)}mm`;let pe=document.createElement("button");pe.type="button",pe.className="bp-mgmt-btn bp-plan-mini-btn",pe.setAttribute("data-testid","mgmt-plan-w-up"),pe.textContent="+",pe.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,de+0.25)*100)/100;Y(S.id,{width:Ue})});let We=document.createElement("span");We.className="bp-plan-sep",ae.append(fe,ue,Z,pe,We)}let Ae=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((de)=>de.layer):T.map((de)=>de.layer);if(Ae.length>0){let de=document.createElement("span");de.className="bp-dim",de.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),ae.appendChild(de);for(let fe of Ae)ae.appendChild(H(fe,fe===x,`mgmt-plan-move-${fe}`,()=>{if(fe!==x)Y(S.id,{layer:fe})}))}I.appendChild(ae)}if(this.planNoteOpen){let ae=document.createElement("form");ae.className="bp-plan-note-form";let Ae=document.createElement("input");Ae.type="text",Ae.className="bp-plan-note-input",Ae.setAttribute("data-testid","mgmt-plan-note-input"),Ae.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let de=document.createElement("button");de.type="submit",de.className="primary bp-mgmt-btn bp-plan-mini-btn",de.setAttribute("data-testid","mgmt-plan-note-submit"),de.textContent=h("gpui.mgmt.plan.addnote","Add note"),ae.append(Ae,de),ae.addEventListener("submit",(fe)=>{fe.preventDefault();let ue=Ae.value.trim();if(!ue)return;Ae.value="",this.planNoteOpen=!1;let Z=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:S.id,text:ue}],...Z!==void 0?{base:Z}:{}})}),I.appendChild(ae)}if(this.planViewMode!=="list"&&!S.locked){let ae=document.createElement("div");ae.className="bp-plan-hint",ae.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(ae)}e.appendChild(I)}}let le=document.createElement("div");le.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),le.setAttribute("data-testid","mgmt-plan-rows");let F=h("gpui.mgmt.plan.done","done");for(let x of T){let S=x.items??[],I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let V=document.createElement("div");V.className="bp-mgmt-row-line";let X=document.createElement("span");X.className="bp-mgmt-strong",X.textContent=x.layer;let j=document.createElement("span");if(j.className="bp-dim bp-mgmt-flex1",j.textContent=`${x.role?`${x.role} · `:""}${x.done??0}/${S.length} ${F}`,V.append(X,j),x.status!=="approved"&&S.length>0){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=h("gpui.mgmt.plan.layer","Approve layer"),B.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!1})),V.append(B,je)}if(I.appendChild(V),x.stackup){let B=document.createElement("div");B.className="bp-plan-layer-stackup",B.textContent=x.stackup,I.appendChild(B)}le.appendChild(I);for(let B of S){if(this.planHideDone&&qn(B))continue;let je=this.planSelectedId===B.id,ke=document.createElement("div");ke.className="bp-mgmt-row bp-plan-row"+(je?" active":""),ke.setAttribute("data-testid",`mgmt-plan-row-${B.id}`);let ce=document.createElement("div");ce.className="bp-mgmt-row-line";let Pe=document.createElement("span");Pe.className=`bp-plan-swatch bp-plan-st-${B.state||"proposed"}`,Pe.style.setProperty("--swatch-color",B.color||"#8a8a8a");let ae=document.createElement("span");ae.className="bp-mgmt-flex1"+(B.state==="blocked"||B.state==="failed"?" bp-tone-bad":B.state==="edited"?" bp-tone-warn":B.state==="rejected"||B.state==="routed"||B.state==="verified"?" bp-dim":""),ae.textContent=`${B.name||B.id}${B.locked?" \uD83D\uDD12":""}`;let Ae=[];if(B.kind==="plane"){if(B.reference)Ae.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:B.reference}))}else{let ue=B.nets??0;Ae.push(ue===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:ue}))}if(typeof B.width==="number"&&Number.isFinite(B.width))Ae.push(`${B.width.toFixed(2)}mm`);if(B.impedance)Ae.push(B.impedance);let de=Ae.join(" · "),fe=document.createElement("span");if(fe.className="bp-plan-mark "+(B.state==="blocked"||B.state==="failed"?"bp-tone-bad":B.state==="verified"||B.state==="routed"?"bp-tone-ok":B.state==="approved"?"bp-tone-accent":"bp-dim"),fe.textContent=Kn(B),ce.append(Pe,ae,fe),B.state==="proposed"||B.state==="edited"){let ue=document.createElement("button");ue.type="button",ue.className="bp-mgmt-btn",ue.textContent="✓",ue.title=h("gpui.mgmt.plan.layer","Approve layer"),ue.addEventListener("click",(pe)=>{pe.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!0})});let Z=document.createElement("button");Z.type="button",Z.className="bp-mgmt-btn",Z.textContent="✗",Z.title=h("gpui.mgmt.plan.reject","Reject"),Z.addEventListener("click",(pe)=>{pe.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!1})}),ce.append(ue,Z)}if(ke.appendChild(ce),de){let ue=document.createElement("div");ue.className="bp-mgmt-row-sub bp-plan-detail bp-dim",ue.textContent=de,ke.appendChild(ue)}if(B.state==="routing"&&typeof B.total==="number"&&B.total>0){let ue=document.createElement("div");ue.className="bp-plan-microbar";let Z=document.createElement("div");Z.className="bp-plan-microbar-fill";let pe=Math.max(0,Math.min(100,Math.round((B.routed??0)/B.total*100)));Z.style.width=`${pe}%`,ue.appendChild(Z),ke.appendChild(ue)}if(B.problem_text){let ue=document.createElement("div");ue.className="bp-plan-problem",ue.textContent=B.problem_text,ke.appendChild(ue)}ke.addEventListener("click",()=>{this.planSelectedId=B.id,n("plan.focus",{id:B.id}),this.render()}),le.appendChild(ke)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new tn({onSelect:(V)=>{if(this.planSelectedId=V,!V)this.planNoteOpen=!1;this.render()},onFocusItem:(V)=>{n("plan.focus",{id:V})},onOptimisticPatch:(V,X)=>{let j=this.planOptimistic.get(V)??{};this.planOptimistic.set(V,{...j,...X})},onCommitFields:(V,X)=>{(this.planCommitFields??Y)(V,X)},onApproveLayer:(V,X)=>{n("plan.approve",{layer:V,ids:[],approve:X})},onQuickApprove:(V,X)=>{n("plan.approve",{layer:"",ids:V,approve:X})}});let x=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,S=this.planExpanded||this.panelEl.clientWidth>=540||x;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:ee,selectedId:this.planSelectedId,board:we,bands:Te,regions:ge,layers:re,copperLayers:t.copper_layers},S);let I=document.createElement("div");I.className="bp-plan-canvas-scroll",I.appendChild(this.planCanvas.root),e.appendChild(I)}if(this.planViewMode!=="canvas")e.appendChild(le);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let x=document.createElement("div");x.className="bp-plan-footer",x.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(x)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,C={})=>{let k=this.watchGen,A=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:A,action:E,...C}).catch((N)=>{if(k!==this.watchGen||A!==this.project)return;this.fabStatus=N instanceof Error?N.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Xn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span"),p=(l?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),u.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(u),l?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(E)}if(!l?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),c.appendChild(E)}if(l?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(E)}m.appendChild(c),o.appendChild(m);let d=Yn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(d.button?"bp-tone-warn":"bp-dim"),f.textContent=d.text,y.appendChild(f),d.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=d.button,E.addEventListener("click",()=>n("drc")),y.appendChild(E)}b.appendChild(y),o.appendChild(b);for(let E of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=E,o.appendChild(C)}for(let E of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.fab.apply","Apply"),N.addEventListener("click",()=>n("apply",{key:E.key})),k.append(A,N),C.appendChild(k),o.appendChild(C)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let k=t.stackup.by==="proposed",A=document.createElement("span");if(A.className="bp-mgmt-flex1 "+(k?"bp-tone-warn":"bp-dim"),A.textContent=`${k?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(A),k){let N=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:N})),C.appendChild(M)}E.appendChild(C),o.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let k=document.createElement("span");k.className="bp-mgmt-flex1 bp-tone-warn",k.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=h("gpui.mgmt.fab.seen","Seen"),A.addEventListener("click",()=>n("seen")),C.append(k,A),E.appendChild(C);for(let N of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=N,E.appendChild(M)}o.appendChild(E)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=h("gpui.mgmt.fab.limit","Limit");let k=document.createElement("span");k.className="bp-mgmt-col",k.textContent=h("gpui.mgmt.fab.free","Base price");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=h("gpui.mgmt.fab.extra","Costs more");let N=document.createElement("span");N.className="bp-mgmt-col bp-mgmt-col-read",N.textContent=h("gpui.mgmt.fab.readcol","Read"),E.append(C,k,A,N),o.appendChild(E);for(let D of g){let q=document.createElement("div");q.className="bp-mgmt-row";let K=document.createElement("div");K.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(D.changed?" bp-tone-warn":D.inherited?" bp-dim":""),H.textContent=`${D.changed?"• ":""}${D.label??""}`;let he=document.createElement("span");he.className="bp-mgmt-col",he.textContent=D.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=D.extra?.text||"—";let ie=D.free&&typeof D.free==="object"?D.free:D.extra,we=ie?.fetched??"",Se=Boolean(we)&&ie?.confidence!=="published",Te=we?Se?`${we}*`:we:"—",ge=ie?.source??"",Be;if(ge.startsWith("https://")&&we){let T=document.createElement("a");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",T.href=ge,T.target="_blank",T.rel="noopener noreferrer",T.textContent=Te,Be=T}else{let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",T.textContent=Te,Be=T}K.append(H,he,me,Be),q.appendChild(K),o.appendChild(q)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Es={trs:(e)=>e,t:(e,t)=>t},xs=new Set(["/settle"]);function di(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function mi(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ui(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function hi(e,t=Es){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=xs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:m}=pi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:m,dotClass:mi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function bi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let b of i)p.set(b.id,b.title||b.id);let d=new Set;for(let b of l)if(b.action.type==="thread")d.add(b.action.id);for(let b of n.threads){if(!b.id||d.has(b.id))continue;d.add(b.id);let{urgency:y,want:f}=pi(b);l.push({label:b.title||"Untitled thread",place:b.project?p.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:mi(b),action:{type:"thread",id:b.id}})}}let m=[];for(let p=0;p0)m.push({score:f,index:p,item:d})}m.sort((p,d)=>{if(o){let f=(d.item.urgency??0)-(p.item.urgency??0);if(f!==0)return f}if(d.score!==p.score)return d.score-p.score;let b=p.item.kind==="thread"?0:1,y=d.item.kind==="thread"?0:1;if(b!==y)return b-y;return p.index-d.index});let c=new Set,u=[];for(let p of m){let d=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(c.has(d))continue;if(c.add(d),u.push(p.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=hi(t,{t:h,trs:xe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=bi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,p)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(p,d),m.appendChild(b),d{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var ks=new Set(["resume","raise","retry","move","signin"]);function vi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function jt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(ks.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function yi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class rn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let c=document.createElement("div");c.className="bp-set-head",c.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";d.textContent=b,p.appendChild(d);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(p.appendChild(y),u.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(c,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let l=document.createElement("div");l.className="bp-set-head",l.textContent="Paired devices",o.appendChild(l);try{let m=await this.cb.onLoadDevices();if(m.length===0){let c=document.createElement("div");c.className="bp-dim",c.textContent="No devices listed.",o.appendChild(c)}else for(let c of m){let u=document.createElement("div");u.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div");if(d.textContent=c.title||c.head||"",p.appendChild(d),c.text||c.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=c.text||c.detail||"",p.appendChild(b)}if(u.appendChild(p),c.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of c.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let c=document.createElement("div");c.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";c.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(c)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function Ce(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=Ce("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function on(e){return Ce("pre","bp-context-code",e)}function Ss(e){return Ce("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,xe(e))}function Ht(e,t){let n=Ce("div","bp-context-row");return n.append(Ce("strong",void 0,e),Ss(t)),n}class ln{fetchContext;dialog=Ce("dialog","bp-context");title=Ce("h2");cwd=Ce("div","bp-context-path");tabs=Ce("div","bp-context-tabs");body=Ce("div","bp-context-body");notice=Ce("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ce("div","bp-context-head"),i=Ce("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ce("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ce("details","bp-context-card"),i=Ce("summary");if(i.append(Ht(t.path,t.status),Ce("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,on(t.preview)),t.note)n.append(Ce("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ce("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ce("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ce("h3",void 0,i),on(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ce("h3",void 0,xe(t)));for(let i of n){let s=Ce("article","bp-context-card");s.append(Ht(i.name,i.status),Ce("p",void 0,i.description),Ce("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ce("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ce("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ce("article","bp-context-card");n.append(Ht(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Ht(s.name,s.status),on(a)),s.cwd)n.append(Ce("small","bp-context-path",s.cwd))}if(t.error)n.append(Ce("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ce("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var wi="http://www.w3.org/2000/svg";function Ei(){let e=document.createElementNS(wi,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(wi,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Ls(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function xi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class cn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=h("thread.new","New thread"),l.setAttribute("aria-label",h("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${Ls(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?vi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,l.appendChild(m);for(let u of r.actions){if(!jt(u,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=u.label,p.setAttribute("data-testid",`need-${u.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(d)=>{d.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(p)}o.append(n,l);let c=this.needErr.get(e.id);if(c){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=c,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let l=document.createElement("section");l.className="bp-side-section",l.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),l.appendChild(m);for(let c of o)l.appendChild(this.renderSectionThreadRow(c,!1));e.appendChild(l);continue}if(r.kind==="projects"){let o=r.rows.filter((c)=>{if(!t)return!0;if((c.title||c.id).toLowerCase().includes(t))return!0;if((c.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((c.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),l=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!l&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),l){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,p=r.open?"▾":"▸";if(c.textContent=`${r.title.toUpperCase()} (${u}) ${p}`,r.hint)c.title=r.hint;c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(c)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!l||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let c=document.createElement("div");c.className="bp-side-empty",c.textContent="No projects yet.",m.appendChild(c)}for(let c of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(c.off?" bp-dim":""),u.setAttribute("data-project-id",c.id),c.nav||c.key)u.setAttribute("data-project-key",c.nav||c.key||"");let p=document.createElement("div");p.className="bp-proj-head";let d=document.createElement("button");d.type="button",d.className="bp-proj-toggle";let b=Ei();if(c.css)b.style.color=c.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=c.title||c.id,d.append(b,y),c.fold==="project-fold"&&c.nav)d.addEventListener("click",()=>this.cb.onToggleProjectFold?.(c.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${c.id}`),c.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(c.id)}),p.append(d,f),u.appendChild(p),!c.folded||Boolean(t)){let g=Boolean(t)&&(c.title||c.id).toLowerCase().includes(t);for(let E of c.swarms??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(E,!0))}for(let E of c.threads??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(E,!0))}if(s&&s.project===c.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:xi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!t,m=Ei();if(i.css)m.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(m,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!l)for(let p of s)a.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:xi(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let c of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(c.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",c.color)p.style.backgroundColor=c.color;let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`@${c.name}`,u.append(p,d),u.addEventListener("click",()=>this.cb.onSelectBot(c)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let l=document.createElement("span");l.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(l,m),r.appendChild(o);for(let c of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${c.name}`,u.appendChild(p),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function As(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ps(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/m:0));s[a]=c<0?c*32768:c*32767}return s}class dn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?As(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Ps(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var Ci=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ki=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Si=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Li=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ns=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ms=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Ts=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class pn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,p},r=(u)=>{let p=0,d=0,b=0;for(let y=1;y<=u.maxBits;y++){p|=a(1);let f=u.counts[y];if(p-f{let p=l+u;if(p>t)throw Error("inflated frame exceeds limit");if(p<=o.length)return;let d=o.length;while(d{m(1),o[l++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),p=a(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let d=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(d^65535)!==b)throw Error("invalid stored block length");if(n+d>e.length)throw Error("truncated stored payload");m(d);for(let y=0;y=e.length)break}else if(p===1||p===2){let d=Ms,b=Ts;if(p===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,E=new Uint8Array(19);for(let M=0;Mk)throw Error("code length overflow");for(let K=0;Kk)throw Error("code length overflow");N+=D}else if(M===18){let D=a(7)+11;if(N+D>k)throw Error("code length overflow");N+=D}else throw Error("invalid code length symbol")}d=Et(A,y),b=Et(A.subarray(y),f)}while(!0){let y=r(d);if(y<256)c(y);else if(y===256)break;else{let f=y-257;if(f>=Ci.length)throw Error("invalid length symbol");let g=Ci[f]+(ki[f]?a(ki[f]):0),E=r(b);if(E>=Si.length)throw Error("invalid distance symbol");let C=Si[E]+(Li[E]?a(Li[E]):0);m(g);let k=this.winPos-C&32767;for(let A=0;A{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new pn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(l))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Bs=new TextDecoder;function Ai(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Pi(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,m=i(o&31);if(m===null)return null;switch(l){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let c=e.subarray(t,t+m);return t+=m,c}case 3:{if(t+m>e.length)return null;let c=Bs.decode(e.subarray(t,t+m));return t+=m,c}case 4:{if(m>e.length)return null;let c=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Mi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new Ni(m),u=[],p=[],d=0,b=0;while(c.more()){let y=c.nextU32(),f=u.length,g=1/0,E=1/0,C=-1/0,k=-1/0;if(a===2)d=d+c.nextI32()|0,b=b+c.nextI32()|0,u.push(d,b),g=C=d,E=k=b;else{let N=Math.min(c.nextU32(),1048576);for(let M=0;MC)C=d;if(bk)k=b}}let A=(u.length-f)/2;if(A>0){let N=a===2||A===1?2:a===0?0:1,M=a===0?0:o;p.push({info:y,x0:g-M,y0:E-M,x1:C+M,y1:k+M,at:f,n:A,kind:N})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(u),pieces:p}}function Ti(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Bi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,c=(t-l)/r;if(m<0||m>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var Ii=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Ri(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class un{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function ji(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,m=-1,c=null,u=new un,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let d=document.createElement("div");d.className="bp-pane-bar bp-browser-nav";function b(Y,le,F){let x=document.createElement("button");if(x.type="button",x.className="bp-v-btn",x.textContent=Y,x.setAttribute("data-testid",le),F)x.title=F;return x}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let k=b("Go","browser-go","Navigate");k.type="submit",E.append(C,k);let A=b("Take over","browser-takeover");A.classList.add("is-primary"),d.append(y,f,g,E,A);let N=document.createElement("div");N.className="bp-browser-drive-bar",N.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let D=document.createElement("input");D.type="text",D.className="bp-browser-input",D.placeholder="Type text or press Enter/Tab/Arrows…",D.autocomplete="off",D.spellcheck=!1,D.setAttribute("data-testid","browser-keys");let q=b("Send","browser-type-send");M.append(D,q);let K=document.createElement("div");K.className="bp-browser-quick-keys";for(let[Y,le]of Ii){let F=b(Y,`browser-key-${le}`);F.addEventListener("click",()=>ge("press",{key:le})),K.append(F)}N.append(M,K);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let he=document.createElement("div");he.className="bp-browser-stage",he.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",he.append(me,ie);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,p.append(d,N,H,he,we),e.replaceChildren(p);function Se(Y){H.textContent=Y,H.hidden=!Y}function Te(){N.hidden=!s,we.hidden=!s,A.textContent=s?"Hand back":"Take over",A.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),A.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function ge(Y,le={},F){u.enqueue(async()=>{if(!i)return;Se("");try{if(await t.hub.rpc("browser",{thread:n,op:Y,...le}),!i)return;F?.(),re()}catch(x){if(!i)return;Se(x instanceof Error?x.message:String(x))}})}function Be(Y){ge("toolbar",{command:Y},()=>{s=!0,Te()})}y.addEventListener("click",()=>Be("back")),f.addEventListener("click",()=>Be("forward")),g.addEventListener("click",()=>Be("reload")),E.addEventListener("submit",(Y)=>{Y.preventDefault();let le=Ri(C.value);if(!le)return;if(C.value=le,!s)ge("takeover",{},()=>{s=!0,Te()});ge("navigate",{url:le},()=>{s=!0,Te()})}),A.addEventListener("click",()=>{if(s)ge("handback",{},()=>{s=!1,Te()});else ge("takeover",{},()=>{s=!0,Te(),D.focus()})});function T(){let Y=D.value;if(!Y)return;D.value="",ge("type",{text:Y})}q.addEventListener("click",T),D.addEventListener("keydown",(Y)=>{if(!s)return;if(Y.key==="Enter"){if(Y.preventDefault(),D.value)T();ge("press",{key:"Enter"});return}if(Y.key==="Tab"||Y.key==="Escape"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="ArrowLeft"||Y.key==="ArrowRight"||Y.key==="Backspace"&&D.value==="")Y.preventDefault(),ge("press",{key:Y.key})}),me.addEventListener("click",(Y)=>{if(!s||!a)return;let le=me.getBoundingClientRect(),F=Bi(Y.clientX,Y.clientY,{left:le.left,top:le.top,width:le.width,height:le.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!F)return;ge("click",F)}),me.addEventListener("wheel",(Y)=>{if(!s||!a)return;Y.preventDefault();let le=Math.round(Y.deltaX),F=Math.round(Y.deltaY);if(le===0&&F===0)return;ge("scroll",{dx:le,dy:F})},{passive:!1});async function re(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let Y=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(Y.ok){let le=await Y.blob();if(!i)return;let F=URL.createObjectURL(le),x=r;if(r=F,me.src=F,me.hidden=!1,ie.hidden=!0,a=!0,x)URL.revokeObjectURL(x)}else if(!a)me.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)me.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ee=t.hub.onFrame((Y)=>{if(!i)return;if(Y.t==="shot"&&Y.bot===n){if(typeof Y.n==="number"){if(Y.n===m)return;m=Y.n}re()}});return re(),{destroy(){if(i=!1,ee(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function W(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Dt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Di(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Rs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Hi(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function js(e){let t=Di(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Fi(e,t,n,i){let s=!0,a="",r="",o=W("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=W("div","bp-pane-bar"),m=W("div","bp-files-crumbs"),c=W("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void f(a)),l.append(m,c);let u=W("div","bp-files-split"),p=W("div","bp-files-list");p.setAttribute("data-testid","files-list");let d=W("div","bp-files-preview");d.setAttribute("data-testid","files-preview"),d.append(W("div","bp-pane-empty","Select a file to preview")),u.append(p,d),o.append(l,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=W("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let E=a.split("/").filter(Boolean),C="";for(let k of E){C=C?`${C}/${k}`:k;let A=C;m.append(W("span","bp-vh-sep","/"));let N=W("button","bp-crumb-btn",k);N.type="button",N.addEventListener("click",()=>void f(A)),m.append(N)}}async function y(g,E,C){r=g,d.replaceChildren();let k=W("div","bp-files-prev-head");k.append(W("span","bp-files-prev-name",g));let A=W("div","bp-files-prev-acts"),N=js(E);if(N){let K=W("button","bp-v-btn is-primary",`Open in ${N}`);K.type="button",K.setAttribute("data-testid","files-open-viewer"),K.addEventListener("click",()=>i(N,g)),A.append(K)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,D=W("a","bp-v-btn","Download");D.href=M,D.download=E,A.append(D),k.append(A),d.append(k);let q=Di(E);if(Rs(q)){let K=W("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=E,H.src=M,K.append(H),d.append(K);return}if(C>524288&&!Hi(q)){d.append(W("div","bp-pane-empty",`Binary file (${Dt(C)}). Use Download to save.`));return}if(Hi(q)||C<=65536){let K=W("div","bp-pane-empty","Loading…");d.append(K);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||r!==g)return;if(!H.ok){K.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){K.remove();let ee=document.createElement("img");ee.className="bp-files-img",ee.alt=E,ee.src=M,d.append(ee);return}let me=262144,ie=[],we=0,Se=!1;if(H.body){let ee=H.body.getReader();try{while(!0){let{done:Y,value:le}=await ee.read();if(Y||!le)break;if(we+le.byteLength>me){let F=me-we;if(F>0)ie.push(le.subarray(0,F)),we+=F;Se=!0,await ee.cancel();break}ie.push(le),we+=le.byteLength}}finally{ee.releaseLock()}}if(!s||r!==g)return;let Te=new Uint8Array(we),ge=0;for(let ee of ie)Te.set(ee,ge),ge+=ee.byteLength;let Be=!1;for(let ee=0;eek.dir===A.dir?k.name.localeCompare(A.name):k.dir?-1:1),p.replaceChildren(),g){let k=W("button","bp-file-row is-dir");k.type="button",k.append(W("span","bp-file-icon","↰"),W("span","bp-file-name",".."));let A=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";k.addEventListener("click",()=>void f(A)),p.append(k)}if(C.length===0){p.append(W("div","bp-pane-empty","Empty folder"));return}for(let k of C){let A=g?`${g}/${k.name}`:k.name,N=W("button","bp-file-row"+(k.dir?" is-dir":"")+(A===r?" is-sel":""));N.type="button",N.setAttribute("data-testid",`file-row-${k.name}`),N.append(W("span","bp-file-icon",k.dir?"▸":"·"),W("span","bp-file-name",k.name),W("span","bp-file-size",k.dir?"":Dt(k.size))),N.addEventListener("click",()=>{if(k.dir)f(A);else p.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),N.classList.add("is-sel"),y(A,k.name,k.size)}),p.append(N)}}catch(E){if(!s)return;p.replaceChildren(W("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return f(""),{destroy(){s=!1}}}function $i(e,t,n){let i=!0,s=W("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=W("div","bp-pane-bar"),r=W("span","bp-diff-summary","Loading diff…"),o=W("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let l=W("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(W("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof c?.diff==="string"?c.diff:"";if(!u.trim()){r.textContent="Clean working tree",l.append(W("div","bp-pane-empty","No uncommitted changes."));return}let p=u.split(` +`),d=0,b=0,y=0,f=document.createDocumentFragment(),g=W("div","bp-diff-file");for(let E of p){if(E.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=W("div","bp-diff-file"),d++;let C=E.match(/ b\/(.+)$/);g.append(W("div","bp-diff-file-head",C?C[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))g.append(W("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))g.append(W("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))b++,g.append(W("div","bp-diff-line is-add",E));else if(E.startsWith("-"))y++,g.append(W("div","bp-diff-line is-del",E));else g.append(W("div","bp-diff-line",E))}if(g.childNodes.length>0)f.append(g);r.textContent=`${d||1} file${d===1?"":"s"} · +${b} -${y}`,l.append(f)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(W("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return m(),{destroy(){i=!1}}}function Gi(e,t,n){let i=!0,s="checks",a=W("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=W("div","bp-pane-bar"),o=W("div","bp-review-tabs"),l=W("button","bp-v-btn is-on","Checks"),m=W("button","bp-v-btn","BOM"),c=W("button","bp-v-btn","Comments");l.type=m.type=c.type="button",o.append(l,m,c);let u=W("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void y()),r.append(o,u);let p=W("div","bp-review-body");p.setAttribute("data-testid","review-body"),a.append(r,p),e.replaceChildren(a);function d(f){s=f,l.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),y()}l.addEventListener("click",()=>d("checks")),m.addEventListener("click",()=>d("bom")),c.addEventListener("click",()=>d("comments"));function b(f){let g=W("div","bp-review-md"),E=f.split(` +`),C=0;while(C{M.preventDefault();let D=A.value.trim();if(!D)return;N.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:D}).then(()=>{A.value="",N.disabled=!1,y()},()=>{N.disabled=!1})}),p.append(k),C.length===0){p.append(W("div","bp-pane-empty","No review comments yet."));return}for(let M of C){let D=W("div","bp-review-comment"+(M.resolved?" is-resolved":"")),q=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");D.append(W("div","bp-review-comment-meta",q),W("div","bp-review-comment-text",M.text)),p.append(D)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(p.replaceChildren(),g.line||g.gate){let E=W("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));p.append(E)}if(g.err)p.append(W("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let E=W("div","bp-review-tasks");g.tasks.forEach((C,k)=>{let A=W("label","bp-review-task"),N=document.createElement("input");N.type="checkbox",N.checked=!!(C.done??C.checked);let M=typeof C.index==="number"?C.index:k;N.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void y(),()=>{})}),A.append(N,W("span",void 0,C.text||C.label||`Item ${k+1}`)),E.append(A)}),p.append(E)}if(g.md&&g.md.trim())p.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))p.append(W("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;p.replaceChildren(W("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function Ui(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class hn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,m=n*0.5,c=this.scale,u=this.cx,p=this.cy,d=u-l/c,b=u+l/c,y=p-m/c,f=p+m/c,{off:g,dim:E,lift:C}=this.masks,k=[],A=[];for(let M=0;M>>D&1)===1)continue;if(D===C)A.push(M);else k.push(M)}let N=k.concat(A);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>q.layer&1)===1,H=q.alpha*(K?0.25:1);if(H<=0.01)continue;this.drawChunk(r,q,H,d,y,b,f,u,p,c,l,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let D=0;Da||f.y1r)continue;if(f.n<3)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+u;e.moveTo(g,E);for(let C=1;C0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=d,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let E=(p[g.at]-o)*m+c,C=(p[g.at+1]-l)*m+u;e.moveTo(E+b,C),e.arc(E,C,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=d,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+u;if(f.n===1)e.moveTo(g,E),e.lineTo(g+0.01,E);else{e.moveTo(g,E);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,m,c,u,p){let d=t.pts,b=Ui(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(d[f.at]-l)*c+u,E=(d[f.at+1]-m)*c+p;if(f.kind===2){let C=Math.max(1.5,t.r*c);e.fillStyle=b,e.beginPath(),e.arc(g,E,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,E);for(let C=1;C=0;c--){let u=n.chunks[c];if(u.layer<32&&(m>>>u.layer&1)===1)continue;for(let p=0;pd.x1+r||ad.y1+r)continue;let b=(d.x1-d.x0+1)*(d.y1-d.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,u=s-l.left-l.width*0.5,p=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-p/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Oi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Vi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function bn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),l=i.replace(/\\/g,"/");if(l.startsWith("/")||/^[A-Za-z]:\//.test(l))return o===l;return o===l||o.endsWith(`/${l}`)}class gn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Hs=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,js=`#version 300 es +`,Ds=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,Hs=`#version 300 es +`,Fs=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,Ds=`#version 300 es +`,$s=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function _e(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Fs=[_e(77),_e(83),_e(94)],$s=[_e(53),_e(58),_e(67)],Gs=[_e(245),_e(246),_e(248)],Us=[_e(225),_e(228),_e(233)];function Oi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function Vi(e,t,n){let i=Oi(e,e.VERTEX_SHADER,t),s=Oi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Os(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Vs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Wi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function _i(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function gn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class fn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=Vi(n,Rs,js),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=Vi(n,Hs,Ds),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Pi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,c=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,l=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,p=0,b=0;for(let g=0;g>>24&255,S=1-k/255,L=(w>>>16&255)/255,M=(w>>>8&255)/255,B=(w&255)/255,H=g*9;if(k===0&&o&&c&&m){let W=p*9;for(let j=0;j<9;j++)o[W+j]=e[H+j],c[W+j]=t[H+j];let _=p*12;for(let j=0;j<3;j++)m[_+j*4]=L,m[_+j*4+1]=M,m[_+j*4+2]=B,m[_+j*4+3]=1;p++}else if(l&&u&&d){let W=b*9;for(let j=0;j<9;j++)l[W+j]=e[H+j],u[W+j]=t[H+j];let _=b*12;for(let j=0;j<3;j++)d[_+j*4]=L,d[_+j*4+1]=M,d[_+j*4+2]=B,d[_+j*4+3]=S;b++}}let y=o&&c&&m?this.createSubBatch(o,c,m,a*3):null,f=l&&u&&d?this.createSubBatch(l,u,d,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Ui(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Gs:Fs,_=this.lightTheme?Us:$s;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),m=Math.sin(this.pitch),l=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*u,this.target[1]-this.dist*c*l,this.target[2]+this.dist*m],p=Wi([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),b=Math.abs(p[2])>0.99?[0,1,0]:[0,0,1],y=Wi(_i(p,b)),f=_i(y,p),g=new Float32Array([y[0],f[0],-p[0],0,y[1],f[1],-p[1],0,y[2],f[2],-p[2],0,-gn(y,d),-gn(f,d),gn(p,d),1]),w=Math.max(0.05,this.dist*0.01),k=Math.max(this.dist*10,this.radius*20),S=Vs(35*Math.PI/180,r/o,w,k),L=Os(S,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,p[0],p[1],p[2]);let M=!1,B=[],H=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,j=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(j<1){if(M=!0,j>0)H.push({batch:W,fade:j})}else B.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of B)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of B)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of H)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),M}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var qi=64,Ws=16777216;function _s(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ki(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function vn(e){return e==="board"||e==="schematic"||e==="gerbers"}function qs(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function yn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let p=document.createElement("div");p.className="bp-v-layers",p.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,l.append(u,d,p,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,c,m,l,y);let f="",g="",w=0,k=!1,S=new Set,L=[],M=0,B=new Map,H=new Map,W={},_=[],j="",me="",ce=!1,ie=!1,ye=0,ke=!1,Ne=0,ge="",Me=0,T=null,re=null,se=null,J=null,de=null,x=new bn,C=0,I=!1,D="",K="",le="",N="";document.addEventListener("click",(R)=>{if(!I)return;if(R.target instanceof Node&&y.contains(R.target))return;I=!1,pe()}),document.addEventListener("keydown",(R)=>{if(I&&R.key==="Escape")I=!1,pe()});function Y(){if(C)window.clearInterval(C),C=0;x.playing=!1}function Ie(){let R=g==="3d"||g==="mech";if(c.hidden=!R,!R)return;if(c.childElementCount>0)return;for(let U of Gi){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=U.label,G.setAttribute("data-testid",`solid-view-${U.id}`),G.addEventListener("click",()=>{se?.setView(U.id)}),c.append(G)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent="Snap view",F.setAttribute("data-testid","solid-snap"),F.addEventListener("click",()=>{if(!se)return;se.snapPng().then((U)=>{if(!U)return;let G=URL.createObjectURL(U),q=document.createElement("a");q.href=G;let X=(je()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");q.download=`${X}-snap.png`,q.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),c.append(F)}async function Ae(){if(!f||g!=="board"&&g!=="schematic")return;pe();let R=x.compareRequest();if(!R){D="",K="",le="",N="",await $e(!1);return}let F=`${g}|${R.commit}|${R.bits}|${me}`;if(F===N&&S.size>0){te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1);return}let U=++w;S.clear(),B.clear(),Ye(),k=!0,D="",K=R.commit,le="",N=F;try{let G=me||(g==="schematic"?W.sch:W.pcb)||"";if(!G){let fe=await t.hub.rpc("viewer.files",{thread:f});if(U!==w)return;W=fe||{},Z(),G=(g==="schematic"?W.sch:W.pcb)||""}if(!G)throw Error(`Unable to resolve ${g} file path for compare`);let q=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:R.commit,bits:R.bits,...me?{path:me}:{}});if(U!==w)return;let X=typeof q?.root==="string"?q.root:"",Q=g==="schematic"?"1":"0";D=X?`${Q}|${X}|diff -`:`${Q}|`,K=R.commit,le=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!X?G:`${X.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,k=!1;let he=L;Ye();for(let fe of he)if(fe.kind==="bin")Ge(fe.buf);else Oe(fe.key,fe.none,fe.retryable);te(x.highlightEdits?`Comparing against ${x.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${x.activeRef()?.label||R.commit.slice(0,7)}`,!1)}catch(G){if(U!==w)return;k=!1,D="",K="",le="",N="",Ye(),te(G instanceof Error?G.message:String(G),!0)}}function pe(){let R=g==="board"||g==="schematic";if(y.hidden=!R,!R)return;let F=document.createElement("div");F.className="bp-history-group";let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="<",U.title="Older snapshot",U.disabled=x.refs.length===0||x.index>=x.refs.length-1,U.setAttribute("data-testid","history-prev"),U.addEventListener("click",()=>{if(Y(),x.step(1))Ae()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(x.playing?" is-on":""),G.textContent=x.playing?"⏸":"▶",G.title=x.playing?"Pause history":"Play history",G.disabled=x.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(x.playing){Y(),pe();return}if(x.refs.length===0)return;if(x.playing=!0,x.isLive())x.index=x.refs.length-1,Ae();else pe();C=window.setInterval(()=>{if(!x.playing||g!=="board"&&g!=="schematic"){Y(),pe();return}if(x.step(-1))Ae();else Y(),pe()},1400)});let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent=">",q.title="Newer snapshot",q.disabled=x.isLive(),q.setAttribute("data-testid","history-next"),q.addEventListener("click",()=>{if(Y(),x.step(-1))Ae()});let X=document.createElement("button");X.type="button",X.className="bp-v-btn"+(x.isLive()?" is-on":""),X.textContent="Live",X.setAttribute("data-testid","history-live"),X.addEventListener("click",()=>{if(Y(),x.goLive())te("",!1),Ae()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let he=x.activeRef();Q.textContent=he?he.label||he.commit.slice(0,7):x.refs.length>0?`Live (${x.refs.length} saved)`:"Live",F.append(U,G,q,X,Q);let fe=document.createElement("div");fe.className="bp-history-group";let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(x.highlightEdits?" is-on":""),Le.textContent="Highlight edits",Le.disabled=x.refs.length===0,Le.setAttribute("data-testid","history-highlight"),Le.addEventListener("click",()=>{Y(),x.toggleHighlight(),Ae()});let we=document.createElement("div");we.className="bp-history-menu-wrap";let Be=document.createElement("button");if(Be.type="button",Be.className="bp-v-btn"+(I||!x.isLive()?" is-on":""),Be.disabled=x.refs.length===0,Be.setAttribute("data-testid","history-compare"),Be.setAttribute("aria-haspopup","menu"),Be.setAttribute("aria-expanded",String(I)),Be.textContent=he?`Compare: ${he.label||he.commit.slice(0,7)} ▾`:"Compare ▾",Be.addEventListener("click",(Re)=>{Re.stopPropagation(),I=!I,pe()}),we.append(Be),I&&x.refs.length>0){let Re=document.createElement("div");Re.className="bp-history-menu",Re.setAttribute("role","menu"),Re.setAttribute("data-testid","history-compare-menu");let We=(De,Xe,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Xe),Ve.textContent=De,Ve.addEventListener("click",()=>{if(I=!1,Y(),x.selectCommit(Xe)){if(x.isLive())te("",!1);Ae()}else pe()}),Re.append(Ve)};We("Live (working tree)","",x.isLive());for(let De of x.refs)We(De.label||De.commit.slice(0,7),De.commit,he?.commit===De.commit);we.append(Re)}fe.append(Le,we),y.replaceChildren(F,fe)}async function ee(R){if(!R)return;try{let F=await t.hub.rpc("viewer.refs",{thread:R});if(R!==f)return;x.setRefs(Array.isArray(F?.refs)?F.refs:[]),pe()}catch{if(R!==f)return;x.setRefs([]),pe()}}function be(){return document.documentElement.classList.contains("light")}let Te=new MutationObserver(()=>{let R=be();re?.setTheme(R),se?.setTheme(R),de?.setTheme(R)});Te.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ue(R,F="",U=!1){if(R==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${R}`;let G=document.createElement("div");G.className="bp-v-state-card";let q=document.createElement("div");if(q.className="bp-v-state-msg",q.textContent=F,G.append(q),U){let X=document.createElement("button");X.type="button",X.className="bp-v-btn is-primary",X.textContent=h("tools.retry","Retry"),X.addEventListener("click",()=>void $e(!0)),G.append(X)}d.replaceChildren(G)}function te(R,F){m.textContent=R,m.hidden=!R,m.classList.toggle("is-warn",F)}function je(){if(me)return xt(me);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(j);return""}function Z(){s.textContent=Ki(g);let R=je();if(a.hidden=!R,r.hidden=!R,r.textContent=R,o.replaceChildren(),g==="mech"&&_.length>1){let U=document.createElement("select");U.className="bp-v-select",U.setAttribute("aria-label",h("viewer.mech","Mech"));for(let G of _){let q=document.createElement("option");q.value=G,q.textContent=xt(G),q.selected=G===j,U.append(q)}U.addEventListener("change",()=>{j=U.value,Z(),$e(!1)}),o.append(U)}if(vn(g)){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(ke?" is-on":""),U.textContent=T?.layerHead||"Layers",U.setAttribute("data-testid","viewer-layers-btn"),U.addEventListener("click",()=>{if(ke=!ke,p.hidden=!ke,U.classList.toggle("is-on",ke),ke)Ue("","")}),o.append(U)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Fit",U.setAttribute("data-testid","viewer-fit-btn"),U.addEventListener("click",()=>{re?.fit(),se?.fit()}),o.append(U)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(ce&&!ie?" is-on":""),U.textContent=ce?ie?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",U.setAttribute("data-testid","viewer-follow-btn"),U.addEventListener("click",()=>void nt()),o.append(U)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn bp-v-close",F.textContent="✕",F.title=h("common.close","Close"),F.setAttribute("aria-label",h("common.close","Close")),F.setAttribute("data-testid","viewer-close-btn"),F.addEventListener("click",()=>t.closeViewer()),o.append(F)}function Ce(){if(!T){p.replaceChildren();return}let R=document.createDocumentFragment(),F=document.createElement("div");F.className="bp-v-layers-head";let U=document.createElement("span");if(U.textContent=T.layerHead||"Layers",F.append(U),T.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void Ue("reset","")),F.append(Q)}if(R.append(F),T.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((he,fe)=>{let Le=document.createElement("button");Le.type="button",Le.className="bp-v-btn"+(T?.layerMode===fe?" is-on":""),Le.textContent=he,Le.addEventListener("click",()=>void Ue("mode",String(fe))),Q.append(Le)}),R.append(Q)}let G=re?.presentColors()??new Map,q=(T.layerList||[]).concat(T.layerMarks||[]),X=document.createElement("div");X.className="bp-v-layers-list";for(let Q of q){let he=G.get(Q.layer);if(he===void 0)continue;let fe=document.createElement("div");fe.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Le=document.createElement("input");Le.type="checkbox",Le.checked=Q.on!==!1,Le.addEventListener("change",()=>void Ue("toggle",String(Q.layer)));let we=document.createElement("span");we.className="bp-v-layer-swatch";let Be=he>>>16&255,Re=he>>>8&255,We=he&255;we.style.background=Q.on!==!1?`rgb(${Be},${Re},${We})`:`rgba(${Be},${Re},${We},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=Q.name,De.addEventListener("click",()=>void Ue("pick",String(Q.layer))),fe.append(Le,we,De),X.append(fe)}R.append(X),p.replaceChildren(R)}async function Ue(R,F){if(!vn(g))return;let U=w;try{let G=await t.hub.rpc("viewer.layers",{kind:g,present:Me,off:Ne,focus:ge,...R?{action:R,value:F}:{}});if(U!==w||!G)return;Ne=Number(G.own)||0,ge=typeof G.focus==="string"?G.focus:"",T=G;let q={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(re?.setLayers(q),Z(),ke)Ce()}catch{}}async function ze(){if(!ce||ie||!f||!t.hub.hasFeature("follow"))return;ie=!0,Z();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function nt(){if(!f||!t.hub.hasFeature("follow"))return;let R=!ce?"on":ie?"resume":"off";try{let F=await t.hub.rpc("viewer.follow",{thread:f,action:R});if(ce=!!F.on,ie=!!F.paused,Z(),F.on&&!F.paused&&F.focus&&Array.isArray(F.focus.box)&&F.focus.box.length===4&&(F.seq||0)>ye)ye=F.seq||ye,re?.zoomToBoxMm([F.focus.box[0],F.focus.box[1],F.focus.box[2],F.focus.box[3]])}catch{}}function oe(){b.hidden=!0,b.replaceChildren(),re?.setHighlights([])}function lt(R){let F=R.split(";").filter(Boolean),U=F.shift()||R,G=[],q="",X="";for(let we of F){if(we.startsWith("g="))continue;let Be=we.indexOf("=");if(Be>0){let Re=we.slice(0,Be),We=we.slice(Be+1);if((Re==="ref"||Re==="symbol")&&!q)q=We;if(Re==="net"&&!X)X=We;G.push([Re,We])}else G.push([we,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let he=document.createElement("span");he.className="bp-v-info-title",he.textContent=U;let fe=document.createElement("button");fe.type="button",fe.className="bp-v-info-x",fe.textContent="×",fe.setAttribute("aria-label","Clear selection"),fe.addEventListener("click",oe),Q.append(he,fe);let Le=document.createElement("div");Le.className="bp-v-info-rows";for(let[we,Be]of G){let Re=document.createElement("span");Re.className="bp-v-info-chip",Re.textContent=Be?`${we}: ${Be}`:we,Le.append(Re)}return b.replaceChildren(Q,...G.length>0?[Le]:[]),b.hidden=!1,{ref:q||void 0,net:X||void 0}}async function Je(R){if(!R){oe();return}let F=Array.from(S)[0]||"";if(!F)return;let U=w;try{let G=await t.hub.rpc("viewer.info",{key:F,at:R.at,idx:R.idx});if(U!==w)return;let q=typeof G.info==="string"?G.info:"";if(!q){oe();return}let{ref:X,net:Q}=lt(q),he=[];if(X)he.push(["ref",X]);if(Q)he.push(["net",Q]);let fe=[[R.at,R.idx]];for(let[Le,we]of he){let Be=await t.hub.rpc("viewer.probe",{key:F,name:Le,value:we});if(U!==w)return;if(Array.isArray(Be.matches))for(let Re of Be.matches)fe.push(Re)}re?.setHighlights(fe)}catch{oe()}}function ct(){J?.destroy(),J=null,de?.destroy(),de=null,re?.destroy(),re=null,se?.destroy(),se=null,u.replaceChildren(),ke=!1,p.hidden=!0,b.hidden=!0,b.replaceChildren(),te("",!1),ue("none")}function Ye(){L=[],M=0}async function $e(R){if(!f||!g)return;let F=++w;if(S.clear(),k=!1,Ye(),ct(),Z(),Ie(),pe(),(g==="board"||g==="schematic")&&f)ee(f);if(qs(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")J=Hi(u,t,f,(q,X)=>{if(g=q,me=X,q==="mech")j=X;$e(!1)});else if(g==="diff")J=Di(u,t,f);else if(g==="review")J=Fi(u,t,f);else if(g==="browser")J=Ii(u,t,f);else if(g==="terminal")ue("loading","Loading terminal…"),import("/assets/terminal.js").then((X)=>{if(F!==w)return;if(ue("none"),X?.mountTerminalPane)de=X.mountTerminalPane(u,t,f,be());else ue("error","Terminal chunk missing",!0)},(X)=>{if(F!==w)return;ue("error",X instanceof Error?X.message:String(X),!0)});return}if(ue("loading","Loading…"),!W.root)try{let q=await t.hub.rpc("viewer.files",{thread:f});if(F!==w)return;W=q||{},Z()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){ue("empty","No Gerbers in this project",!1);return}let U=be();if(g==="3d"||g==="mech")se=new fn(u,{onStatus:(q,X)=>{if(X)ue("none"),te(q,!1);else if(q)ue("loading",q);else ue("none"),te("",!1)},onUserMove:()=>void ze()}),se.setTheme(U);else if(g==="board"||g==="schematic"||g==="gerbers")re=new hn(u,{onPick:(q)=>void Je(q),onUserMove:()=>void ze()}),re.setTheme(U);else{ue("empty",`${Ki(g)} is not available in this viewer`,!1);return}let G={thread:f};if(R)G.force=!0;if(g==="mech"){if(_.length===0)try{let q=await t.hub.rpc("mech.list",{thread:f});if(F!==w)return;if(_=Array.isArray(q.parts)?q.parts:[],!j)j=q.primary||_[0]||"";Z()}catch(q){if(F!==w)return;ue("error",q instanceof Error?q.message:String(q),!0);return}if(!j){ue("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=j}else{if(G.kind=g,me&&(g==="board"||g==="schematic"))G.path=me;if(g==="3d"&&!R&&se){let q=se.keptToken();if(q)G.kept=q}if((g==="board"||g==="schematic"||g==="gerbers")&&!R&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(H.keys())}k=!0,D="",K="",le="",N="";try{let q=await t.hub.rpc("viewer.watch",G);if(F!==w)return;S=new Set(Array.isArray(q.keys)?q.keys:[]),k=!1;let X=L;Ye();for(let Q of X)if(Q.kind==="bin")Ge(Q.buf);else Oe(Q.key,Q.none,Q.retryable)}catch(q){if(F!==w)return;k=!1,S.clear(),Ye();let X=q instanceof Error?q.message:String(q),Q=/no gerbers|not in this project|another machine/i.test(X);ue(Q?"empty":"error",X,!Q)}}function Oe(R,F,U){if(k){if(L.length{if(R.t==="plot"&&typeof R.none==="string"&&typeof R.key==="string")Oe(R.key,R.none,R.retryable===!0)}),Dt=Lt(()=>{if(g)Z()}),kt=(R)=>{if(R.key==="Escape"&&g&&!b.hidden)oe()};return window.addEventListener("keydown",kt),{open(R,F){if(F!==f){if(f=F,W={},_=[],j="",B.clear(),ce=!1,ie=!1,ye=0,Ne=0,ge="",Me=0,T=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:F}).then((U)=>{if(F!==f)return;if(ce=!!U.on,ie=!!U.paused,ye=Number(U.seq)||0,g)Z()}).catch(()=>{})}if(R!==g)Y(),x.goLive(),Ne=0,ge="",Me=0,T=null;g=R,me="",$e(!1)},reconcileHas(R){if(g&&!_s(g,R))t.closeViewer()},close(){if(w++,k=!1,Y(),I=!1,D="",K="",le="",N="",x.goLive(),c.hidden=!0,y.hidden=!0,Ye(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",S.clear(),ct()}}}var zi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(zi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(zi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ks(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ji(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Yi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function zs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Xi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,c,m,l);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let p=document.createElement("span");p.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(d,p,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let k=document.createElement("span");k.textContent=h("menu.settle","Settle"),w.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),k);let S=document.createElement("div");S.className="bp-menu-wrap";let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost bp-top-act",L.textContent="▾",L.title="Thread menu",L.setAttribute("aria-label","Thread menu"),L.setAttribute("data-testid","thread-menu-btn");let M=document.createElement("div");M.className="bp-popover bp-hidden",M.setAttribute("data-testid","thread-menu"),S.append(L,M),y.append(f,w,S);let B=document.createElement("div");B.className="bp-top-right";let H=document.createElement("button");H.type="button",H.className="bp-btn-ghost bp-top-act bp-hide-tablet",H.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=h("gpui.improvements","Improvements"),H.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let j=document.createElement("button");j.type="button",j.className="icon bp-top-icon",j.title="Search",j.setAttribute("aria-label","Search"),j.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let me=document.createElement("button");me.type="button",me.className="icon bp-top-icon",me.title=h("palette.settings","Settings"),me.setAttribute("aria-label",h("palette.settings","Settings")),me.setAttribute("data-testid","settings-btn"),me.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),B.append(H,_,j,me),t.append(n,i,u,y,B);let ce=document.createElement("div");ce.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let ke=document.createElement("div");ke.className="bp-right-area bp-hidden",ke.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let ge=document.createElement("section");ge.className="bp-viewer-pane bp-hidden",ge.setAttribute("data-testid","viewer-pane"),Ne.appendChild(ge),ke.appendChild(Ne);let Me=document.createElement("nav");Me.className="bp-rail",Me.setAttribute("aria-label","Viewer rail"),Me.setAttribute("data-testid","viewer-rail"),ce.append(ie,ye,ke,Me),e.append(t,ce);let T=new pn,re=null,se=new Set,J=0,de=null,x=[],C=[],I=[],D=[],K=[],le=[],N="",Y=0,Ie=0,Ae=null,pe=null,ee="",be=null,Te=20,ue={},te=new Map;function je(v,E){te.delete(v),te.set(v,E);while(te.size>Te){let A=te.keys().next().value;if(A!==void 0)te.delete(A);else break}}let Z=new ln(ie,{onSelectThread:(v)=>{if(v===N&&Ae!==null){ie.classList.remove("bp-sidebar-open");return}we(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{we(v.thread)},onThreadAct:(v,E)=>{Qe(v,E)},onToggleSection:(v)=>{if(se.has(v))se.delete(v);else se.add(v);he()},onToggleProjectFold:(v)=>{T.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>he()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let E=Rt(v,!1);if(!E)return;if(E.kind==="thread"){we(E.id);return}if(E.kind!=="call")return;let A=fi(await T.rpc(E.method,E.params));if(A?.kind==="thread")we(A.id);he()},hasRoomView:!1,onAddProject:()=>Oe.open({mode:"folder"})}),Ce=new qt(ye,{onLoadOlder:()=>{We()},onGoToEntry:(v)=>{Re(v)},onAnswerAsk:(v,E)=>{T.rpc("ask.answer",{ask:v,answer:E}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not send answer")})},onToggleReview:(v)=>{if(!N)return;let E=Y;T.rpc("thread.review",{thread:N,on:v}).then((A)=>{if(E===Y)Ce.setReview(A.review??null)}).catch(()=>{})},onUnansweredAction:(v,E)=>{if(!N)return;if(v==="again"||v==="thread-again")T.rpc("thread.again",{thread:N,value:E}).catch(()=>{});else T.rpc("thread.act",{thread:N,action:v,value:E}).catch(()=>{})},onReplyEntry:(v)=>{if(!T.hasFeature("reply")){let E=(v.text||"").split(` -`)[0]?.slice(0,100)??"";if(E)oe.prependDraft(`> ${E} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,E)=>{try{let A={entry:v,path:E};if(T.hasFeature("blobs"))A.metaOnly=!0;let P=await T.rpc("message.image",A);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function Ue(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function ze(v,E){if(!N)return;let A=Y,P=N;T.rpc(v,E).then((V)=>{if(A!==Y||N!==P)return;if(V.thread){let ne=C.findIndex((ve)=>ve.id===V.thread.id);if(ne>=0)C[ne]=V.thread;else C.unshift(V.thread);Z.setData(x,C,I,D),Ce.updateThreadMeta(V.thread),R(),oe.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(A===Y&&N===P)oe.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let nt,oe=new zt(ye,{onSend:(v,E)=>{wn(v,E)},onRunCommand:(v)=>{En(v)},onInterrupt:()=>{if(N)T.rpc("turn.interrupt",{thread:N}).catch(()=>{})},onQueryMentions:async(v,E)=>{try{return(await T.rpc("mentions.list",{q:v,kind:E,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=C.find((A)=>A.id===N)??null,E=Ue(v);if(!E||!N)return;if(E.interaction!=="plan")ze("thread.planonce",{thread:N,on:!0});else if(E.once)ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!N)return;if(v==="once")ze("thread.planonce",{thread:N,on:!0});else if(v==="always")ze("thread.pick",{thread:N,action:"interaction",value:"plan"});else ze("thread.pick",{thread:N,action:"interaction",value:"default"})}});nt=new cn(T,{getThreadId:()=>N,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function lt(){let v=ee!=="",E=Je.isOpen();ke.classList.toggle("bp-hidden",!v&&!E),ke.classList.toggle("bp-has-viewer",v),ke.classList.toggle("bp-has-mgmt",E)}let Je=new tn(Ne,ke,{hub:T,getThreadId:()=>N,getThreadGen:()=>Y,onSendText:(v)=>{wn(v)},onOpenChange:()=>lt()});function ct(v){let E=window.prompt("Rename thread",v.title||"");if(!E||!E.trim())return;T.rpc("thread.act",{thread:v.id,action:"rename",title:E.trim()}).then((A)=>{if(A.thread)C=C.map((P)=>P.id===A.thread.id?A.thread:P),R(),he()}).catch((A)=>{oe.showError(A instanceof Error?A.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":we(v.id);break;case"rail":if(!N&&v.id!=="terminal")break;if(ee===v.id)F();else U(v.id);break;case"thread-act":if(N)Qe(N,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let E=C.find((A)=>A.id===N);if(E)ct(E);break}case"prev-thread":case"next-thread":{let E=C.filter((ne)=>!ne.archived&&!ne.swarm);if(E.length<2)break;let A=E.findIndex((ne)=>ne.id===N),P=v.type==="next-thread"?1:-1,V=E[(A<0?0:A+P+E.length)%E.length];if(V)we(V.id);break}case"command":if(v.runDirectly)En(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":kt();break;case"settings":qe.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let $e=new nn(e,{getState:()=>({selectedThreadId:N,threads:C,projects:x,bots:I,railItems:K,commands:le}),onSearch:async(v)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:v,limit:20})},onExecute:Ye}),Oe=new Vt(e,{hub:T,onProjectAdded:(v)=>{if(he(),v.id)De(v.id)},onCloneDone:(v)=>{if(he(),v.thread)we(v.thread)}}),Ge=new sn(Me,(v)=>{if(v==="commands"){$e.open();return}if(!N)return;if(ee===v)F();else U(v)}),it=null,qe=new an(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,E)=>{await T.rpc("devices.page.act",{action:v,value:E})},onGetHome:()=>it,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>Hn(()=>{T.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=C.find((E)=>E.id===N);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let Dt=new on(e,(v,E)=>E?T.rpc("thread.context.mcp",{thread:v,...E}):T.rpc("thread.context",{thread:v}));L.addEventListener("click",(v)=>{v.stopPropagation();let E=C.find((V)=>V.id===N);if(!E)return;if(!M.classList.contains("bp-hidden")){M.classList.add("bp-hidden");return}let A=[{label:"Rename…",run:()=>ct(E)},{label:E.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(E.id,E.pinned?"unpin":"pin")}},{label:E.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(E.id,E.settled?"unsettle":"settle")}},{label:E.archived?"Unarchive":"Archive",run:()=>{Qe(E.id,E.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(E.id,"delete")}}];if(T.hasFeature("threadContext"))A.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Dt.open(E.id)});let P=document.createDocumentFragment();for(let V of A){let ne=document.createElement("button");ne.type="button",ne.className="bp-popover-item"+(V.danger?" danger":""),ne.textContent=V.label,ne.addEventListener("click",()=>{M.classList.add("bp-hidden"),V.run()}),P.appendChild(ne)}M.replaceChildren(P),M.classList.remove("bp-hidden")}),document.addEventListener("click",()=>M.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let E=document.createElement("div");E.className="bp-modal";let A=document.createElement("div");A.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),A.append(P,V);let ne=document.createElement("div");ne.className="bp-modal-body",ne.textContent="Loading…",E.append(A,ne),v.appendChild(E),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await T.rpc("improvements.projects",{}),He=ve.projects??[];if(He.length===0){ne.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Se of He){let ae=document.createElement("div");ae.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Se.title||Se.name||Se.id;let tt=document.createElement("button");tt.type="button",tt.className=Se.id===ve.project?"primary":"",tt.textContent=Se.id===ve.project?"Active":"Select",tt.addEventListener("click",()=>{T.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),ae.append(Ze,tt),et.appendChild(ae)}ne.replaceChildren(et)}catch(ve){ne.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}H.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>$e.open()),j.addEventListener("click",()=>$e.open()),me.addEventListener("click",()=>{qe.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function R(){let v=C.find((P)=>P.id===N)??null,E=v?x.find((P)=>P.id===v.project):void 0;o.textContent=E?.title??"",r.classList.toggle("bp-hidden",!E),c.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let A=Ue(v);if(oe.setPlanMode(A),!A||A.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",A.phase==="executing"),l.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=A.phase==="armed"&&A.once?h("gpui.planmode.top.once","Plan (1 turn)"):A.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):A.phase==="planning"?h("gpui.planmode.top.planning","Planning"):A.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){p.className=`bp-dot ${Ks(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),k.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;oe.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function F(v=!0){if(Ie++,ee="",Ge.setActive(""),ge.classList.add("bp-hidden"),be?.close(),lt(),v&&N&&T.getState()==="connected")T.rpc("viewer.watch",{thread:N,kind:""}).catch(()=>{})}function U(v){if(Ie++,ee=v,Ge.setActive(v),ge.classList.remove("bp-hidden"),lt(),!be&&typeof yn==="function")be=yn(ge,{hub:T,getThreadId:()=>N,closeViewer:()=>F(!0)});if(be)be.open(v,N);else{let E=document.createElement("div");E.className="bp-viewer-placeholder";let A=document.createElement("div");A.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>F(!0)),A.append(P,V);let ne=document.createElement("div");ne.className="bp-dim bp-viewer-msg",ne.textContent=`Viewer pane (${v}).`,E.append(A,ne),ge.replaceChildren(E)}}async function G(v,E){if(!v||!T.hasFeature("rail")){if(E===Y)K=[],Ge.setItems([]);return}let A=++Ie;try{let P=await T.rpc("viewer.rail",{thread:v,page:ee});if(E!==Y||A!==Ie)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(K=V,Ge.setItems(V),P.has){if(be?.reconcileHas?.(P.has),ee&&!Ji(P.has,ee))F(!0)}}catch{if(E===Y&&A===Ie)K=[],Ge.setItems([])}}function q(v){for(let E of v)if(E.kind==="threads"){for(let A of E.rows)if(!A.off&&(A.nav||A.id)&&!(A.nav||"").startsWith("@room:"))return A.nav||A.id}else if(E.kind==="projects"){for(let A of E.rows)for(let P of A.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function X(v,E){for(let A of v)if(A.kind==="threads"){if(A.rows.some((P)=>(P.nav||P.id)===E))return!0}else if(A.kind==="projects"){for(let P of A.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===E))return!0}return!1}function Q(v){let E=[];for(let A of v){if(A.kind!=="projects")continue;for(let P of A.rows)E.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(E.length>0)x=E}async function he(){if(!T.hasFeature("sections"))return!1;let v=++J;try{let E=await T.rpc("sidebar.sections",{open:Array.from(se)});if(v!==J)return!0;let A=Array.isArray(E.sections)?E.sections:[];return re=A,Q(A),Z.setData(x,C,I,D),Z.setSections(A,I,D),R(),!0}catch{return!1}}function fe(){if(!T.hasFeature("sections"))return;if(de!==null)window.clearTimeout(de);de=window.setTimeout(()=>{de=null,he()},150)}async function Le(){if(Ae=null,T.hasFeature("bots"))try{let E=await T.rpc("bots.list",{});I=E.bots??[],D=E.rooms??[]}catch{}if(T.hasFeature("shell")){let E=await T.rpc("shell.sync",{have:ue,settled:25}),A=new Set(E.removed??[]),P=new Set((E.projects??[]).map((V)=>V.id));if(A.size>0||P.size>0)x=[...x.filter((V)=>!A.has(V.id)&&!P.has(V.id)),...E.projects??[]],C=[...C.filter((V)=>!A.has(V.project)&&!P.has(V.project)),...E.threads??[]];else if(Array.isArray(E.threads)&&E.threads.length>0){let V=new Map(C.map((ne)=>[ne.id,ne]));for(let ne of E.threads)V.set(ne.id,ne);C=Array.from(V.values())}if(E.sections!==void 0){let V=Array.isArray(E.sections)?E.sections:Array.isArray(E.sections?.sections)?E.sections.sections:null;if(V)re=V,Q(V)}if(E.h)ue=E.h;Z.setData(x,C,I,D),Z.setSections(re,I,D)}else if(T.hasFeature("sections")){let[E,A]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(se)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(C=A.threads??[],E&&Array.isArray(E.sections)){let P=E.sections;if(!P.some((ne)=>ne.kind==="projects"&&ne.rows.length>0)){let ne=P.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(ne?.toggle&&!se.has(ne.toggle)){se.add(ne.toggle);let ve=await T.rpc("sidebar.sections",{open:Array.from(se)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))P=ve.sections}}re=P,Q(P),Z.setData(x,C,I,D),Z.setSections(P,I,D)}else re=null,x=(await T.rpc("projects.list",{limit:100})).projects??[],Z.setSections(null,I,D),Z.setData(x,C,I,D);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{re=null;let[E,A]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);x=E.projects??[],C=A.threads??[],Z.setSections(null,I,D),Z.setData(x,C,I,D),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=N;if(!v){let E="";try{E=localStorage.getItem("bp.lastThread")||""}catch{}if(E&&(re&&X(re,E)||C.some((A)=>A.id===E)))v=E;else if(re)v=q(re);if(!v)v=(C.find((P)=>!P.archived&&!P.swarm&&!P.settled)??C.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(re&&X(re,v)||C.some((E)=>E.id===v)))await we(v);else N="",K=[],Ge.setItems([]),oe.setState(!1,!1),R()}async function we(v){if(N&&N!==v){nt.cancel();let Se=Ce.getEntries();if(Se.length>0){let ae=te.get(N);je(N,{entries:Se,ids:ae?.ids??Se.map((Ze)=>Ze.id),olderCursor:pe,review:ae?.review??null,unanswered:ae?.unanswered??null,rail:ae?.rail??K,hashes:ae?.hashes??{}})}}let E=++Y;Ie++,Ve(null);let A=Ae;if(Ae=null,A!==null)T.rpc("unsubscribe",{sub:A}).catch(()=>{});N=v;let P=te.get(v);pe=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}Z.setSelected(v),ie.classList.remove("bp-sidebar-open"),R();let V=C.find((Se)=>Se.id===v)??null;if(P)Ce.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),K=P.rail,Ge.setItems(P.rail);else Ce.setLoading(V),K=[],Ge.setItems([]);if(oe.setState(!0,V?.state==="working"),T.hasFeature("open")){let Se={};if(P){for(let[Pe,pt]of Object.entries(P.hashes))Se[Pe]=pt;for(let Pe of P.entries)if(Pe.h)Se[Pe.id]=Pe.h}let ae;try{ae=await T.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Pe){if(E===Y){let pt=Pe instanceof Error&&Pe.message?Pe.message:"Could not load messages.";Ce.setError(V,pt,()=>{we(v)})}return}if(E!==Y){if(ae.sub!==void 0&&ae.sub!==null)T.rpc("unsubscribe",{sub:ae.sub}).catch(()=>{});return}if(Ae=ae.sub??null,ae.thread){V=ae.thread;let Pe=C.findIndex((pt)=>pt.id===ae.thread.id);if(Pe>=0)C[Pe]=ae.thread;else C.unshift(ae.thread);R(),oe.setState(!0,V.state==="working")}if("next"in ae)pe=ae.next??null;let Ze=new Map;if(P)for(let Pe of P.entries)Ze.set(Pe.id,Pe);for(let Pe of ae.entries??[])Ze.set(Pe.id,Pe);let tt=ae.ids??P?.ids??(ae.entries??[]).map((Pe)=>Pe.id),Cn=tt.map((Pe)=>Ze.get(Pe)).filter((Pe)=>Boolean(Pe)),dt=P?.rail??[];if(ae.rail!==void 0){if(Array.isArray(ae.rail))dt=ae.rail;else if(dt=Array.isArray(ae.rail?.rail)?ae.rail.rail:Array.isArray(ae.rail?.items)?ae.rail.items:[],ae.rail?.has){if(be?.reconcileHas?.(ae.rail.has),ee&&!Ji(ae.rail.has,ee))F(!0)}}K=dt,Ge.setItems(dt);let Ft=P?.review??null;if(T.hasFeature("reviewmode"))try{let Pe=await T.rpc("thread.review",{thread:v});if(E!==Y)return;Ft=Pe.review??null}catch{}if(E!==Y)return;let kn="unanswered"in ae?ae.unanswered??null:P?.unanswered??null,Zi=ae.h??P?.hashes??{};if(je(v,{entries:Cn,ids:tt,olderCursor:pe,review:Ft,unanswered:kn,rail:dt,hashes:Zi}),Ce.setThread(V,Cn,Boolean(pe),Ft,kn),Be(v,E),ee)U(ee);return}let ne;try{ne=await T.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(E===Y){let ae=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";Ce.setError(V,ae,()=>{we(v)})}return}if(E!==Y)return;if(ne.thread){let Se=C.findIndex((ae)=>ae.id===ne.thread.id);if(Se>=0)C[Se]=ne.thread;else C.unshift(ne.thread);R()}pe=ne.next??null;let ve=null;if(T.hasFeature("reviewmode"))try{let Se=await T.rpc("thread.review",{thread:v});if(E!==Y)return;ve=Se.review??null}catch{}if(E!==Y)return;let He=ne.entries??[],et=ne.unanswered??null;je(v,{entries:He,ids:He.map((Se)=>Se.id),olderCursor:pe,review:ve,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),Ce.setThread(V,He,Boolean(pe),ve,et);try{let ae=(await T.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(ae!==null){if(E!==Y){T.rpc("unsubscribe",{sub:ae}).catch(()=>{});return}Ae=ae}}catch{}if(E!==Y)return;if(G(v,E),Be(v,E),ee)U(ee)}async function Be(v,E){if(!v||!T.hasFeature("mgmt")){if(E===Y)Je.clear();return}let A=C.find((V)=>V.id===v),P=A?.project?x.find((V)=>V.id===A.project)?.root??"":"";if(!P&&T.hasFeature("viewers"))try{let V=await T.rpc("viewer.files",{thread:v});if(E!==Y)return;P=V.pcb||V.sch||V.root||""}catch{}if(E!==Y)return;if(P)await Je.watchProject(P);else Je.clear()}async function Re(v){let E=Y;for(let A=0;A<25&&E===Y;A++){if(Ce.goTo(v))return;if(!pe)return;let P=pe;if(await We(),pe===P)return}}async function We(){if(!N||!pe){Ce.clearLoadingOlder();return}let v=Y,E=N,A=pe;try{let P=await T.rpc("thread.entries",{thread:E,limit:40,before:A});if(v!==Y||N!==E)return;pe=P.next??null,Ce.prependEntries(P.entries??[],Boolean(pe))}catch{if(v===Y)Ce.clearLoadingOlder()}}async function De(v){try{let E=await T.rpc("thread.create",{project:v});if(E.thread)C=[E.thread,...C.filter((A)=>A.id!==E.thread.id)],Z.setData(x,C,I,D),he(),await we(E.thread.id),oe.focus()}catch(E){oe.showError(E instanceof Error?E.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` -`).map((E)=>E.trim()).find((E)=>E.length>0)??"").slice(0,200)}function Ve(v){Xe=v,oe.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Re(Xe.id)},()=>Ve(null))}async function wn(v,E=[]){if(!N)return;let A=Y,P=N,V=zs(),ne=`local-${V}`,ve=Xe&&v.trim()&&T.hasFeature("reply")?Xe:null;if(ve)Ve(null);Ce.upsertEntry({id:ne,kind:"user",text:v,at:Date.now(),clientId:V,...ve?{replyTo:{id:ve.id,quote:St(ve.text)}}:{},attachments:E.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:V};if(E.length>0)He.attachments=E;if(ve)He.replyTo={id:ve.id,text:ve.text};let et=await T.rpc("message.send",He);if(A!==Y||N!==P)return;if(et.entry)Ce.upsertEntry(et.entry)}catch(He){if(A===Y&&N===P){if(Ce.removeEntry(ne),oe.setDraft(v),ve&&!Xe)Ve(ve);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function En(v){if(!N)return;let E=Y,A=N;try{let P=await T.rpc("composer.run",{thread:A,text:v});if(E!==Y||N!==A)return;if(P.error)oe.setDraft(v),oe.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")oe.setDraft(P.text);else if(P.kind==="project")Oe.open({mode:"folder"});else if(P.kind==="clone")Oe.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(E===Y&&N===A)oe.setDraft(v),oe.showError(P instanceof Error?P.message:"Command refused")}}async function Qe(v,E){try{let A=await T.rpc("thread.act",{thread:v,action:E});if(A.thread){if(C=C.map((P)=>P.id===A.thread.id?A.thread:P),Z.setData(x,C,I,D),A.thread.id===N)Ce.updateThreadMeta(A.thread),R()}he()}catch(A){oe.showError(A instanceof Error?A.message:`Action "${E}" not allowed`)}}function xn(v,E){if(!v||!v.text||E-v.at>=300000)return"";let A=v.build.split("-").pop()??"";if(v.reason==="build"&&A)return h("hub.restarting.build",v.text,{build:A});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function At(v){if(v==="connected")Z.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&xn(T.restarting,Date.now()))Z.setConnStatus(xn(T.restarting,Date.now()),"");else if(v==="reconnecting")Z.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")Z.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Z.setConnStatus("Connecting…","")}Lt(()=>{At(T.getState()),W.textContent=h("gpui.improvements","Improvements"),me.title=h("palette.settings","Settings"),me.setAttribute("aria-label",h("palette.settings","Settings")),R(),Z.refreshLocale(),Ce.refreshLocale(),oe.refreshLocale(),Ge.render(),qe.refreshLocale(),Oe.refreshLocale()}),T.onState((v,E)=>{if(v==="connected"&&E){if(E.locale)Mn(E.locale);if(E.theme)Yi(E.theme);if(E.name)Z.setHostName(E.name);if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();At(v);let A=typeof E.hubBack==="string"?String(E.hubBack):"";if(A)try{let P=JSON.parse(A);if(P.reason==="crash")Z.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>At(T.getState()),6000)}catch{}if(oe.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(E.commands))le=E.commands,oe.setCommands(le);else le=[];Le(),Oe.reconcile()}else nt.cancel(),At(v)}),T.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let E=v;if(E.k==="clone"||E.k==="clone.repos"||E.k==="clone.signin"){Oe.handleFrame(E);return}switch(E.k){case"project":{let A=E.project;if(!A)break;let P=x.findIndex((V)=>V.id===A.id);if(P>=0)x[P]=A;else x.unshift(A);Z.setData(x,C,I,D),R(),fe();break}case"thread":{let A=E.thread;if(!A)break;let P=C.findIndex((V)=>V.id===A.id);if(P>=0)C[P]=A;else C.unshift(A);if(Z.setData(x,C,I,D),A.id===N)Ce.updateThreadMeta(A),R(),oe.setState(!0,A.state==="working");fe();break}case"thread.removed":{let A=String(E.id??"");C=C.filter((P)=>P.id!==A),Z.setData(x,C,I,D),fe();break}case"entry":{if(E.thread===N&&E.entry)Ce.upsertEntry(E.entry);break}case"text":{if(E.thread===N)Ce.appendLiveText(String(E.entry??""),String(E.append??""),Number(E.at??Date.now()));break}case"turn":{if(E.thread===N){let A=String(E.state??"idle");oe.setState(!0,A==="working"),G(N,Y)}fe();break}case"btw":{if(E.thread===N)Ce.showBtw(String(E.q??""),String(E.a??""));break}case"unanswered":{if(E.thread===N)Ce.setUnanswered(E.unanswered??null);break}case"theme":{if(typeof E.theme==="string")Yi(E.theme);break}case"home":{if(it=E.home??null,Z.setHome(it),qe.isOpen())qe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let E=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(E==="k"||v.shiftKey&&E==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Oe.isOpen())Oe.escape();else if(qe.isOpen())qe.close();else if(Ce.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Xi);else Xi(); +`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Gs=[qe(77),qe(83),qe(94)],Us=[qe(53),qe(58),qe(67)],Os=[qe(245),qe(246),qe(248)],Vs=[qe(225),qe(228),qe(233)];function Wi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function _i(e,t,n){let i=Wi(e,e.VERTEX_SHADER,t),s=Wi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Ws(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function _s(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function qi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function Ki(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function fn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class vn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=_i(n,Hs,Ds),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=_i(n,Fs,$s),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Mi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,d=0,b=0;for(let g=0;g>>24&255,k=1-C/255,A=(E>>>16&255)/255,N=(E>>>8&255)/255,M=(E&255)/255,D=g*9;if(C===0&&o&&l&&m){let q=d*9;for(let H=0;H<9;H++)o[q+H]=e[D+H],l[q+H]=t[D+H];let K=d*12;for(let H=0;H<3;H++)m[K+H*4]=A,m[K+H*4+1]=N,m[K+H*4+2]=M,m[K+H*4+3]=1;d++}else if(c&&u&&p){let q=b*9;for(let H=0;H<9;H++)c[q+H]=e[D+H],u[q+H]=t[D+H];let K=b*12;for(let H=0;H<3;H++)p[K+H*4]=A,p[K+H*4+1]=N,p[K+H*4+2]=M,p[K+H*4+3]=k;b++}}let y=o&&l&&m?this.createSubBatch(o,l,m,a*3):null,f=c&&u&&p?this.createSubBatch(c,u,p,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Vi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let q=this.lightTheme?Os:Gs,K=this.lightTheme?Vs:Us;t.uniform3f(this.uBgTop,q[0],q[1],q[2]),t.uniform3f(this.uBgBot,K[0],K[1],K[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),m=Math.sin(this.pitch),c=Math.cos(this.yaw),u=Math.sin(this.yaw),p=[this.target[0]+this.dist*l*u,this.target[1]-this.dist*l*c,this.target[2]+this.dist*m],d=qi([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),b=Math.abs(d[2])>0.99?[0,1,0]:[0,0,1],y=qi(Ki(d,b)),f=Ki(y,d),g=new Float32Array([y[0],f[0],-d[0],0,y[1],f[1],-d[1],0,y[2],f[2],-d[2],0,-fn(y,p),-fn(f,p),fn(d,p),1]),E=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),k=_s(35*Math.PI/180,r/o,E,C),A=Ws(k,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,A),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,d[0],d[1],d[2]);let N=!1,M=[],D=[];for(let q of this.partBatches){let K=e-q.fadeStartMs,H=q.fadeStartMs===0?1:Math.min(1,Math.max(0,K/300));if(H<1){if(N=!0,H>0)D.push({batch:q,fade:H})}else M.push(q)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let q of M)this.drawSubBatch(q.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let q of M)this.drawSubBatch(q.translucent);for(let{batch:q,fade:K}of D)t.uniform1f(this.uFade,K),this.drawSubBatch(q.opaque),this.drawSubBatch(q.translucent);return t.depthMask(!0),t.bindVertexArray(null),N}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var zi=64,qs=16777216;function Ks(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ji(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function yn(e){return e==="board"||e==="schematic"||e==="gerbers"}function zs(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function wn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let d=document.createElement("div");d.className="bp-v-layers",d.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,c.append(u,p,d,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,l,m,c,y);let f="",g="",E=0,C=!1,k=new Set,A=[],N=0,M=new Map,D=new Map,q={},K=[],H="",he="",me=!1,ie=!1,we=0,Se=!1,Te=0,ge="",Be=0,T=null,re=null,ee=null,Y=null,le=null,F=new gn,x=0,S=!1,I="",V="",X="",j="";document.addEventListener("click",(R)=>{if(!S)return;if(R.target instanceof Node&&y.contains(R.target))return;S=!1,ce()}),document.addEventListener("keydown",(R)=>{if(S&&R.key==="Escape")S=!1,ce()});function B(){if(x)window.clearInterval(x),x=0;F.playing=!1}function je(){let R=g==="3d"||g==="mech";if(l.hidden=!R,!R)return;if(l.childElementCount>0)return;for(let O of Oi){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent=O.label,U.setAttribute("data-testid",`solid-view-${O.id}`),U.addEventListener("click",()=>{ee?.setView(O.id)}),l.append(U)}let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent="Snap view",G.setAttribute("data-testid","solid-snap"),G.addEventListener("click",()=>{if(!ee)return;ee.snapPng().then((O)=>{if(!O)return;let U=URL.createObjectURL(O),z=document.createElement("a");z.href=U;let Q=(ue()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");z.download=`${Q}-snap.png`,z.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),l.append(G)}async function ke(){if(!f||g!=="board"&&g!=="schematic")return;ce();let R=F.compareRequest();if(!R){I="",V="",X="",j="",await $e(!1);return}let G=`${g}|${R.commit}|${R.bits}|${he}`;if(G===j&&k.size>0){fe(F.highlightEdits?`Comparing against ${F.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${F.activeRef()?.label||R.commit.slice(0,7)}`,!1);return}let O=++E;k.clear(),M.clear(),Ye(),C=!0,I="",V=R.commit,X="",j=G;try{let U=he||(g==="schematic"?q.sch:q.pcb)||"";if(!U){let ve=await t.hub.rpc("viewer.files",{thread:f});if(O!==E)return;q=ve||{},Z(),U=(g==="schematic"?q.sch:q.pcb)||""}if(!U)throw Error(`Unable to resolve ${g} file path for compare`);let z=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:R.commit,bits:R.bits,...he?{path:he}:{}});if(O!==E)return;let Q=typeof z?.root==="string"?z.root:"",te=g==="schematic"?"1":"0";I=Q?`${te}|${Q}|diff +`:`${te}|`,V=R.commit,X=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Q?U:`${Q.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,C=!1;let be=A;Ye();for(let ve of be)if(ve.kind==="bin")Ge(ve.buf);else Oe(ve.key,ve.none,ve.retryable);fe(F.highlightEdits?`Comparing against ${F.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${F.activeRef()?.label||R.commit.slice(0,7)}`,!1)}catch(U){if(O!==E)return;C=!1,I="",V="",X="",j="",Ye(),fe(U instanceof Error?U.message:String(U),!0)}}function ce(){let R=g==="board"||g==="schematic";if(y.hidden=!R,!R)return;let G=document.createElement("div");G.className="bp-history-group";let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="<",O.title="Older snapshot",O.disabled=F.refs.length===0||F.index>=F.refs.length-1,O.setAttribute("data-testid","history-prev"),O.addEventListener("click",()=>{if(B(),F.step(1))ke()});let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(F.playing?" is-on":""),U.textContent=F.playing?"⏸":"▶",U.title=F.playing?"Pause history":"Play history",U.disabled=F.refs.length===0,U.setAttribute("data-testid","history-play"),U.addEventListener("click",()=>{if(F.playing){B(),ce();return}if(F.refs.length===0)return;if(F.playing=!0,F.isLive())F.index=F.refs.length-1,ke();else ce();x=window.setInterval(()=>{if(!F.playing||g!=="board"&&g!=="schematic"){B(),ce();return}if(F.step(-1))ke();else B(),ce()},1400)});let z=document.createElement("button");z.type="button",z.className="bp-v-btn",z.textContent=">",z.title="Newer snapshot",z.disabled=F.isLive(),z.setAttribute("data-testid","history-next"),z.addEventListener("click",()=>{if(B(),F.step(-1))ke()});let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn"+(F.isLive()?" is-on":""),Q.textContent="Live",Q.setAttribute("data-testid","history-live"),Q.addEventListener("click",()=>{if(B(),F.goLive())fe("",!1),ke()});let te=document.createElement("span");te.className="bp-history-label",te.setAttribute("data-testid","history-label");let be=F.activeRef();te.textContent=be?be.label||be.commit.slice(0,7):F.refs.length>0?`Live (${F.refs.length} saved)`:"Live",G.append(O,U,z,Q,te);let ve=document.createElement("div");ve.className="bp-history-group";let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(F.highlightEdits?" is-on":""),Ne.textContent="Highlight edits",Ne.disabled=F.refs.length===0,Ne.setAttribute("data-testid","history-highlight"),Ne.addEventListener("click",()=>{B(),F.toggleHighlight(),ke()});let Ee=document.createElement("div");Ee.className="bp-history-menu-wrap";let Ie=document.createElement("button");if(Ie.type="button",Ie.className="bp-v-btn"+(S||!F.isLive()?" is-on":""),Ie.disabled=F.refs.length===0,Ie.setAttribute("data-testid","history-compare"),Ie.setAttribute("aria-haspopup","menu"),Ie.setAttribute("aria-expanded",String(S)),Ie.textContent=be?`Compare: ${be.label||be.commit.slice(0,7)} ▾`:"Compare ▾",Ie.addEventListener("click",(Re)=>{Re.stopPropagation(),S=!S,ce()}),Ee.append(Ie),S&&F.refs.length>0){let Re=document.createElement("div");Re.className="bp-history-menu",Re.setAttribute("role","menu"),Re.setAttribute("data-testid","history-compare-menu");let _e=(De,Xe,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Xe),Ve.textContent=De,Ve.addEventListener("click",()=>{if(S=!1,B(),F.selectCommit(Xe)){if(F.isLive())fe("",!1);ke()}else ce()}),Re.append(Ve)};_e("Live (working tree)","",F.isLive());for(let De of F.refs)_e(De.label||De.commit.slice(0,7),De.commit,be?.commit===De.commit);Ee.append(Re)}ve.append(Ne,Ee),y.replaceChildren(G,ve)}async function Pe(R){if(!R)return;try{let G=await t.hub.rpc("viewer.refs",{thread:R});if(R!==f)return;F.setRefs(Array.isArray(G?.refs)?G.refs:[]),ce()}catch{if(R!==f)return;F.setRefs([]),ce()}}function ae(){return document.documentElement.classList.contains("light")}let Ae=new MutationObserver(()=>{let R=ae();re?.setTheme(R),ee?.setTheme(R),le?.setTheme(R)});Ae.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function de(R,G="",O=!1){if(R==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${R}`;let U=document.createElement("div");U.className="bp-v-state-card";let z=document.createElement("div");if(z.className="bp-v-state-msg",z.textContent=G,U.append(z),O){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn is-primary",Q.textContent=h("tools.retry","Retry"),Q.addEventListener("click",()=>void $e(!0)),U.append(Q)}p.replaceChildren(U)}function fe(R,G){m.textContent=R,m.hidden=!R,m.classList.toggle("is-warn",G)}function ue(){if(he)return xt(he);if(g==="board"||g==="3d")return xt(q.pcb);if(g==="schematic")return xt(q.sch);if(g==="mech")return xt(H);return""}function Z(){s.textContent=Ji(g);let R=ue();if(a.hidden=!R,r.hidden=!R,r.textContent=R,o.replaceChildren(),g==="mech"&&K.length>1){let O=document.createElement("select");O.className="bp-v-select",O.setAttribute("aria-label",h("viewer.mech","Mech"));for(let U of K){let z=document.createElement("option");z.value=U,z.textContent=xt(U),z.selected=U===H,O.append(z)}O.addEventListener("change",()=>{H=O.value,Z(),$e(!1)}),o.append(O)}if(yn(g)){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(Se?" is-on":""),O.textContent=T?.layerHead||"Layers",O.setAttribute("data-testid","viewer-layers-btn"),O.addEventListener("click",()=>{if(Se=!Se,d.hidden=!Se,O.classList.toggle("is-on",Se),Se)We("","")}),o.append(O)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="Fit",O.setAttribute("data-testid","viewer-fit-btn"),O.addEventListener("click",()=>{re?.fit(),ee?.fit()}),o.append(O)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(me&&!ie?" is-on":""),O.textContent=me?ie?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",O.setAttribute("data-testid","viewer-follow-btn"),O.addEventListener("click",()=>void nt()),o.append(O)}let G=document.createElement("button");G.type="button",G.className="bp-v-btn bp-v-close",G.textContent="✕",G.title=h("common.close","Close"),G.setAttribute("aria-label",h("common.close","Close")),G.setAttribute("data-testid","viewer-close-btn"),G.addEventListener("click",()=>t.closeViewer()),o.append(G)}function pe(){if(!T){d.replaceChildren();return}let R=document.createDocumentFragment(),G=document.createElement("div");G.className="bp-v-layers-head";let O=document.createElement("span");if(O.textContent=T.layerHead||"Layers",G.append(O),T.layerReset){let te=document.createElement("button");te.type="button",te.className="bp-v-btn",te.textContent="Reset",te.addEventListener("click",()=>void We("reset","")),G.append(te)}if(R.append(G),T.layerModes){let te=document.createElement("div");te.className="bp-v-layers-modes",["All","Dim","Only"].forEach((be,ve)=>{let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(T?.layerMode===ve?" is-on":""),Ne.textContent=be,Ne.addEventListener("click",()=>void We("mode",String(ve))),te.append(Ne)}),R.append(te)}let U=re?.presentColors()??new Map,z=(T.layerList||[]).concat(T.layerMarks||[]),Q=document.createElement("div");Q.className="bp-v-layers-list";for(let te of z){let be=U.get(te.layer);if(be===void 0)continue;let ve=document.createElement("div");ve.className="bp-v-layer-row"+(te.active?" is-focus":"");let Ne=document.createElement("input");Ne.type="checkbox",Ne.checked=te.on!==!1,Ne.addEventListener("change",()=>void We("toggle",String(te.layer)));let Ee=document.createElement("span");Ee.className="bp-v-layer-swatch";let Ie=be>>>16&255,Re=be>>>8&255,_e=be&255;Ee.style.background=te.on!==!1?`rgb(${Ie},${Re},${_e})`:`rgba(${Ie},${Re},${_e},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=te.name,De.addEventListener("click",()=>void We("pick",String(te.layer))),ve.append(Ne,Ee,De),Q.append(ve)}R.append(Q),d.replaceChildren(R)}async function We(R,G){if(!yn(g))return;let O=E;try{let U=await t.hub.rpc("viewer.layers",{kind:g,present:Be,off:Te,focus:ge,...R?{action:R,value:G}:{}});if(O!==E||!U)return;Te=Number(U.own)||0,ge=typeof U.focus==="string"?U.focus:"",T=U;let z={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(re?.setLayers(z),Z(),Se)pe()}catch{}}async function Ue(){if(!me||ie||!f||!t.hub.hasFeature("follow"))return;ie=!0,Z();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function nt(){if(!f||!t.hub.hasFeature("follow"))return;let R=!me?"on":ie?"resume":"off";try{let G=await t.hub.rpc("viewer.follow",{thread:f,action:R});if(me=!!G.on,ie=!!G.paused,Z(),G.on&&!G.paused&&G.focus&&Array.isArray(G.focus.box)&&G.focus.box.length===4&&(G.seq||0)>we)we=G.seq||we,re?.zoomToBoxMm([G.focus.box[0],G.focus.box[1],G.focus.box[2],G.focus.box[3]])}catch{}}function oe(){b.hidden=!0,b.replaceChildren(),re?.setHighlights([])}function lt(R){let G=R.split(";").filter(Boolean),O=G.shift()||R,U=[],z="",Q="";for(let Ee of G){if(Ee.startsWith("g="))continue;let Ie=Ee.indexOf("=");if(Ie>0){let Re=Ee.slice(0,Ie),_e=Ee.slice(Ie+1);if((Re==="ref"||Re==="symbol")&&!z)z=_e;if(Re==="net"&&!Q)Q=_e;U.push([Re,_e])}else U.push([Ee,""])}let te=document.createElement("div");te.className="bp-v-info-head";let be=document.createElement("span");be.className="bp-v-info-title",be.textContent=O;let ve=document.createElement("button");ve.type="button",ve.className="bp-v-info-x",ve.textContent="×",ve.setAttribute("aria-label","Clear selection"),ve.addEventListener("click",oe),te.append(be,ve);let Ne=document.createElement("div");Ne.className="bp-v-info-rows";for(let[Ee,Ie]of U){let Re=document.createElement("span");Re.className="bp-v-info-chip",Re.textContent=Ie?`${Ee}: ${Ie}`:Ee,Ne.append(Re)}return b.replaceChildren(te,...U.length>0?[Ne]:[]),b.hidden=!1,{ref:z||void 0,net:Q||void 0}}async function Je(R){if(!R){oe();return}let G=Array.from(k)[0]||"";if(!G)return;let O=E;try{let U=await t.hub.rpc("viewer.info",{key:G,at:R.at,idx:R.idx});if(O!==E)return;let z=typeof U.info==="string"?U.info:"";if(!z){oe();return}let{ref:Q,net:te}=lt(z),be=[];if(Q)be.push(["ref",Q]);if(te)be.push(["net",te]);let ve=[[R.at,R.idx]];for(let[Ne,Ee]of be){let Ie=await t.hub.rpc("viewer.probe",{key:G,name:Ne,value:Ee});if(O!==E)return;if(Array.isArray(Ie.matches))for(let Re of Ie.matches)ve.push(Re)}re?.setHighlights(ve)}catch{oe()}}function ct(){Y?.destroy(),Y=null,le?.destroy(),le=null,re?.destroy(),re=null,ee?.destroy(),ee=null,u.replaceChildren(),Se=!1,d.hidden=!0,b.hidden=!0,b.replaceChildren(),fe("",!1),de("none")}function Ye(){A=[],N=0}async function $e(R){if(!f||!g)return;let G=++E;if(k.clear(),C=!1,Ye(),ct(),Z(),je(),ce(),(g==="board"||g==="schematic")&&f)Pe(f);if(zs(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")Y=Fi(u,t,f,(z,Q)=>{if(g=z,he=Q,z==="mech")H=Q;$e(!1)});else if(g==="diff")Y=$i(u,t,f);else if(g==="review")Y=Gi(u,t,f);else if(g==="browser")Y=ji(u,t,f);else if(g==="terminal")de("loading","Loading terminal…"),import("/assets/terminal.js").then((Q)=>{if(G!==E)return;if(de("none"),Q?.mountTerminalPane)le=Q.mountTerminalPane(u,t,f,ae());else de("error","Terminal chunk missing",!0)},(Q)=>{if(G!==E)return;de("error",Q instanceof Error?Q.message:String(Q),!0)});return}if(de("loading","Loading…"),!q.root)try{let z=await t.hub.rpc("viewer.files",{thread:f});if(G!==E)return;q=z||{},Z()}catch{}if(g==="gerbers"&&q.hasGerbers===!1){de("empty","No Gerbers in this project",!1);return}let O=ae();if(g==="3d"||g==="mech")ee=new vn(u,{onStatus:(z,Q)=>{if(Q)de("none"),fe(z,!1);else if(z)de("loading",z);else de("none"),fe("",!1)},onUserMove:()=>void Ue()}),ee.setTheme(O);else if(g==="board"||g==="schematic"||g==="gerbers")re=new hn(u,{onPick:(z)=>void Je(z),onUserMove:()=>void Ue()}),re.setTheme(O);else{de("empty",`${Ji(g)} is not available in this viewer`,!1);return}let U={thread:f};if(R)U.force=!0;if(g==="mech"){if(K.length===0)try{let z=await t.hub.rpc("mech.list",{thread:f});if(G!==E)return;if(K=Array.isArray(z.parts)?z.parts:[],!H)H=z.primary||K[0]||"";Z()}catch(z){if(G!==E)return;de("error",z instanceof Error?z.message:String(z),!0);return}if(!H){de("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=H}else{if(U.kind=g,he&&(g==="board"||g==="schematic"))U.path=he;if(g==="3d"&&!R&&ee){let z=ee.keptToken();if(z)U.kept=z}if((g==="board"||g==="schematic"||g==="gerbers")&&!R&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(D.keys())}C=!0,I="",V="",X="",j="";try{let z=await t.hub.rpc("viewer.watch",U);if(G!==E)return;k=new Set(Array.isArray(z.keys)?z.keys:[]),C=!1;let Q=A;Ye();for(let te of Q)if(te.kind==="bin")Ge(te.buf);else Oe(te.key,te.none,te.retryable)}catch(z){if(G!==E)return;C=!1,k.clear(),Ye();let Q=z instanceof Error?z.message:String(z),te=/no gerbers|not in this project|another machine/i.test(Q);de(te?"empty":"error",Q,!te)}}function Oe(R,G,O){if(C){if(A.length{if(R.t==="plot"&&typeof R.none==="string"&&typeof R.key==="string")Oe(R.key,R.none,R.retryable===!0)}),Ft=At(()=>{if(g)Z()}),kt=(R)=>{if(R.key==="Escape"&&g&&!b.hidden)oe()};return window.addEventListener("keydown",kt),{open(R,G){if(G!==f){if(f=G,q={},K=[],H="",M.clear(),me=!1,ie=!1,we=0,Te=0,ge="",Be=0,T=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:G}).then((O)=>{if(G!==f)return;if(me=!!O.on,ie=!!O.paused,we=Number(O.seq)||0,g)Z()}).catch(()=>{})}if(R!==g)B(),F.goLive(),Te=0,ge="",Be=0,T=null;g=R,he="",$e(!1)},reconcileHas(R){if(g&&!Ks(g,R))t.closeViewer()},close(){if(E++,C=!1,B(),S=!1,I="",V="",X="",j="",F.goLive(),l.hidden=!0,y.hidden=!0,Ye(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",k.clear(),ct()}}}var Yi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(Yi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Yi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Js(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Xi(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Zi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function Ys(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Qi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,m,c);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let p=document.createElement("span");p.className="bp-top-state-lbl",p.textContent="STATE";let d=document.createElement("span");d.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(p,d,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=h("menu.settle","Settle"),E.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);let k=document.createElement("div");k.className="bp-menu-wrap";let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost bp-top-act",A.textContent="▾",A.title="Thread menu",A.setAttribute("aria-label","Thread menu"),A.setAttribute("data-testid","thread-menu-btn");let N=document.createElement("div");N.className="bp-popover bp-hidden",N.setAttribute("data-testid","thread-menu"),k.append(A,N),y.append(f,E,k);let M=document.createElement("div");M.className="bp-top-right";let D=document.createElement("button");D.type="button",D.className="bp-btn-ghost bp-top-act bp-hide-tablet",D.setAttribute("data-testid","improvements-btn");let q=document.createElement("span");q.textContent=h("gpui.improvements","Improvements"),D.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),q);let K=document.createElement("button");K.type="button",K.className="bp-cmd-box bp-hide-tablet",K.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let he=document.createElement("button");he.type="button",he.className="icon bp-top-icon",he.title=h("palette.settings","Settings"),he.setAttribute("aria-label",h("palette.settings","Settings")),he.setAttribute("data-testid","settings-btn"),he.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(D,K,H,he),t.append(n,i,u,y,M);let me=document.createElement("div");me.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Se=document.createElement("div");Se.className="bp-right-area bp-hidden",Se.setAttribute("data-testid","right-area");let Te=document.createElement("div");Te.className="bp-right-top";let ge=document.createElement("section");ge.className="bp-viewer-pane bp-hidden",ge.setAttribute("data-testid","viewer-pane"),Te.appendChild(ge),Se.appendChild(Te);let Be=document.createElement("nav");Be.className="bp-rail",Be.setAttribute("aria-label","Viewer rail"),Be.setAttribute("data-testid","viewer-rail"),me.append(ie,we,Se,Be),e.append(t,me);let T=new mn,re=null,ee=new Set,Y=0,le=null,F=[],x=[],S=[],I=[],V=[],X=[],j="",B=0,je=0,ke=null,ce=null,Pe="",ae=null,Ae=20,de={},fe=new Map;function ue(v,w){fe.delete(v),fe.set(v,w);while(fe.size>Ae){let L=fe.keys().next().value;if(L!==void 0)fe.delete(L);else break}}let Z=new cn(ie,{onSelectThread:(v)=>{if(v===j&&ke!==null){ie.classList.remove("bp-sidebar-open");return}Ee(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{Ee(v.thread)},onThreadAct:(v,w)=>{Qe(v,w)},onToggleSection:(v)=>{if(ee.has(v))ee.delete(v);else ee.add(v);be()},onToggleProjectFold:(v)=>{T.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>be()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let w=jt(v,!1);if(!w)return;if(w.kind==="thread"){Ee(w.id);return}if(w.kind!=="call")return;let L=yi(await T.rpc(w.method,w.params));if(L?.kind==="thread")Ee(L.id);be()},hasRoomView:!1,onAddProject:()=>Oe.open({mode:"folder"})}),pe=new Kt(we,{onLoadOlder:()=>{_e()},onGoToEntry:(v)=>{Re(v)},onAnswerAsk:(v,w)=>{T.rpc("ask.answer",{ask:v,answer:w}).catch((L)=>{oe.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!j)return;let w=B;T.rpc("thread.review",{thread:j,on:v}).then((L)=>{if(w===B)pe.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,w)=>{if(!j)return;if(v==="again"||v==="thread-again")T.rpc("thread.again",{thread:j,value:w}).catch(()=>{});else T.rpc("thread.act",{thread:j,action:v,value:w}).catch(()=>{})},onReplyEntry:(v)=>{if(!T.hasFeature("reply")){let w=(v.text||"").split(` +`)[0]?.slice(0,100)??"";if(w)oe.prependDraft(`> ${w} +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,w)=>{try{let L={entry:v,path:w};if(T.hasFeature("blobs"))L.metaOnly=!0;let P=await T.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function We(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,w){if(!j)return;let L=B,P=j;T.rpc(v,w).then((_)=>{if(L!==B||j!==P)return;if(_.thread){let ne=x.findIndex((ye)=>ye.id===_.thread.id);if(ne>=0)x[ne]=_.thread;else x.unshift(_.thread);Z.setData(F,x,S,I),pe.updateThreadMeta(_.thread),R(),oe.setState(!0,_.thread.state==="working")}}).catch((_)=>{if(L===B&&j===P)oe.showError(_ instanceof Error?_.message:"Could not change Plan mode")})}let nt,oe=new Jt(we,{onSend:(v,w)=>{En(v,w)},onRunCommand:(v)=>{xn(v)},onInterrupt:()=>{if(j)T.rpc("turn.interrupt",{thread:j}).catch(()=>{})},onQueryMentions:async(v,w)=>{try{return(await T.rpc("mentions.list",{q:v,kind:w,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=x.find((L)=>L.id===j)??null,w=We(v);if(!w||!j)return;if(w.interaction!=="plan")Ue("thread.planonce",{thread:j,on:!0});else if(w.once)Ue("thread.pick",{thread:j,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:j,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!j)return;if(v==="once")Ue("thread.planonce",{thread:j,on:!0});else if(v==="always")Ue("thread.pick",{thread:j,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:j,action:"interaction",value:"default"})}});nt=new dn(T,{getThreadId:()=>j,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function lt(){let v=Pe!=="",w=Je.isOpen();Se.classList.toggle("bp-hidden",!v&&!w),Se.classList.toggle("bp-has-viewer",v),Se.classList.toggle("bp-has-mgmt",w)}let Je=new nn(Te,Se,{hub:T,getThreadId:()=>j,getThreadGen:()=>B,onSendText:(v)=>{En(v)},onOpenChange:()=>lt()});function ct(v){let w=window.prompt("Rename thread",v.title||"");if(!w||!w.trim())return;T.rpc("thread.act",{thread:v.id,action:"rename",title:w.trim()}).then((L)=>{if(L.thread)x=x.map((P)=>P.id===L.thread.id?L.thread:P),R(),be()}).catch((L)=>{oe.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ee(v.id);break;case"rail":if(!j&&v.id!=="terminal")break;if(Pe===v.id)G();else O(v.id);break;case"thread-act":if(j)Qe(j,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let w=x.find((L)=>L.id===j);if(w)ct(w);break}case"prev-thread":case"next-thread":{let w=x.filter((ne)=>!ne.archived&&!ne.swarm);if(w.length<2)break;let L=w.findIndex((ne)=>ne.id===j),P=v.type==="next-thread"?1:-1,_=w[(L<0?0:L+P+w.length)%w.length];if(_)Ee(_.id);break}case"command":if(v.runDirectly)xn(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":kt();break;case"settings":Ke.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let $e=new sn(e,{getState:()=>({selectedThreadId:j,threads:x,projects:F,bots:S,railItems:V,commands:X}),onSearch:async(v)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:v,limit:20})},onExecute:Ye}),Oe=new Wt(e,{hub:T,onProjectAdded:(v)=>{if(be(),v.id)De(v.id)},onCloneDone:(v)=>{if(be(),v.thread)Ee(v.thread)}}),Ge=new an(Be,(v)=>{if(v==="commands"){$e.open();return}if(!j)return;if(Pe===v)G();else O(v)}),it=null,Ke=new rn(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,w)=>{await T.rpc("devices.page.act",{action:v,value:w})},onGetHome:()=>it,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>Dn(()=>{T.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=x.find((w)=>w.id===j);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let v=x.find((w)=>w.id===j);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let Ft=new ln(e,(v,w)=>w?T.rpc("thread.context.mcp",{thread:v,...w}):T.rpc("thread.context",{thread:v}));A.addEventListener("click",(v)=>{v.stopPropagation();let w=x.find((_)=>_.id===j);if(!w)return;if(!N.classList.contains("bp-hidden")){N.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ct(w)},{label:w.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(w.id,w.pinned?"unpin":"pin")}},{label:w.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(w.id,w.settled?"unsettle":"settle")}},{label:w.archived?"Unarchive":"Archive",run:()=>{Qe(w.id,w.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(w.id,"delete")}}];if(T.hasFeature("threadContext"))L.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Ft.open(w.id)});let P=document.createDocumentFragment();for(let _ of L){let ne=document.createElement("button");ne.type="button",ne.className="bp-popover-item"+(_.danger?" danger":""),ne.textContent=_.label,ne.addEventListener("click",()=>{N.classList.add("bp-hidden"),_.run()}),P.appendChild(ne)}N.replaceChildren(P),N.classList.remove("bp-hidden")}),document.addEventListener("click",()=>N.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let w=document.createElement("div");w.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let _=document.createElement("button");_.type="button",_.className="icon",_.textContent="×",_.addEventListener("click",()=>v.remove()),L.append(P,_);let ne=document.createElement("div");ne.className="bp-modal-body",ne.textContent="Loading…",w.append(L,ne),v.appendChild(w),v.addEventListener("click",(ye)=>{if(ye.target===v)v.remove()}),e.appendChild(v);try{let ye=await T.rpc("improvements.projects",{}),He=ye.projects??[];if(He.length===0){ne.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Le of He){let se=document.createElement("div");se.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Le.title||Le.name||Le.id;let tt=document.createElement("button");tt.type="button",tt.className=Le.id===ye.project?"primary":"",tt.textContent=Le.id===ye.project?"Active":"Select",tt.addEventListener("click",()=>{T.rpc("improvements.project",{project:Le.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Ze,tt),et.appendChild(se)}ne.replaceChildren(et)}catch(ye){ne.textContent=ye instanceof Error?ye.message:"Could not load Improvements."}}D.addEventListener("click",()=>{kt()}),K.addEventListener("click",()=>$e.open()),H.addEventListener("click",()=>$e.open()),he.addEventListener("click",()=>{Ke.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function R(){let v=x.find((P)=>P.id===j)??null,w=v?F.find((P)=>P.id===v.project):void 0;o.textContent=w?.title??"",r.classList.toggle("bp-hidden",!w),l.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let L=We(v);if(oe.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?h("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?h("gpui.planmode.top.planning","Planning"):L.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){d.className=`bp-dot ${Js(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),C.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;oe.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function G(v=!0){if(je++,Pe="",Ge.setActive(""),ge.classList.add("bp-hidden"),ae?.close(),lt(),v&&j&&T.getState()==="connected")T.rpc("viewer.watch",{thread:j,kind:""}).catch(()=>{})}function O(v){if(je++,Pe=v,Ge.setActive(v),ge.classList.remove("bp-hidden"),lt(),!ae&&typeof wn==="function")ae=wn(ge,{hub:T,getThreadId:()=>j,closeViewer:()=>G(!0)});if(ae)ae.open(v,j);else{let w=document.createElement("div");w.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let _=document.createElement("button");_.type="button",_.className="icon",_.textContent="×",_.addEventListener("click",()=>G(!0)),L.append(P,_);let ne=document.createElement("div");ne.className="bp-dim bp-viewer-msg",ne.textContent=`Viewer pane (${v}).`,w.append(L,ne),ge.replaceChildren(w)}}async function U(v,w){if(!v||!T.hasFeature("rail")){if(w===B)V=[],Ge.setItems([]);return}let L=++je;try{let P=await T.rpc("viewer.rail",{thread:v,page:Pe});if(w!==B||L!==je)return;let _=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(V=_,Ge.setItems(_),P.has){if(ae?.reconcileHas?.(P.has),Pe&&!Xi(P.has,Pe))G(!0)}}catch{if(w===B&&L===je)V=[],Ge.setItems([])}}function z(v){for(let w of v)if(w.kind==="threads"){for(let L of w.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(w.kind==="projects"){for(let L of w.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function Q(v,w){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===w))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((_)=>(_.nav||_.id)===w))return!0}return!1}function te(v){let w=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)w.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(w.length>0)F=w}async function be(){if(!T.hasFeature("sections"))return!1;let v=++Y;try{let w=await T.rpc("sidebar.sections",{open:Array.from(ee)});if(v!==Y)return!0;let L=Array.isArray(w.sections)?w.sections:[];return re=L,te(L),Z.setData(F,x,S,I),Z.setSections(L,S,I),R(),!0}catch{return!1}}function ve(){if(!T.hasFeature("sections"))return;if(le!==null)window.clearTimeout(le);le=window.setTimeout(()=>{le=null,be()},150)}async function Ne(){if(ke=null,T.hasFeature("bots"))try{let w=await T.rpc("bots.list",{});S=w.bots??[],I=w.rooms??[]}catch{}if(T.hasFeature("shell")){let w=await T.rpc("shell.sync",{have:de,settled:25}),L=new Set(w.removed??[]),P=new Set((w.projects??[]).map((_)=>_.id));if(L.size>0||P.size>0)F=[...F.filter((_)=>!L.has(_.id)&&!P.has(_.id)),...w.projects??[]],x=[...x.filter((_)=>!L.has(_.project)&&!P.has(_.project)),...w.threads??[]];else if(Array.isArray(w.threads)&&w.threads.length>0){let _=new Map(x.map((ne)=>[ne.id,ne]));for(let ne of w.threads)_.set(ne.id,ne);x=Array.from(_.values())}if(w.sections!==void 0){let _=Array.isArray(w.sections)?w.sections:Array.isArray(w.sections?.sections)?w.sections.sections:null;if(_)re=_,te(_)}if(w.h)de=w.h;Z.setData(F,x,S,I),Z.setSections(re,S,I)}else if(T.hasFeature("sections")){let[w,L]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(ee)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(x=L.threads??[],w&&Array.isArray(w.sections)){let P=w.sections;if(!P.some((ne)=>ne.kind==="projects"&&ne.rows.length>0)){let ne=P.find((ye)=>ye.kind==="projects"&&ye.fold&&ye.toggle&&(ye.count??0)>0);if(ne?.toggle&&!ee.has(ne.toggle)){ee.add(ne.toggle);let ye=await T.rpc("sidebar.sections",{open:Array.from(ee)}).catch(()=>null);if(ye&&Array.isArray(ye.sections))P=ye.sections}}re=P,te(P),Z.setData(F,x,S,I),Z.setSections(P,S,I)}else re=null,F=(await T.rpc("projects.list",{limit:100})).projects??[],Z.setSections(null,S,I),Z.setData(F,x,S,I);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{re=null;let[w,L]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);F=w.projects??[],x=L.threads??[],Z.setSections(null,S,I),Z.setData(F,x,S,I),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=j;if(!v){let w="";try{w=localStorage.getItem("bp.lastThread")||""}catch{}if(w&&(re&&Q(re,w)||x.some((L)=>L.id===w)))v=w;else if(re)v=z(re);if(!v)v=(x.find((P)=>!P.archived&&!P.swarm&&!P.settled)??x.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(re&&Q(re,v)||x.some((w)=>w.id===v)))await Ee(v);else j="",V=[],Ge.setItems([]),oe.setState(!1,!1),R()}async function Ee(v){if(j&&j!==v){nt.cancel();let Le=pe.getEntries();if(Le.length>0){let se=fe.get(j);ue(j,{entries:Le,ids:se?.ids??Le.map((Ze)=>Ze.id),olderCursor:ce,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??V,hashes:se?.hashes??{}})}}let w=++B;je++,Ve(null);let L=ke;if(ke=null,L!==null)T.rpc("unsubscribe",{sub:L}).catch(()=>{});j=v;let P=fe.get(v);ce=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}Z.setSelected(v),ie.classList.remove("bp-sidebar-open"),R();let _=x.find((Le)=>Le.id===v)??null;if(P)pe.setThread(_,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),V=P.rail,Ge.setItems(P.rail);else pe.setLoading(_),V=[],Ge.setItems([]);if(oe.setState(!0,_?.state==="working"),T.hasFeature("open")){let Le={};if(P){for(let[Me,pt]of Object.entries(P.hashes))Le[Me]=pt;for(let Me of P.entries)if(Me.h)Le[Me.id]=Me.h}let se;try{se=await T.rpc("thread.open",{thread:v,limit:40,have:Le})}catch(Me){if(w===B){let pt=Me instanceof Error&&Me.message?Me.message:"Could not load messages.";pe.setError(_,pt,()=>{Ee(v)})}return}if(w!==B){if(se.sub!==void 0&&se.sub!==null)T.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(ke=se.sub??null,se.thread){_=se.thread;let Me=x.findIndex((pt)=>pt.id===se.thread.id);if(Me>=0)x[Me]=se.thread;else x.unshift(se.thread);R(),oe.setState(!0,_.state==="working")}if("next"in se)ce=se.next??null;let Ze=new Map;if(P)for(let Me of P.entries)Ze.set(Me.id,Me);for(let Me of se.entries??[])Ze.set(Me.id,Me);let tt=se.ids??P?.ids??(se.entries??[]).map((Me)=>Me.id),kn=tt.map((Me)=>Ze.get(Me)).filter((Me)=>Boolean(Me)),dt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))dt=se.rail;else if(dt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(ae?.reconcileHas?.(se.rail.has),Pe&&!Xi(se.rail.has,Pe))G(!0)}}V=dt,Ge.setItems(dt);let $t=P?.review??null;if(T.hasFeature("reviewmode"))try{let Me=await T.rpc("thread.review",{thread:v});if(w!==B)return;$t=Me.review??null}catch{}if(w!==B)return;let Sn="unanswered"in se?se.unanswered??null:P?.unanswered??null,es=se.h??P?.hashes??{};if(ue(v,{entries:kn,ids:tt,olderCursor:ce,review:$t,unanswered:Sn,rail:dt,hashes:es}),pe.setThread(_,kn,Boolean(ce),$t,Sn),Ie(v,w),Pe)O(Pe);return}let ne;try{ne=await T.rpc("thread.entries",{thread:v,limit:40})}catch(Le){if(w===B){let se=Le instanceof Error&&Le.message?Le.message:"Could not load messages.";pe.setError(_,se,()=>{Ee(v)})}return}if(w!==B)return;if(ne.thread){let Le=x.findIndex((se)=>se.id===ne.thread.id);if(Le>=0)x[Le]=ne.thread;else x.unshift(ne.thread);R()}ce=ne.next??null;let ye=null;if(T.hasFeature("reviewmode"))try{let Le=await T.rpc("thread.review",{thread:v});if(w!==B)return;ye=Le.review??null}catch{}if(w!==B)return;let He=ne.entries??[],et=ne.unanswered??null;ue(v,{entries:He,ids:He.map((Le)=>Le.id),olderCursor:ce,review:ye,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),pe.setThread(_,He,Boolean(ce),ye,et);try{let se=(await T.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(w!==B){T.rpc("unsubscribe",{sub:se}).catch(()=>{});return}ke=se}}catch{}if(w!==B)return;if(U(v,w),Ie(v,w),Pe)O(Pe)}async function Ie(v,w){if(!v||!T.hasFeature("mgmt")){if(w===B)Je.clear();return}let L=x.find((_)=>_.id===v),P=L?.project?F.find((_)=>_.id===L.project)?.root??"":"";if(!P&&T.hasFeature("viewers"))try{let _=await T.rpc("viewer.files",{thread:v});if(w!==B)return;P=_.pcb||_.sch||_.root||""}catch{}if(w!==B)return;if(P)await Je.watchProject(P);else Je.clear()}async function Re(v){let w=B;for(let L=0;L<25&&w===B;L++){if(pe.goTo(v))return;if(!ce)return;let P=ce;if(await _e(),ce===P)return}}async function _e(){if(!j||!ce){pe.clearLoadingOlder();return}let v=B,w=j,L=ce;try{let P=await T.rpc("thread.entries",{thread:w,limit:40,before:L});if(v!==B||j!==w)return;ce=P.next??null,pe.prependEntries(P.entries??[],Boolean(ce))}catch{if(v===B)pe.clearLoadingOlder()}}async function De(v){try{let w=await T.rpc("thread.create",{project:v});if(w.thread)x=[w.thread,...x.filter((L)=>L.id!==w.thread.id)],Z.setData(F,x,S,I),be(),await Ee(w.thread.id),oe.focus()}catch(w){oe.showError(w instanceof Error?w.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` +`).map((w)=>w.trim()).find((w)=>w.length>0)??"").slice(0,200)}function Ve(v){Xe=v,oe.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Re(Xe.id)},()=>Ve(null))}async function En(v,w=[]){if(!j)return;let L=B,P=j,_=Ys(),ne=`local-${_}`,ye=Xe&&v.trim()&&T.hasFeature("reply")?Xe:null;if(ye)Ve(null);pe.upsertEntry({id:ne,kind:"user",text:v,at:Date.now(),clientId:_,...ye?{replyTo:{id:ye.id,quote:St(ye.text)}}:{},attachments:w.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:_};if(w.length>0)He.attachments=w;if(ye)He.replyTo={id:ye.id,text:ye.text};let et=await T.rpc("message.send",He);if(L!==B||j!==P)return;if(et.entry)pe.upsertEntry(et.entry)}catch(He){if(L===B&&j===P){if(pe.removeEntry(ne),oe.setDraft(v),ye&&!Xe)Ve(ye);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function xn(v){if(!j)return;let w=B,L=j;try{let P=await T.rpc("composer.run",{thread:L,text:v});if(w!==B||j!==L)return;if(P.error)oe.setDraft(v),oe.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")oe.setDraft(P.text);else if(P.kind==="project")Oe.open({mode:"folder"});else if(P.kind==="clone")Oe.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(w===B&&j===L)oe.setDraft(v),oe.showError(P instanceof Error?P.message:"Command refused")}}async function Qe(v,w){try{let L=await T.rpc("thread.act",{thread:v,action:w});if(L.thread){if(x=x.map((P)=>P.id===L.thread.id?L.thread:P),Z.setData(F,x,S,I),L.thread.id===j)pe.updateThreadMeta(L.thread),R()}be()}catch(L){oe.showError(L instanceof Error?L.message:`Action "${w}" not allowed`)}}function Cn(v,w){if(!v||!v.text||w-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return h("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function Lt(v){if(v==="connected")Z.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Cn(T.restarting,Date.now()))Z.setConnStatus(Cn(T.restarting,Date.now()),"");else if(v==="reconnecting")Z.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")Z.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Z.setConnStatus("Connecting…","")}At(()=>{Lt(T.getState()),q.textContent=h("gpui.improvements","Improvements"),he.title=h("palette.settings","Settings"),he.setAttribute("aria-label",h("palette.settings","Settings")),R(),Z.refreshLocale(),pe.refreshLocale(),oe.refreshLocale(),Ge.render(),Ke.refreshLocale(),Oe.refreshLocale()}),T.onState((v,w)=>{if(v==="connected"&&w){if(w.locale)Tn(w.locale);if(w.theme)Zi(w.theme);if(w.name)Z.setHostName(w.name);if(it=w.home??null,Z.setHome(it),Ke.isOpen())Ke.refresh();Lt(v);let L=typeof w.hubBack==="string"?String(w.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")Z.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Lt(T.getState()),6000)}catch{}if(oe.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(w.commands))X=w.commands,oe.setCommands(X);else X=[];Ne(),Oe.reconcile()}else nt.cancel(),Lt(v)}),T.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let w=v;if(w.k==="clone"||w.k==="clone.repos"||w.k==="clone.signin"){Oe.handleFrame(w);return}switch(w.k){case"project":{let L=w.project;if(!L)break;let P=F.findIndex((_)=>_.id===L.id);if(P>=0)F[P]=L;else F.unshift(L);Z.setData(F,x,S,I),R(),ve();break}case"thread":{let L=w.thread;if(!L)break;let P=x.findIndex((_)=>_.id===L.id);if(P>=0)x[P]=L;else x.unshift(L);if(Z.setData(F,x,S,I),L.id===j)pe.updateThreadMeta(L),R(),oe.setState(!0,L.state==="working");ve();break}case"thread.removed":{let L=String(w.id??"");x=x.filter((P)=>P.id!==L),Z.setData(F,x,S,I),ve();break}case"entry":{if(w.thread===j&&w.entry)pe.upsertEntry(w.entry);break}case"text":{if(w.thread===j)pe.appendLiveText(String(w.entry??""),String(w.append??""),Number(w.at??Date.now()));break}case"turn":{if(w.thread===j){let L=String(w.state??"idle");oe.setState(!0,L==="working"),U(j,B)}ve();break}case"btw":{if(w.thread===j)pe.showBtw(String(w.q??""),String(w.a??""));break}case"unanswered":{if(w.thread===j)pe.setUnanswered(w.unanswered??null);break}case"theme":{if(typeof w.theme==="string")Zi(w.theme);break}case"home":{if(it=w.home??null,Z.setHome(it),Ke.isOpen())Ke.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let w=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(w==="k"||v.shiftKey&&w==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Oe.isOpen())Oe.escape();else if(Ke.isOpen())Ke.close();else if(pe.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Qi);else Qi(); diff --git a/web/dist/manifest.json b/web/dist/manifest.json index ca32e4880c..e48828b70c 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 200464, + "totalAssetGzipBytes": 200991, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -278,13 +278,13 @@ "web/src/inflate.ts": "bc10ed23159668193d6de6d582e60baf009cae0a619018f0588f836a77dde831", "web/src/logout.ts": "9d29482c4671deee1e868ee477b123e067a4c22f7d8ac30b4c2420cf71b8ebe2", "web/src/md.ts": "c606d1ec598b3ce132c7cc9366383dacafc3fcb71c0fccd97b41ec0e19a96c78", - "web/src/mgmt-model.ts": "5135cce33f870d5b45b9fd8c2eb91f62fa7d274cd961cd523ed0df599893c955", - "web/src/mgmt.ts": "29d968b9601dda45a85dd70f378c4e15f2abb3108124f5974c33b02b84c1ce2d", + "web/src/mgmt-model.ts": "89af6290740690cac0bd1fd986098ede9d5bbed96b22f80c5a176f7e625f18ea", + "web/src/mgmt.ts": "1a2ae80790f345a38377833ae2b93724ce3fd1d2ba600e6d44faaa26c7b98744", "web/src/pair.html": "cf7b94703316f910718356e9ff8e99e088b68211db39b5200213b623c9275f6e", "web/src/pair.ts": "af07d19224043f8176f8cd2298d00b6806248eee453fd2f287c183e71a08179b", "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", - "web/src/plan-canvas.ts": "be46faf9e3207600516dfac12d93ba6cf8798ba65615a3eb24ff3dfacc0f8507", + "web/src/plan-canvas.ts": "fdd06b67480d731ac7baa4f22de1ad72f9fdc6388198408dcd87efedc7126eb6", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "7b4d8be26fabc6c2a0b8af94a64572a0e3c1e589bf079bfa58c8985a8acd984a", @@ -317,9 +317,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 333026, - "gzipBytes": 93878, - "sha256": "c418ffce805c12fcd0733b3515d603e838904c7558daf32207a781a24b13c63d" + "bytes": 334768, + "gzipBytes": 94405, + "sha256": "659b1c4303b47a29f1cc08dfbc83ef0e75fe8dd4ff554c3581ee7642ba5686db" }, "assets/favicon-light.svg": { "bytes": 1207, diff --git a/web/src/mgmt-model.ts b/web/src/mgmt-model.ts index 4b624a654f..934d3677dc 100644 --- a/web/src/mgmt-model.ts +++ b/web/src/mgmt-model.ts @@ -874,3 +874,49 @@ export function planLayoutLabels( } return out; } + +export function unwrapPlanGetPanel(res: unknown): PlanInfo | null { + if (!res || typeof res !== "object") return null; + const r = res as Record; + if (r.panel && typeof r.panel === "object") return r.panel as PlanInfo; + if (r.result && typeof r.result === "object") { + const nested = (r.result as Record).panel; + if (nested && typeof nested === "object") return nested as PlanInfo; + } + return null; +} + +export function planAllCanvasLayers(layers: PlanLayer[], copperLayers?: PlanCopperLayer[]): PlanLayer[] { + if (!copperLayers || copperLayers.length === 0) return layers; + const byName = new Map(); + for (const l of layers) { + if (l.layer) byName.set(l.layer, l); + } + const out: PlanLayer[] = []; + const seen = new Set(); + for (const cl of copperLayers) { + if (!cl.layer) continue; + seen.add(cl.layer); + const existing = byName.get(cl.layer); + if (existing) { + out.push(existing); + } else { + out.push({ + layer: cl.layer, + index: cl.index, + title: cl.title || `L${cl.index} · ${cl.layer}`, + subtitle: cl.subtitle || "", + role: cl.role, + status: "proposed", + done: 0, + approved: 0, + total: 0, + items: [], + }); + } + } + for (const l of layers) { + if (l.layer && !seen.has(l.layer)) out.push(l); + } + return out; +} diff --git a/web/src/mgmt.ts b/web/src/mgmt.ts index 75f434bbe1..9ceb558ced 100644 --- a/web/src/mgmt.ts +++ b/web/src/mgmt.ts @@ -18,6 +18,7 @@ import { money, pkgName, planBusColor, + planAllCanvasLayers, planDefaultLayerPair, planDone, planMark, @@ -27,6 +28,7 @@ import { refsFit, stockSummary, tierWords, + unwrapPlanGetPanel, type BomInfo, type BomLine, type BomUndoRecord, @@ -38,6 +40,7 @@ import { type MgmtStateInfo, type PlanBand, type PlanBoardGeom, + type PlanCopperLayer, type PlanInfo, type PlanItem, type PlanLayer, @@ -97,6 +100,7 @@ export class MgmtStrip { private planOptimistic = new Map>(); private planOptimisticRev: number | undefined = undefined; private planHydratedKey = ""; + private planHydrateAskedKey = ""; private planHydratedBoard: PlanBoardGeom | null = null; private planHydratedDraw: { bands?: PlanBand[]; regions?: PlanRegion[] } | null = null; private planNoteOpen = false; @@ -164,6 +168,7 @@ export class MgmtStrip { this.planOptimistic.clear(); this.planOptimisticRev = undefined; this.planHydratedKey = ""; + this.planHydrateAskedKey = ""; this.planHydratedBoard = null; this.planHydratedDraw = null; this.planNoteOpen = false; @@ -204,11 +209,13 @@ export class MgmtStrip { this.planOptimistic.clear(); this.planOptimisticRev = undefined; this.planHydratedKey = ""; + this.planHydrateAskedKey = ""; this.planHydratedBoard = null; this.planHydratedDraw = null; this.planNoteOpen = false; this.planCanvas?.destroy(); this.planCanvas = null; + this.planCommitFields = null; this.fabStatus = ""; this.lifeSelectedKey = ""; this.lifePartSamples = null; @@ -401,7 +408,15 @@ export class MgmtStrip { body.appendChild(this.renderFab()); break; } + const keepCanvasFocus = + this.planCanvas !== null && + document.activeElement instanceof HTMLElement && + this.panelEl.contains(document.activeElement) && + this.planCanvas.root.contains(document.activeElement); this.panelEl.replaceChildren(body); + if (keepCanvasFocus) { + this.planCanvas?.root.focus({ preventScroll: true }); + } } // ---- BOM panel ---- @@ -1000,15 +1015,17 @@ export class MgmtStrip { } const hydKey = `${this.project}:${d.revision ?? 0}`; - if (d.board_trimmed && this.planHydratedKey !== hydKey && this.project) { - this.planHydratedKey = hydKey; + if (d.board_trimmed && this.planHydrateAskedKey !== hydKey && this.project) { + this.planHydrateAskedKey = hydKey; const gen = this.watchGen; const proj = this.project; - void this.cb.hub.rpc<{ panel?: PlanInfo }>("plan.get", { pro: proj, board: true }) + void this.cb.hub.rpc("plan.get", { pro: proj, board: true }) .then((res) => { - if (gen !== this.watchGen || proj !== this.project || !res?.panel) return; - this.planHydratedBoard = res.panel.board ?? null; - this.planHydratedDraw = res.panel.draw ?? null; + const panel = unwrapPlanGetPanel(res); + if (gen !== this.watchGen || proj !== this.project || !panel) return; + this.planHydratedKey = hydKey; + this.planHydratedBoard = panel.board ?? null; + this.planHydratedDraw = panel.draw ?? null; this.render(); }) .catch(() => {}); @@ -1394,24 +1411,25 @@ export class MgmtStrip { } } + const canvasLayers = planAllCanvasLayers(mergedLayers, d.copper_layers); const activeLayers = this.planGridMode === "all" - ? mergedLayers.map((l) => l.layer) + ? canvasLayers.map((l) => l.layer) : this.planGridMode === "single" ? [ - this.planShownLayers.find((n) => mergedLayers.some((l) => l.layer === n)) ?? - planDefaultLayerPair(mergedLayers)[0] ?? - mergedLayers[0]?.layer ?? + this.planShownLayers.find((n) => canvasLayers.some((l) => l.layer === n)) ?? + planDefaultLayerPair(canvasLayers)[0] ?? + canvasLayers[0]?.layer ?? "", ].filter(Boolean) - : (this.planShownLayers.length > 0 && this.planShownLayers.every((n) => mergedLayers.some((l) => l.layer === n)) + : (this.planShownLayers.length > 0 && this.planShownLayers.every((n) => canvasLayers.some((l) => l.layer === n)) ? this.planShownLayers.slice(0, 2) - : planDefaultLayerPair(mergedLayers)); + : planDefaultLayerPair(canvasLayers)); - if (this.planViewMode !== "list" && mergedLayers.length > 1) { + if (this.planViewMode !== "list" && canvasLayers.length > 1) { const layerBar = document.createElement("div"); layerBar.className = "bp-plan-layerbar"; - for (const l of mergedLayers) { + for (const l of canvasLayers) { const isShown = activeLayers.includes(l.layer); layerBar.appendChild( mkChip(l.title || l.layer, isShown, `mgmt-plan-layerpill-${l.layer}`, () => { @@ -1453,8 +1471,12 @@ export class MgmtStrip { wireFields.outline = [fields.outline, ...reg.holes]; } } + const baseRev = typeof d.revision === "number" ? d.revision : undefined; this.render(); - sendPlan("plan.update", { ops: [{ op: "set", id, fields: wireFields }] }); + sendPlan("plan.update", { + ops: [{ op: "set", id, fields: wireFields }], + ...(baseRev !== undefined ? { base: baseRev } : {}), + }); }; this.planCommitFields = commitItemFields; @@ -1621,8 +1643,12 @@ export class MgmtStrip { if (!txt) return; ni.value = ""; this.planNoteOpen = false; + const baseRev = typeof d.revision === "number" ? d.revision : undefined; this.render(); - sendPlan("plan.update", { ops: [{ op: "note", id: selItem!.id, text: txt }] }); + sendPlan("plan.update", { + ops: [{ op: "note", target: selItem!.id, text: txt }], + ...(baseRev !== undefined ? { base: baseRev } : {}), + }); }); ins.appendChild(nf); } @@ -1816,7 +1842,8 @@ export class MgmtStrip { board: rawBoard, bands: mergedBands, regions: mergedRegions, - layers: mergedLayers, + layers: canvasLayers, + copperLayers: d.copper_layers, }, twoCols, ); diff --git a/web/src/plan-canvas.ts b/web/src/plan-canvas.ts index a30892a977..9606c1542b 100644 --- a/web/src/plan-canvas.ts +++ b/web/src/plan-canvas.ts @@ -3,6 +3,7 @@ // paint order, hit testing, pan/zoom synchronization, and direct vertex/midpoint/keyboard steering. import { t } from "./i18n"; import { + planAllCanvasLayers, planBandStrokePx, planBusColor, planDefaultLayerPair, @@ -20,6 +21,7 @@ import { type PlanBand, type PlanBoardGeom, type PlanCamera, + type PlanCopperLayer, type PlanHit, type PlanLayer, type PlanRegion, @@ -37,6 +39,7 @@ export interface PlanCanvasStateSnapshot { bands: PlanBand[]; regions: PlanRegion[]; layers: PlanLayer[]; + copperLayers?: PlanCopperLayer[]; } export interface PlanCanvasCallbacks { @@ -169,7 +172,7 @@ export class PlanFloorplannerCanvas { private selectedVertex: { id: string; idx: number } | null = null; private drag: | { layer: string; kind: "pan"; lastX: number; lastY: number } - | { layer: string; kind: "vertex"; id: string; isPlane: boolean; idx: number; pts: Array<[number, number]> } + | { layer: string; kind: "vertex"; id: string; isPlane: boolean; idx: number; pts: Array<[number, number]>; origPts: Array<[number, number]>; moved: boolean } | null = null; private downPos: { x: number; y: number } | null = null; private rafPending = 0; @@ -202,26 +205,27 @@ export class PlanFloorplannerCanvas { } private visibleLayers(s: PlanCanvasStateSnapshot): PlanLayer[] { - if (s.layers.length === 0) return []; - if (s.gridMode === "all") return s.layers; + const all = planAllCanvasLayers(s.layers, s.copperLayers); + if (all.length === 0) return []; + if (s.gridMode === "all") return all; if (s.gridMode === "single") { const target = - s.shownLayers.find((n) => s.layers.some((l) => l.layer === n)) ?? - planDefaultLayerPair(s.layers)[0] ?? - s.layers[0]?.layer; - const found = s.layers.find((l) => l.layer === target); + s.shownLayers.find((n) => all.some((l) => l.layer === n)) ?? + planDefaultLayerPair(all)[0] ?? + all[0]?.layer; + const found = all.find((l) => l.layer === target); return found ? [found] : []; } const pairNames = - s.shownLayers.length > 0 && s.shownLayers.every((n) => s.layers.some((l) => l.layer === n)) + s.shownLayers.length > 0 && s.shownLayers.every((n) => all.some((l) => l.layer === n)) ? s.shownLayers.slice(0, 2) - : planDefaultLayerPair(s.layers); + : planDefaultLayerPair(all); const out: PlanLayer[] = []; for (const name of pairNames) { - const found = s.layers.find((l) => l.layer === name); + const found = all.find((l) => l.layer === name); if (found) out.push(found); } - return out.length > 0 ? out : s.layers.slice(0, 2); + return out.length > 0 ? out : all.slice(0, 2); } public update(snapshot: PlanCanvasStateSnapshot, twoCols: boolean): void { @@ -397,11 +401,12 @@ export class PlanFloorplannerCanvas { private attachPointerListeners(canvas: HTMLCanvasElement, layer: string): void { canvas.addEventListener("contextmenu", (e) => e.preventDefault()); + canvas.addEventListener("dblclick", () => this.fitAll()); canvas.addEventListener("pointerdown", (e) => { const s = this.state; if (!s) return; - this.root.focus(); + this.root.focus({ preventScroll: true }); const rect = canvas.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; @@ -428,24 +433,21 @@ export class PlanFloorplannerCanvas { if (hit?.kind === "vertex") { const pts = this.getItemPts(hit.id, hit.isPlane); + const origPts = pts.map((p) => [p[0], p[1]] as [number, number]); this.selectedVertex = { id: hit.id, idx: hit.idx }; - this.cb.onSelect(hit.id); - this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: hit.idx, pts: pts.map((p) => [p[0], p[1]]) }; + this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: hit.idx, pts: pts.map((p) => [p[0], p[1]]), origPts, moved: false }; this.scheduleDraw(); } else if (hit?.kind === "midpoint") { const curPts = this.getItemPts(hit.id, hit.isPlane); + const origPts = curPts.map((p) => [p[0], p[1]] as [number, number]); const newPts = planInsertVertex(curPts, hit.segIdx, hit.pos, hit.isPlane); const insertedIdx = hit.isPlane && hit.segIdx + 1 >= curPts.length ? newPts.length - 1 : Math.min(hit.segIdx + 1, newPts.length - 1); - this.cb.onSelect(hit.id); this.selectedVertex = { id: hit.id, idx: insertedIdx }; this.patchLocalItem(hit.id, hit.isPlane, newPts); this.cb.onOptimisticPatch(hit.id, { [hit.isPlane ? "outline" : "path"]: newPts }); - this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: insertedIdx, pts: newPts }; + this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: insertedIdx, pts: newPts, origPts, moved: true }; this.scheduleDraw(); } else { - if (hit && (hit.kind === "band" || hit.kind === "region")) { - this.cb.onSelect(hit.id); - } this.selectedVertex = null; this.drag = { layer, kind: "pan", lastX: mx, lastY: my }; } @@ -469,9 +471,13 @@ export class PlanFloorplannerCanvas { this.scheduleDraw(); return; } + if (this.downPos && Math.hypot(e.clientX - this.downPos.x, e.clientY - this.downPos.y) < 1.5 && !this.drag.moved) { + return; + } const cam = this.getCam(layer, w, h); const [wx, wy] = planPxToWorld(cam, mx, my, w, h); const rounded: [number, number] = [Math.round(wx * 1000) / 1000, Math.round(wy * 1000) / 1000]; + this.drag.moved = true; this.drag.pts[this.drag.idx] = rounded; const copy = this.drag.pts.map((p) => [p[0], p[1]] as [number, number]); this.patchLocalItem(this.drag.id, this.drag.isPlane, copy); @@ -483,10 +489,11 @@ export class PlanFloorplannerCanvas { const cam = this.getCam(layer, w, h); const hit = planHitTest(s.bands, s.regions, layer, s.selectedId, cam, w, h, mx, my); const prevId = this.hover?.hit ? ("id" in this.hover.hit ? this.hover.hit.id : "") : ""; + const prevKind = this.hover?.hit.kind ?? ""; const nextId = hit ? hit.id : ""; this.hover = hit ? { layer, hit } : null; - canvas.style.cursor = hit?.kind === "vertex" || hit?.kind === "midpoint" ? "pointer" : hit ? "pointer" : "crosshair"; - if (prevId !== nextId || hit?.kind !== this.hover?.hit.kind) { + canvas.style.cursor = hit ? "pointer" : "crosshair"; + if (prevId !== nextId || (hit?.kind ?? "") !== prevKind) { this.syncHoverHud(layer); this.scheduleDraw(); } @@ -500,6 +507,21 @@ export class PlanFloorplannerCanvas { } }); + const cancelActiveDrag = (restoreOrig: boolean): void => { + const d = this.drag; + if (!d || d.layer !== layer) return; + this.drag = null; + this.downPos = null; + if (restoreOrig && d.kind === "vertex") { + const copy = d.origPts.map((p) => [p[0], p[1]] as [number, number]); + this.patchLocalItem(d.id, d.isPlane, copy); + this.cb.onOptimisticPatch(d.id, { [d.isPlane ? "outline" : "path"]: copy }); + } + this.scheduleDraw(); + }; + canvas.addEventListener("pointercancel", () => cancelActiveDrag(true)); + canvas.addEventListener("lostpointercapture", () => cancelActiveDrag(false)); + canvas.addEventListener("pointerup", (e) => { const s = this.state; const d = this.drag; @@ -510,11 +532,11 @@ export class PlanFloorplannerCanvas { canvas.releasePointerCapture(e.pointerId); } if (d && d.kind === "vertex" && d.layer === layer) { - this.cb.onCommitFields(d.id, { [d.isPlane ? "outline" : "path"]: d.pts }); - return; - } - if (e.detail >= 2) { - this.fitAll(); + if (d.moved) { + this.cb.onCommitFields(d.id, { [d.isPlane ? "outline" : "path"]: d.pts }); + } else { + this.scheduleDraw(); + } return; } if (s && down && Math.hypot(e.clientX - down.x, e.clientY - down.y) < 4.5) { diff --git a/web/test/mgmt.test.ts b/web/test/mgmt.test.ts index c7bcd319ff..f67f919e95 100644 --- a/web/test/mgmt.test.ts +++ b/web/test/mgmt.test.ts @@ -30,6 +30,8 @@ import { planRemoveVertex, planDefaultLayerPair, planLayoutLabels, + planAllCanvasLayers, + unwrapPlanGetPanel, } from "../src/mgmt-model"; describe("Management strip pure model", () => { @@ -215,5 +217,18 @@ describe("Management strip pure model", () => { [], ); expect(labels.map((l) => l.text)).toEqual(["U1", "U2"]); + + expect(unwrapPlanGetPanel(null)).toBeNull(); + expect(unwrapPlanGetPanel({ result: { panel: { revision: 3 } } })?.revision).toBe(3); + expect(unwrapPlanGetPanel({ panel: { revision: 5 } })?.revision).toBe(5); + const mergedAll = planAllCanvasLayers( + [{ layer: "F.Cu", role: "signal", items: [{ id: "c1", kind: "corridor" }] }], + [ + { layer: "F.Cu", index: 1, role: "signal", title: "L1 · TOP" }, + { layer: "In1.Cu", index: 2, role: "power", title: "L2 · GND", subtitle: "Faces TOP across 40 µm" }, + ], + ); + expect(mergedAll.map((l) => l.layer)).toEqual(["F.Cu", "In1.Cu"]); + expect(mergedAll[1].title).toBe("L2 · GND"); }); }); From 36fe406ff7faf94765996ff33509d3672e66842d Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 22:35:24 -0500 Subject: [PATCH 4/5] plan: harden drag deferral, hydration fencing, symlink sidecar checks, and live hole preservation --- native/gpui/src/screens/mgmt.rs | 2 +- native/gpui/src/screens/mgmt_plan_canvas.rs | 73 +++++++++++++-------- native/host/src/data/ext.rs | 51 ++++++++++---- native/host/src/plan/geom.rs | 19 ++++-- native/host/src/plan/mod.rs | 63 +++++++++++++++++- native/host/src/plan/panel.rs | 25 ++++++- web/dist/assets/app.js | 36 +++++----- web/dist/manifest.json | 14 ++-- web/src/mgmt-model.ts | 18 +++++ web/src/mgmt.ts | 71 ++++++++++++++------ web/src/plan-canvas.ts | 25 +++++-- web/test/mgmt.test.ts | 7 ++ 12 files changed, 299 insertions(+), 105 deletions(-) diff --git a/native/gpui/src/screens/mgmt.rs b/native/gpui/src/screens/mgmt.rs index 4eb9cc9361..8e47a62b1c 100644 --- a/native/gpui/src/screens/mgmt.rs +++ b/native/gpui/src/screens/mgmt.rs @@ -131,7 +131,7 @@ pub fn answered(app: &mut Backplane, id: u64, reply: &Value, cx: &mut Context bool { (BOARD_TAG_BASE..=BOARD_TAG_END).contains(&id) } +static BOARD_TAG_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); pub const COMPACT_PANEL_W: u64 = 400; pub const EXPANDED_PANEL_W: u64 = 880; const SIDE_BY_SIDE_MIN_W: f32 = 540.0; @@ -160,8 +163,10 @@ pub struct State { pub optimistic: HashMap, pub optimistic_at: Option, pub last_rev: Option, + pub hydrated_req_tag: Option, pub hydrated_req_key: String, pub hydrated_req_pro: String, + pub hydrated_rev: Option, pub hydrated_key: String, pub hydrated_board: Option, pub hydrated_draw: Option, @@ -189,8 +194,10 @@ impl Default for State { optimistic: HashMap::new(), optimistic_at: None, last_rev: None, + hydrated_req_tag: None, hydrated_req_key: String::new(), hydrated_req_pro: String::new(), + hydrated_rev: None, hydrated_key: String::new(), hydrated_board: None, hydrated_draw: None, @@ -215,8 +222,10 @@ impl State { self.optimistic.clear(); self.optimistic_at = None; self.last_rev = None; + self.hydrated_req_tag = None; self.hydrated_req_key.clear(); self.hydrated_req_pro.clear(); + self.hydrated_rev = None; self.hydrated_key.clear(); self.hydrated_board = None; self.hydrated_draw = None; @@ -688,7 +697,9 @@ pub fn resolved_board_and_draw(app: &Backplane, d: &Value) -> (Value, Value) { let pro = &app.screens.mgmt.project; let rev = d["revision"].as_u64().unwrap_or(0); let key = format!("{pro}:{rev}"); - let use_hyd = ui.hydrated_key == key; + let use_hyd = ui.hydrated_board.is_some() + && ui.hydrated_key.starts_with(&format!("{pro}:")) + && (ui.hydrated_key == key || ui.hydrated_rev.map_or(false, |hr| hr >= rev)); let board = if use_hyd { ui.hydrated_board.clone().unwrap_or_else(|| d["board"].clone()) } else { @@ -715,20 +726,38 @@ pub fn unwrap_board_panel(reply: &Value) -> Option<&Value> { } } -pub fn board_answered(app: &mut Backplane, reply: &Value, cx: &mut Context) { - let Some(panel) = unwrap_board_panel(reply).cloned() else { +pub fn accept_hydration_reply(req_tag: Option, reply_tag: u64, cur_pro: &str, reply: &Value) -> Option<(u64, Value, Value)> { + if req_tag != Some(reply_tag) { + return None; + } + let panel = unwrap_board_panel(reply)?; + let r = if reply["result"].is_object() { &reply["result"] } else { reply }; + if let Some(rp) = r["pro"].as_str().filter(|s| !s.is_empty()) { + if rp != cur_pro { + return None; + } + } + let rev = panel["revision"].as_u64().unwrap_or(0); + Some((rev, panel["board"].clone(), panel["draw"].clone())) +} + +pub fn board_answered(app: &mut Backplane, tag: u64, reply: &Value, cx: &mut Context) { + let pro = app.screens.mgmt.project.clone(); + let Some((rev, board, draw)) = accept_hydration_reply(app.screens.mgmt.plan_ui.hydrated_req_tag, tag, &pro, reply) else { return; }; - let pro = app.screens.mgmt.project.clone(); let ui = &mut app.screens.mgmt.plan_ui; if !ui.hydrated_req_pro.is_empty() && ui.hydrated_req_pro != pro { return; } - let rev = panel["revision"].as_u64().unwrap_or(0); + if ui.hydrated_rev.map_or(false, |prev| rev < prev) { + return; + } + ui.hydrated_rev = Some(rev); ui.hydrated_key = format!("{pro}:{rev}"); ui.hydrated_req_key = ui.hydrated_key.clone(); - ui.hydrated_board = Some(panel["board"].clone()); - ui.hydrated_draw = Some(panel["draw"].clone()); + ui.hydrated_board = Some(board); + ui.hydrated_draw = Some(draw); cx.notify(); } @@ -748,9 +777,11 @@ pub fn sync_revision_and_hydrate(app: &mut Backplane, d: &Value) { } let key = format!("{pro}:{}", rev.unwrap_or(0)); if d["board_trimmed"] == true && ui.hydrated_req_key != key && !pro.is_empty() { + let tag = BOARD_TAG_BASE + (BOARD_TAG_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 0xffff); + ui.hydrated_req_tag = Some(tag); ui.hydrated_req_key = key; ui.hydrated_req_pro = pro.clone(); - let _ = app.tx.try_send(Command::Ask("plan.get".into(), json!({"pro": pro, "board": true}), BOARD_TAG)); + let _ = app.tx.try_send(Command::Ask("plan.get".into(), json!({"pro": pro, "board": true}), tag)); } } @@ -768,23 +799,8 @@ pub fn apply_optimistic(app: &mut Backplane, id: &str, patch: Value) { pub fn commit_item_fields(app: &mut Backplane, id: &str, fields: Value, cx: &mut Context) { apply_optimistic(app, id, fields.clone()); let d = app.screens.mgmt.data("plan"); - let base = d["revision"].as_u64(); - let mut wire_fields = fields; - if let Some(outer) = wire_fields.get("outline").cloned() { - if outer.as_array().and_then(|a| a.first()).and_then(|p| p.as_array()).and_then(|p| p.first()).and_then(Value::as_f64).is_some() { - let (_, draw) = resolved_board_and_draw(app, &d); - if let Some(holes) = draw["regions"].as_array().into_iter().flatten().find(|r| r["id"] == id).and_then(|r| r["holes"].as_array()).filter(|h| !h.is_empty()) { - let mut rings = Vec::with_capacity(1 + holes.len()); - rings.push(outer); - rings.extend(holes.iter().cloned()); - if let Some(obj) = wire_fields.as_object_mut() { - obj.insert("outline".into(), Value::Array(rings)); - } - } - } - } - let mut payload = json!({"ops": [{"op": "set", "id": id, "fields": wire_fields}]}); - if let Some(b) = base { + let mut payload = json!({"ops": [{"op": "set", "id": id, "fields": fields}]}); + if let Some(b) = d["revision"].as_u64() { payload["base"] = json!(b); } mgmt_plan::send(app, "plan.update", payload, cx); @@ -2032,8 +2048,11 @@ mod tests { #[test] fn board_hydration_unwraps_result_and_all_layers_includes_empty_copper() { assert!(unwrap_board_panel(&json!({"t": "reply", "ok": false, "error": "nope"})).is_none()); - let wrapped = json!({"t": "reply", "ok": true, "result": {"panel": {"revision": 4, "board": {}, "draw": {}}}}); + let wrapped = json!({"t": "reply", "ok": true, "result": {"pro": "/p/a.kicad_pro", "panel": {"revision": 4, "board": {}, "draw": {}}}}); assert_eq!(unwrap_board_panel(&wrapped).unwrap()["revision"], 4); + assert!(accept_hydration_reply(Some(BOARD_TAG_BASE + 1), BOARD_TAG_BASE, "/p/a.kicad_pro", &wrapped).is_none(), "stale tag rejected"); + assert!(accept_hydration_reply(Some(BOARD_TAG_BASE), BOARD_TAG_BASE, "/p/b.kicad_pro", &wrapped).is_none(), "wrong project rejected"); + assert_eq!(accept_hydration_reply(Some(BOARD_TAG_BASE), BOARD_TAG_BASE, "/p/a.kicad_pro", &wrapped).unwrap().0, 4); let direct = json!({"panel": {"revision": 9}}); assert_eq!(unwrap_board_panel(&direct).unwrap()["revision"], 9); diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index 5f571d029c..585232659d 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -744,8 +744,24 @@ fn too_wide_plan_root(p: &std::path::Path) -> bool { p.parent().is_none() || home.as_ref().map_or(false, |h| h == p) } +fn check_plan_sidecar(roots: &[std::path::PathBuf], real_home: &std::path::Path, sidecar: &std::path::Path) -> Result<(), &'static str> { + if let Ok(md) = std::fs::symlink_metadata(sidecar) { + if md.file_type().is_symlink() { + return Err("that routing plan is not shared"); + } + let real_sidecar = crate::plat::fs::canonicalize(sidecar).map_err(|_| "that routing plan is not shared")?; + if real_sidecar.starts_with(real_home) || !roots.iter().any(|r| real_sidecar.starts_with(r)) { + return Err("that routing plan is not shared"); + } + } + Ok(()) +} + fn check_browser_plan_path(roots: &[std::path::PathBuf], home: &std::path::Path, raw: &str) -> Result<(std::path::PathBuf, std::path::PathBuf), &'static str> { let full = crate::files::share::local_path(raw).ok_or("that path is not in a project")?; + if std::fs::symlink_metadata(&full).is_ok_and(|md| md.file_type().is_symlink()) { + return Err("that path is not shared"); + } let real = crate::plat::fs::canonicalize(&full).map_err(|_| "no such file or project")?; let real_home = crate::plat::fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf()); if real.starts_with(&real_home) || !roots.iter().any(|r| real.starts_with(r)) { @@ -760,23 +776,19 @@ fn check_browser_plan_path(roots: &[std::path::PathBuf], home: &std::path::Path, if pcb_raw.is_empty() { return Err("no KiCad board in this project"); } - let real_pcb = crate::plat::fs::canonicalize(std::path::Path::new(&pcb_raw)).map_err(|_| "no such board")?; + let pcb_path = std::path::Path::new(&pcb_raw); + if std::fs::symlink_metadata(pcb_path).is_ok_and(|md| md.file_type().is_symlink()) { + return Err("that board is not shared"); + } + let real_pcb = crate::plat::fs::canonicalize(pcb_path).map_err(|_| "no such board")?; if real_pcb.starts_with(&real_home) || !roots.iter().any(|r| real_pcb.starts_with(r)) { return Err("that board is not in a project"); } if !real_pcb.parent().map_or(false, |p| roots.iter().any(|r| p.starts_with(r))) { return Err("that board is not in a project"); } - let sidecar = real_pcb.with_extension("kicad_plan"); - if let Ok(md) = std::fs::symlink_metadata(&sidecar) { - if md.file_type().is_symlink() { - return Err("that routing plan is not shared"); - } - let real_sidecar = crate::plat::fs::canonicalize(&sidecar).map_err(|_| "that routing plan is not shared")?; - if real_sidecar.starts_with(&real_home) || !roots.iter().any(|r| real_sidecar.starts_with(r)) { - return Err("that routing plan is not shared"); - } - } + check_plan_sidecar(roots, &real_home, &pcb_path.with_extension("kicad_plan"))?; + check_plan_sidecar(roots, &real_home, &real_pcb.with_extension("kicad_plan"))?; Ok((real, real_pcb)) } @@ -813,10 +825,10 @@ async fn sanitize_browser_plan_params(hub: &Arc, m: &str, p: &Value) -> Res if let Some(o) = q.as_object_mut() { o.remove("pro"); o.remove("path"); - if real.extension().and_then(|e| e.to_str()) == Some("kicad_pcb") { - o.insert("path".into(), json!(real_pcb.to_string_lossy())); - } else { + if matches!(m, "plan.focus" | "plan.enable") && real.extension().and_then(|e| e.to_str()) != Some("kicad_pcb") { o.insert("pro".into(), json!(real.to_string_lossy())); + } else { + o.insert("path".into(), json!(real_pcb.to_string_lossy())); } } Ok(q) @@ -867,6 +879,17 @@ mod pick_tests { std::fs::write(&outside_plan, "{}").unwrap(); std::os::unix::fs::symlink(&outside_plan, &sidecar).unwrap(); assert!(check_browser_plan_path(&roots, &home, pro.to_str().unwrap()).is_err()); + + // Symlinked .kicad_pcb alias inside project with malicious .kicad_plan beside it is also rejected + let sub = proj.join("sub"); + std::fs::create_dir_all(&sub).unwrap(); + let sub_pro = sub.join("alias.kicad_pro"); + let sub_pcb = sub.join("alias.kicad_pcb"); + let sub_sidecar = sub.join("alias.kicad_plan"); + std::fs::write(&sub_pro, "{}").unwrap(); + std::os::unix::fs::symlink(&pcb, &sub_pcb).unwrap(); + std::os::unix::fs::symlink(&outside_plan, &sub_sidecar).unwrap(); + assert!(check_browser_plan_path(&roots, &home, sub_pro.to_str().unwrap()).is_err()); } let _ = std::fs::remove_dir_all(&base); } diff --git a/native/host/src/plan/geom.rs b/native/host/src/plan/geom.rs index 499cfee7c9..a157c12453 100644 --- a/native/host/src/plan/geom.rs +++ b/native/host/src/plan/geom.rs @@ -775,15 +775,17 @@ pub fn guides_for_plan(board: &CachedBoard, plan: &Value) -> HashMap = to_refs.iter().copied().collect(); f_sorted.sort_unstable(); t_sorted.sort_unstable(); - 'fallback: for fr in f_sorted { - for tr in &t_sorted { - if segs.len() >= MAX_CORRIDOR_GUIDES || total_segs + segs.len() >= MAX_TOTAL_GUIDES { + let f_pts: Vec<[f64; 2]> = f_sorted.into_iter().filter_map(|r| part_center.get(r).copied()).take(MAX_CORRIDOR_GUIDES).collect(); + let t_pts: Vec<[f64; 2]> = t_sorted.into_iter().filter_map(|r| part_center.get(r).copied()).take(MAX_CORRIDOR_GUIDES).collect(); + let mut checks = 0usize; + 'fallback: for a in &f_pts { + for b in &t_pts { + if checks >= MAX_CORRIDOR_GUIDES * 4 || segs.len() >= MAX_CORRIDOR_GUIDES || total_segs + segs.len() >= MAX_TOTAL_GUIDES { break 'fallback; } - if let (Some(a), Some(b)) = (part_center.get(fr), part_center.get(tr)) { - if (a[0] - b[0]).hypot(a[1] - b[1]) > 0.5 { - segs.push([a[0], a[1], b[0], b[1]]); - } + checks += 1; + if (a[0] - b[0]).hypot(a[1] - b[1]) > 0.5 { + segs.push([a[0], a[1], b[0], b[1]]); } } } @@ -940,5 +942,8 @@ mod tests { let g2 = guides_for_plan(&dummy, &p_many); assert_eq!(g1["cm"].len(), 18); assert_eq!(g1, g2); + + let p_missing = json!({"corridors": [{"id": "cmiss", "from": (0..50).map(|i| format!("M{i}")).collect::>(), "to": (0..50).map(|i| format!("N{i}")).collect::>()}]}); + assert!(guides_for_plan(&dummy, &p_missing).is_empty()); } } diff --git a/native/host/src/plan/mod.rs b/native/host/src/plan/mod.rs index eb87ea6a7f..9e364de618 100644 --- a/native/host/src/plan/mod.rs +++ b/native/host/src/plan/mod.rs @@ -613,16 +613,55 @@ fn update_saved_plan_sync(pcb: &str, base: Option, ops: &[NormOp]) -> Resul Ok((plan["revision"].clone(), touched)) } +fn merge_preserved_holes_into_ops(plan: &Value, ops: &[NormOp]) -> Vec { + let planes = plan["planes"].as_array(); + ops.iter().map(|nop| { + if !nop.preserve_holes { + return nop.wire.clone(); + } + let mut wire = nop.wire.clone(); + let id = wire["id"].as_str().unwrap_or(""); + let new_len = wire["fields"]["outline"].as_array().map_or(0, Vec::len); + if new_len == 1 { + if let Some(old_raw) = planes.and_then(|ps| ps.iter().find(|p| p["id"] == id)).and_then(|p| p.get("outline")) { + if let Ok(Value::Array(old_rings)) = norm_outline(old_raw) { + if old_rings.len() > 1 { + let mut merged = Vec::with_capacity(old_rings.len()); + merged.push(wire["fields"]["outline"][0].clone()); + merged.extend(old_rings[1..].iter().cloned()); + if let Some(flds) = wire["fields"].as_object_mut() { + flds.insert("outline".into(), Value::Array(merged)); + } + } + } + } + } + wire + }).collect() +} + /// The person's steering edits (the Plan canvas/inspector): sends KiCad's `UpdatePlan` as the person when open, /// else updates `.kicad_plan` atomically on disk and broadcasts the settled panel update. pub async fn update(hub: &Arc, pcb: &str, base: Option, ops: &[Value]) -> Result { let norm_ops = normalize_person_ops_checked(ops)?; - let wire_ops: Vec = norm_ops.iter().map(|n| n.wire.clone()).collect(); let pro = crate::files::kicad::project::read(&Path::new(pcb).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()).pro; if let Some(r) = crate::files::kicad::embed::gui_route(&pro) { + let needs_holes = norm_ops.iter().any(|n| n.preserve_holes); + let live_plan = if needs_holes { + Some(read_plan(hub, None, pcb, false).await?) + } else if base.is_none() { + read_plan(hub, None, pcb, false).await.ok() + } else { + None + }; let rev = match base { Some(b) => b, - None => read_plan(hub, None, pcb, false).await.ok().and_then(|p| p["revision"].as_u64()).unwrap_or(0), + None => live_plan.as_ref().and_then(|p| p["revision"].as_u64()).unwrap_or(0), + }; + let wire_ops: Vec = if let Some(lp) = live_plan.as_ref().filter(|_| needs_holes) { + merge_preserved_holes_into_ops(lp, &norm_ops) + } else { + norm_ops.iter().map(|n| n.wire.clone()).collect() }; let msg = json!({"board": spec(pcb), "base": rev, "ops": Value::Array(wire_ops).to_string()}); let o = crate::files::kicad::embed::gui_call_as(&r, &format!("{NS}UpdatePlan"), msg, &crate::files::kicad::coedit::client_name(&crate::files::kicad::coedit::Who::Person)).await; @@ -717,7 +756,7 @@ impl RpcHandler for Rpc { _ if p["board"] == true || p["panel"] == true => { let (plan, live) = panel::plan_now(hub, &pcb).await; let pan = if plan.is_null() { Value::Null } else { panel::data_with_board(&plan, &events::open_asks(&pcb), live, Some(&pcb)) }; - Ok(json!({"plan": plan, "panel": pan})) + Ok(json!({"plan": plan, "panel": pan, "pro": path})) } _ => read_plan(hub, None, &pcb, true).await, } @@ -940,4 +979,22 @@ mod tests { assert_eq!(disk_after["notes"][0]["target"], "c1"); let _ = std::fs::remove_dir_all(&dir); } + + #[test] fn live_merge_preserved_holes_keeps_authoritative_holes_and_allows_explicit_clear() { + let hole1 = json!([[2.0, 2.0], [3.0, 2.0], [3.0, 3.0]]); + let hole2 = json!([[6.0, 6.0], [7.0, 6.0], [7.0, 7.0]]); + let live_plan = json!({ + "planes": [{"id": "p1", "outline": [[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], hole1, hole2]}] + }); + let flat = normalize_person_ops_checked(&[json!({"op": "set", "id": "p1", "outline": [[0.0, 0.0], [12.0, 0.0], [12.0, 10.0]]})]).unwrap(); + let merged = merge_preserved_holes_into_ops(&live_plan, &flat); + let rings = merged[0]["fields"]["outline"].as_array().unwrap(); + assert_eq!(rings.len(), 3); + assert_eq!(rings[1], hole1); + assert_eq!(rings[2], hole2); + + let clear = normalize_person_ops_checked(&[json!({"op": "set", "id": "p1", "outline": [[[0.0, 0.0], [12.0, 0.0], [12.0, 10.0]]]})]).unwrap(); + let cleared = merge_preserved_holes_into_ops(&live_plan, &clear); + assert_eq!(cleared[0]["fields"]["outline"].as_array().unwrap().len(), 1); + } } diff --git a/native/host/src/plan/panel.rs b/native/host/src/plan/panel.rs index 1bdb5077b7..2936b69b3b 100644 --- a/native/host/src/plan/panel.rs +++ b/native/host/src/plan/panel.rs @@ -271,6 +271,21 @@ pub fn fit_info_budget(d: &mut Value) { break; } } + if d.to_string().len() > BUDGET { + if let Some(obj) = d.as_object_mut() { + for k in ["copper_layers", "elsewhere", "asks"] { + if obj.contains_key(k) { + obj.insert(k.into(), json!([])); + } + if serde_json::Value::Object(obj.clone()).to_string().len() <= BUDGET { + return; + } + } + if obj.contains_key("keys_note") { + obj.insert("keys_note".into(), json!("")); + } + } + } } /// The board of a project's .kicad_pro. @@ -281,7 +296,12 @@ pub async fn plan_now(hub: &Arc, pcb: &str) -> (Value, bool) { let pro = crate::files::kicad::project::read(&Path::new(pcb).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default()).pro; if crate::files::kicad::embed::gui_route(&pro).is_some() { if let Ok(p) = super::read_plan(hub, None, pcb, true).await { return (p, true) } } let f = Path::new(pcb).with_extension("kicad_plan"); - (tokio::task::spawn_blocking(move || std::fs::read_to_string(f).ok().and_then(|t| serde_json::from_str::(&t).ok())).await.ok().flatten().unwrap_or(Value::Null), false) + (tokio::task::spawn_blocking(move || { + if std::fs::symlink_metadata(&f).is_ok_and(|md| md.file_type().is_symlink()) { + return None; + } + std::fs::read_to_string(f).ok().and_then(|t| serde_json::from_str::(&t).ok()) + }).await.ok().flatten().unwrap_or(Value::Null), false) } /// Publish the panel for a project (its .kicad_pro): the open KiCad's plan, else the saved one. pub async fn publish(hub: &Arc, pro: &str) { @@ -465,6 +485,9 @@ mod tests { huge_plan["notes"] = json!((0..400).map(|i| json!({"id": format!("n{i}"), "text": "a".repeat(250)})).collect::>()); huge_plan["corridors"] = json!((0..250).map(|i| json!({"id": format!("c{i}"), "group": "g1", "layer": "F.Cu", "path": [[1, 1], [2, 2]], "status": "proposed"})).collect::>()); let mut huge_d = data(&huge_plan, &[], false); + huge_d["copper_layers"] = json!((0..500).map(|i| json!({"layer": format!("In{i}.Cu"), "subtitle": "x".repeat(80)})).collect::>()); + huge_d["asks"] = json!((0..200).map(|i| json!({"id": format!("a{i}"), "note": "y".repeat(120)})).collect::>()); + huge_d["elsewhere"] = json!((0..200).map(|i| json!({"name": format!("b{i}"), "rel": "z".repeat(120)})).collect::>()); assert!(huge_d.to_string().len() > 58 * 1024); fit_info_budget(&mut huge_d); assert!(huge_d.to_string().len() <= 58 * 1024); diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index 20c3a82a7e..aac07d28b5 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function Gt(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function Ln(e){return e==="done"||e==="failed"||e==="cancelled"}function An(e,t){if(!e||e.id!==t.id)return!0;let n=Ln(e.state),i=Ln(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Pn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Nn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ut=ts(),Ut=new Set,Ot=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ot.has(t))Ot.set(t,e);function ts(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Mn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ut}Mn();function At(e){return Ut.add(e),()=>{Ut.delete(e)}}function Tn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ut;if(ut=n,Mn(),i)for(let s of Ut)s(ut);return i}function h(e,t,n){let s=(mt[ut]||mt.en||{})[e]??mt.en?.[e]??t??e;return Nn(s,n)}function xe(e){if(!e)return"";let t=Ot.get(e);if(!t)return e;return h(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function ns(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function is(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Vt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let a=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(xe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(is(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(ns(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(xe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Wt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",h("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Vt(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),a=J("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,J("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(J("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=J("div","bp-ap-foot");this.cloneBtn=Fe(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(J("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",xe(t.hint))),t.state==="signedout"){let a=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(xe(t.error)))}else if(t){let r=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=Fe(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let m=J("label","bp-ap-name");m.append(J("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let c=J("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(c),n.push(m),!t.ok&&t.error)n.push(this.errLine(xe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Vt(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Gt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=xe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Gt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=xe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Pn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let r=J("div","bp-ap-phase",xe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(J("div","bp-ap-detail bp-dim",t.detail));let m=J("div","bp-ap-foot"),c=Fe(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),m.append(c),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=J("div","bp-ap-err",xe(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=J("div","bp-ap-foot"),o=Fe(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=Fe(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let l=Fe(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=J("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let u of r)c.appendChild(J("li","",xe(u)));a.push(c)}let o=J("div","bp-ap-foot"),l=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=Fe(l,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=J("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(J("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",xe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ss(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ht(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ss(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i=(e.ended??0)}function Pn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Nn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ht=ns(),Ot=new Set,Ut=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function ns(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Mn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ht}Mn();function At(e){return Ot.add(e),()=>{Ot.delete(e)}}function Tn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ht;if(ht=n,Mn(),i)for(let s of Ot)s(ht);return i}function u(e,t,n){let s=(mt[ht]||mt.en||{})[e]??mt.en?.[e]??t??e;return Nn(s,n)}function xe(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return u(t,e)}function Q(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function $e(e,t="",n){let i=Q("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function is(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ss(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Vt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=Q("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=Q("div","bp-fb-head");this.upBtn=$e("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=u("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",u("web.clone.up","Up")),this.pathInput=Q("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=Q("div","bp-fb-list"),this.errEl=Q("div","bp-ap-err bp-hidden");let a=Q("div","bp-ap-foot");this.actBtn=$e("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(Q("div","bp-fb-empty",u("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(xe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=u("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(Q("div","bp-fb-empty",u("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=$e("","bp-fb-row",()=>{this.go(ss(this.path,n))});i.append(Q("span","bp-fb-icon","▸"),Q("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(is(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(xe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Wt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=Q("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=Q("div","bp-modal bp-ap"),n=Q("div","bp-modal-head"),i=Q("h2","",u("sidebar.add.project","Add project")),s=$e("×","icon",()=>this.close());s.title=u("common.close","Close"),s.setAttribute("aria-label",u("common.close","Close")),n.append(i,s),this.tabsEl=Q("div","bp-ap-tabs"),this.bodyEl=Q("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=u("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=$e(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",u("gpui.e.open.folder","Open folder")),e("clone",u("web.clone.tab","Clone from git")))}renderFolder(){let e=new Vt(this.host.hub,(t)=>u("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=Q("div","bp-ap-form"),n=Q("div","bp-ap-repo"),i=Q("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=u("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",u("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=Q("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=Q("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=Q("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=Q("label","bp-ap-check"),a=Q("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,Q("span","",u("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(Q("div","bp-ap-first bp-dim",u("web.clone.first","First message: {text}",{text:this.firstText})));let o=Q("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=Q("div","bp-ap-foot");this.cloneBtn=$e(u("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=$e("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=Q("div","bp-ap-sug-top");if(o.append(Q("span","bp-ap-sug-name",s.name)),s.private)o.append(Q("span","bp-ap-tag",u("web.clone.private","private")));if(r.append(o),s.description)r.append(Q("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(Q("div","bp-ap-sug-note",u("web.clone.loading","Loading…")));else if(t.hint){let s=Q("div","bp-ap-sug-note");if(s.append(Q("span","",xe(t.hint))),t.state==="signedout"){let a=$e(u("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(xe(t.error)))}else if(t){let r=Q("div","bp-ap-where"),o=Q("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=$e(u("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let m=Q("label","bp-ap-name");m.append(Q("span","bp-ap-lbl",u("web.clone.folder.name","Folder name")));let c=Q("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),m.append(c),n.push(m),!t.ok&&t.error)n.push(this.errLine(xe(t.error)));else if(t.same)n.push(Q("div","bp-ap-note bp-dim",u("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=Q("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=$e(u("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Vt(this.host.hub,(i)=>u("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Gt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=xe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Gt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=xe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Pn(e))this.goTo(e)}renderJobView(){this.jobEl=Q("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=Q("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?u("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?u("web.clone.stopped","Stopped cloning {repo}",{repo:i}):u("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[Q("div","bp-ap-job-title",s)];if(t.state==="running"){let r=Q("div","bp-ap-phase",xe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=Q("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=Q("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(Q("div","bp-ap-detail bp-dim",t.detail));let m=Q("div","bp-ap-foot"),c=$e(u("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),m.append(c),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=Q("div","bp-ap-err",xe(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=Q("div","bp-ap-foot"),o=$e(u("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=$e(u("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let l=$e(u("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=Q("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let h of r)c.appendChild(Q("li","",xe(h)));a.push(c)}let o=Q("div","bp-ap-foot"),l=t.thread?u("web.clone.open.thread","Open the thread"):u("web.clone.open.project","Open the project"),m=$e(l,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=Q("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(Q("div","bp-dim",u("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(Q("div","",u("web.clone.signin.enter","Enter this code on GitHub:")));let i=Q("div","bp-ap-code-row"),s=Q("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=$e(this.copied?u("web.clone.copied","Copied"):u("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=Q("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(Q("div","bp-ok",u("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(Q("div","bp-ap-err",xe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function as(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ut(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=as(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(c).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),p.append(d,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=c,f.appendChild(g),u.append(p,f),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",ht(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ht(l,m.join(` -`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));ht(o,r[l])}t.appendChild(o)}return t}var Bn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qt(e){return e<10000000000?e*1000:e}function as(e){if(!e)return"";return new Date(qt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function rs(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function _t(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Kt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!_t(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!_t(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(_t(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=h("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let u=as(e.at);if(t)c.textContent=u,i.append(s,...m?[o]:[],c);else{let p=n&&e.at?rs(qt(e.at)-qt(n)):"",d=u?p?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:p}):h("web.chat.finished","Finished {time}",{time:u}):"";c.textContent=e.live?h("web.chat.streaming","Streaming…"):d,i.append(c,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,c.appendChild(u),a.tool.summary){let p=document.createElement("span");p.className="bp-tool-summary",p.textContent=a.tool.summary,c.appendChild(p)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${c.id}`);let p=document.createElement("div");if(p.className="bp-ask-q",p.textContent=c.question,u.appendChild(p),c.state==="open"){let d=document.createElement("div");if(d.className="bp-ask-opts",c.options&&c.options.length>0)for(let b of c.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,b.id)),d.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=h("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=h("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(c.id,b.value.trim())}),d.append(b,y)}u.appendChild(d)}else{let d=document.createElement("div");d.className="bp-ask-answered",d.textContent=h("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),u.appendChild(d)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!m&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let p=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};c.addEventListener("click",p),c.addEventListener("keydown",(d)=>{if(d.key==="Enter"||d.key===" ")d.preventDefault(),p()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.textContent=a.text;else c.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(m&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let p=document.createElement("img");p.className="bp-reply-img",p.src=u.previewUrl,p.alt=u.name||"attachment",c.appendChild(p)}else if(u.path||u.name){let p=document.createElement("span");p.className="bp-tool-pill",p.textContent=u.name||u.path||"image",c.appendChild(p)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.images){let p=document.createElement("img");p.className="bp-reply-img",p.alt=u;let d=`${a.id}|${u}`,b=this.imageCache.get(d);if(b)p.src=b;else this.cb.onLoadImage(a.id,u).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(d,f),p.src=f});c.appendChild(p)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):xe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let u=h("common.copy","Copy"),p=document.createElement("span");p.textContent=u,c.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),p),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),p.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),p.textContent=u},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let u=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),p=document.createElement("button");if(p.type="button",p.className="primary",p.setAttribute("data-testid","plan-implement"),p.textContent=u?.label&&u.label!=="Implement"?xe(u.label):h("approval.implement","Implement"),p.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),c.appendChild(p),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(y)}let d=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=d?.label&&d.label!=="Dismiss"?xe(d.label):h("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,d?.id??"dismiss")}),c.appendChild(b),i.appendChild(c),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=h("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let E=()=>{let A=f.value.trim();if(!A)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${A}`)},C=()=>{this.closePlanRevise()};y.addEventListener("keydown",(A)=>{if(A.key==="Escape")A.preventDefault(),A.stopPropagation(),C()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(A)=>{if(A.key==="Enter"&&!A.shiftKey)A.preventDefault(),E()}),g.addEventListener("click",E);let k=document.createElement("button");k.type="button",k.className="bp-btn-ghost",k.textContent=h("common.cancel","Cancel"),k.addEventListener("click",C),y.append(f,g,k),i.appendChild(y)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var In="http://www.w3.org/2000/svg",Rn=4,jn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(In,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(In,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function zt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Hn(){return Pt(["M6 4l14 8-14 8z"])}function os(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Jt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let m=l.clipboardData?.items;if(!m)return;let c=[];for(let u=0;u0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=os(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?Hn():zt()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?Hn():zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let c=(u,p,d,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(p?" active":""),y.textContent=u,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(d)),y};m.append(c(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(m)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} -${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!jn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Rn){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:Rn}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Dn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var ls=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&ls.has(t.id))}function Un(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var cs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ds=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function On(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(cs.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ds.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function Vn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Wn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function _n(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Yt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function qn(e){return e.state==="routed"||e.state==="verified"}function Kn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function zn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Jn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Yn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Xn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Xt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Zn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Zt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Fn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],$n=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Qn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Fn[Qn(i)%Fn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return $n[Qn(e)%$n.length]}function ei(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function ze(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ti(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ni(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[m,c]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function ii(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function si(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Qt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ps(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+m*r,u=i+m*o;return(e-c)*(e-c)+(t-u)*(t-u)}function Gn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(l-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function en(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,l){if(i){for(let p of e){if(p.layer!==n||p.id!==i||p.locked)continue;let d=p.path??[];for(let b=0;b=3)for(let b=0;b=0;p--){let d=t[p];if(d.layer!==n)continue;let b=d.outline??[];if(!Gn(c,u,b))continue;if(!(d.holes??[]).some((f)=>Gn(c,u,f)))return{kind:"region",id:d.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,l=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function ai(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[c,u]=ze(t,m.b[0],m.b[1],n,i),[p,d]=ze(t,m.b[2],m.b[3],n,i),b=Math.abs(p-c),y=Math.abs(d-u);if(b<13||y<9)continue;let f=(c+p)*0.5,g=(u+d)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,c)=>c.score-m.score);let o=[],l=[];for(let m of r){let c=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((p)=>!(c[2]<=p[0]||c[0]>=p[2]||c[3]<=p[1]||c[1]>=p[3])))o.push(c),l.push({text:m.text,cx:m.cx,cy:m.cy})}return l}function ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Rt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}var oi="#111917",ms="#16201d",us="rgba(212, 224, 219, 0.92)",hs="rgba(61, 80, 73, 0.72)",bs="rgba(82, 107, 97, 0.85)",gs="rgba(143, 163, 155, 0.88)",li="#f59e0b",fs="#eef5f2",ci="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function vs(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function ys(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function ws(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class tn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Rt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??rt(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):rt(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ei(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=h("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,m);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let p=document.createElement("canvas");p.className="bp-plan-card-canvas",p.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let d=document.createElement("div");d.className="bp-plan-hover-hud bp-hidden",u.append(p,d);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=p.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(p,e.layer);let g={layer:e.layer,el:t,canvas:p,ctx:y,legendEl:b,okBtn:l,noBtn:m,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:d,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=ws(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let l=document.createElement("button");l.type="button";let m=this.state?.selectedId===o.id;l.className="bp-plan-legend-chip"+(m?" active":"");let c=document.createElement("span");c.className="bp-plan-legend-sw",c.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,l.append(c,u),l.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(l)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height),c=this.getCam(t,l,m),u=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o);if(i.button===2){if(u?.kind==="vertex"){let p=this.getItemPts(u.id,u.isPlane),d=Qt(p,u.idx,u.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(u.id,{[u.isPlane?"outline":"path"]:d})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},u?.kind==="vertex"){let p=this.getItemPts(u.id,u.isPlane),d=p.map((b)=>[b[0],b[1]]);this.selectedVertex={id:u.id,idx:u.idx},this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:u.idx,pts:p.map((b)=>[b[0],b[1]]),origPts:d,moved:!1},this.scheduleDraw()}else if(u?.kind==="midpoint"){let p=this.getItemPts(u.id,u.isPlane),d=p.map((f)=>[f[0],f[1]]),b=si(p,u.segIdx,u.pos,u.isPlane),y=u.isPlane&&u.segIdx+1>=p.length?b.length-1:Math.min(u.segIdx+1,b.length-1);this.selectedVertex={id:u.id,idx:y},this.patchLocalItem(u.id,u.isPlane,b),this.cb.onOptimisticPatch(u.id,{[u.isPlane?"outline":"path"]:b}),this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:y,pts:b,origPts:d,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let k=this.getCam(t,l,m);this.setCam(t,ti(k,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let y=this.getCam(t,l,m),[f,g]=Bt(y,r,o,l,m),E=[Math.round(f*1000)/1000,Math.round(g*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let C=this.drag.pts.map((k)=>[k[0],k[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:C}),this.scheduleDraw();return}let c=this.getCam(t,l,m),u=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o),p=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=this.hover?.hit.kind??"",b=u?u.id:"";if(this.hover=u?{layer:t,hit:u}:null,e.style.cursor=u?"pointer":"crosshair",p!==b||(u?.kind??"")!==d)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=(i)=>{let s=this.drag;if(!s||s.layer!==t)return;if(this.drag=null,this.downPos=null,i&&s.kind==="vertex"){let a=s.origPts.map((r)=>[r[0],r[1]]);this.patchLocalItem(s.id,s.isPlane,a),this.cb.onOptimisticPatch(s.id,{[s.isPlane?"outline":"path"]:a})}this.scheduleDraw()};e.addEventListener("pointercancel",()=>n(!0)),e.addEventListener("lostpointercapture",()=>n(!1)),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,m=i.clientY-o.top,c=Math.max(1,o.width),u=Math.max(1,o.height),p=this.getCam(t,c,u),d=It(s.bands,s.regions,t,s.selectedId,p,c,u,l,m);if(d&&(d.kind==="band"||d.kind==="region"))this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);else if(!d)this.cb.onSelect("")}}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),m=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ni(m,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=Qt(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(d,b)=>ze(a,d,b,n,i);e.fillStyle=oi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((d)=>d.length>=3);if(e.fillStyle=ms,o.length>0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let d of l){let b=d.outline??[];if(b.length<3)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ys(d.state||"proposed",y,f),E=ft(d.net||d.id,d.color||"");e.beginPath();for(let C=0;C0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),p=[];for(let d of u){for(let b of d.from??[])p.push(b);for(let b of d.to??[])p.push(b)}e.fillStyle=gs,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let d of ai(c,a,n,i,p))e.fillText(d.text,d.cx,d.cy);for(let d of u){let b=d.guides??[];if(b.length===0)continue;let y=s.selectedId===d.id||m?.id===d.id,f=vt(d.name||d.id,d.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[E,C]=r(g[0],g[1]),[k,A]=r(g[2],g[3]);e.moveTo(E,C),e.lineTo(k,A)}e.stroke()}for(let d of u){let b=d.path??[];if(b.length<2)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=vs(d.state||"proposed",y,f),E=vt(d.name||d.id,d.color||""),C=en(d.width??1.5,a.scale),k=()=>{e.beginPath();for(let N=0;N0){let N=ii(b);if(N){let[M,D]=r(N[0],N[1]),q=String(A),K=Math.max(16,q.length*6.5+8),H=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(M-K*0.5,D-7.5,K,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":E,e.strokeRect(M-K*0.5,D-7.5,K,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(q,M,D+0.5)}}}if(s.selectedId){let d=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let m=document.createElement("span");m.textContent=xe(r.label),o.appendChild(m);let c=this.getPanelData(r.id),u=Un(c);if(u){let p=document.createElement("span");p.className=`bp-mgmt-badge bp-tone-${u.tone}`,p.textContent=u.text,o.appendChild(p)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=h("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,s.appendChild(r)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}let a=this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&this.planCanvas.root.contains(document.activeElement);if(this.panelEl.replaceChildren(s),a)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=xe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),m.appendChild(c),e.appendChild(m)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=Wn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),l.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),l.appendChild(y)}else{let y=Vn(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,l.appendChild(f)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let p=[`${a.qty??r.length}×`,a.value??"",On(a.footprint??"")].filter(Boolean).join(" · "),d=document.createElement("span");d.className="bp-dim",d.textContent=p;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(d,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=xe(a.stock.class),u.appendChild(y)}o.append(l,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(p,d=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!Xt(b,o()))return;this.bomLastUndo=!d&&(y.changed??0)>0?{project:p.project,editId:b.editId,refs:p.refs.slice(),field:p.field,was:typeof y.was==="string"?y.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=d?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Xt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(c,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn",d.textContent="Undo",d.addEventListener("click",()=>{l(Zn(p),!0)}),m.appendChild(d)}if(t.append(i,r,m),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),a=(p)=>t.sources?.[p]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let p of i){let d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),d.textContent=s(p)+(a(p)?" · judged":""),d.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),r.appendChild(d)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let p=this.watchGen,d=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:d}).then(()=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(l,m),e.appendChild(r),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let u=_n(n,this.checksSource);if(u.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let p of u){let d=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${d}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(p.source)} · ${p.rule}`;let g=document.createElement("span");g.className=`bp-tone-${d}`,g.textContent=String(p.n),b.append(y,f,g),c.appendChild(b);for(let E of p.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let k=document.createElement("div");if(k.textContent=xe(E.title??""),C.appendChild(k),E.names||this.checksSelectedId===E.id){let A=document.createElement("div");A.className="bp-mgmt-row-sub";let N=document.createElement("span");if(N.className="bp-dim bp-mgmt-flex1",N.textContent=E.names??"",A.appendChild(N),this.checksSelectedId===E.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(D)=>{D.stopPropagation();let q={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:q.project,id:E.id}).then((K)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(q,H))return;if(K.text)this.cb.onSendText(K.text),this.checksStatus="Sent to agent",this.render()}).catch((K)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(q,H))return;this.checksStatus=K instanceof Error?K.message:"Could not send finding",this.render()})}),A.appendChild(M)}C.appendChild(A)}C.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),c.appendChild(C)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let m=i[l]??0,c=Yt(l),u=document.createElement("span");u.className=m>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",u.textContent=`${c.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(l,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],m=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${at(l[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let m=this.lifeSelectedKey===l.key,c=Yt(l.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let d=document.createElement("span");d.className="bp-mgmt-strong",d.textContent=Mt(l.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=l.mpn||l.key;let y=document.createElement("span");if(y.className=`bp-tone-${c.tone}`,y.textContent=c.label,p.append(d,b,y),typeof l.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(l.stock),p.appendChild(f)}if(u.appendChild(p),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((f)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(x,S)=>{let I=this.watchGen,V=this.project;this.planStatus="",this.cb.hub.rpc(x,{pro:V,...S}).catch((X)=>{if(I!==this.watchGen||V!==this.project)return;this.planOptimistic.clear(),this.planStatus=X instanceof Error?X.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let x=this.watchGen,S=this.project;this.cb.hub.rpc("plan.get",{pro:S,board:!0}).then((I)=>{let V=ri(I);if(x!==this.watchGen||S!==this.project||!V)return;this.planHydratedKey=i,this.planHydratedBoard=V.board??null,this.planHydratedDraw=V.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),l.setAttribute("data-testid","mgmt-plan-off"),l.setAttribute("aria-pressed",!a?"true":"false"),l.textContent=h("gpui.bots.recall.off","Off"),l.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,l),e.appendChild(s);for(let x of t.elsewhere??[]){let S=document.createElement("div");S.className="bp-plan-elsewhere";let I=document.createElement("span");I.className="bp-tone-warn bp-mgmt-flex1",I.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:x.name||x.rel||""}),S.appendChild(I),e.appendChild(S)}if(t.empty){let x=document.createElement("div");x.className="bp-mgmt-note";let S=document.createElement("div");S.className="bp-dim",S.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let I=document.createElement("div");return I.className="bp-mgmt-faint",I.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),x.append(S,I),e.appendChild(x),e}let m=t.awaiting??0,c=t.blocked??0,u=t.done??0,p=t.total??0,d=t.revision??0,b=zn(t),y=Jn(t),f=y.reduce((x,S)=>x+S.count,0),g=document.createElement("div");g.className="bp-plan-status";let E=document.createElement("div");E.className="bp-plan-status-top";let C=document.createElement("span");if(C.className=`bp-plan-status-badge tone-${b.tone}`,C.textContent=h(b.key,b.label),E.appendChild(C),d>0){let x=document.createElement("span");x.className="bp-dim",x.textContent=`v${d}`,E.appendChild(x)}let k=document.createElement("span");if(k.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":c>0?"bp-tone-bad":"bp-dim"),k.textContent=p>0?`${u}/${p} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),E.appendChild(k),!t.live){let x=document.createElement("span");x.className="bp-mgmt-pill",x.textContent=h("gpui.mgmt.plan.saved","saved plan"),E.appendChild(x)}if(g.appendChild(E),f>0){let x=document.createElement("div");x.className="bp-plan-segbar";for(let S of y){if(S.count<=0)continue;let I=document.createElement("div");I.className=`bp-plan-seg bp-tone-bg-${S.tone}`,I.style.flexGrow=String(S.count),x.appendChild(I)}g.appendChild(x)}e.appendChild(g);let A=document.createElement("div");if(A.className="bp-mgmt-head",m>0){let x=document.createElement("button");x.type="button",x.className="primary bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-approve-all"),x.textContent=h("gpui.mgmt.plan.all","Approve all"),x.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(x)}if(t.routing){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-stop"),x.textContent=h("gpui.mgmt.plan.stop","Stop routing"),x.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(x)}if(t.live&&u>0){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.setAttribute("data-testid","mgmt-plan-verify"),x.textContent=h("gpui.mgmt.plan.verify","Verify"),x.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(x)}let N=document.createElement("span");N.className="bp-mgmt-flex1";let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.setAttribute("data-testid","mgmt-plan-hide"),M.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),M.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.append(N,M),e.appendChild(A);let D=Array.isArray(t.asks)?t.asks:[];if(D.length>0){let x=D.map((j)=>j.what||"").filter(Boolean).join(", "),S=D[0]?.note||"",I=document.createElement("div");I.className="bp-plan-elsewhere";let V=document.createElement("div");V.className="bp-plan-ask-col";let X=document.createElement("div");if(X.className="bp-tone-warn",X.textContent=x?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:x}):h("gpui.mgmt.plan.reqplain","Approval requested"),V.appendChild(X),S){let j=document.createElement("div");j.className="bp-dim",j.textContent=S,V.appendChild(j)}I.appendChild(V),e.appendChild(I)}if(this.planStatus){let x=document.createElement("div");x.className="bp-mgmt-note bp-plan-err bp-tone-bad";let S=document.createElement("span");S.className="bp-mgmt-flex1",S.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):xe(this.planStatus);let I=document.createElement("button");I.type="button",I.className="icon",I.textContent="×",I.title=h("common.close","Close"),I.addEventListener("click",()=>{this.planStatus="",this.render()}),x.append(S,I),e.appendChild(x)}if(t.keys_note){let x=document.createElement("div");x.className="bp-mgmt-note bp-dim";let S="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";x.textContent=t.keys_note===S?h("gpui.mgmt.plan.keysnote",S):xe(t.keys_note),e.appendChild(x)}let q=t.stackup_summary??"",K=Array.isArray(t.impedances)?t.impedances:[];if(q||K.length>0){let x=document.createElement("div");x.className="bp-plan-stackup";let S=document.createElement("button");S.type="button",S.className="bp-plan-stackup-head",S.setAttribute("data-testid","mgmt-plan-stackup-toggle"),S.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let I=document.createElement("span");I.className="bp-plan-chev",I.textContent=this.planStackupOpen?"▾":"▸";let V=document.createElement("span");if(V.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),S.append(I,V),S.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),x.appendChild(S),this.planStackupOpen){let X=document.createElement("div");if(X.className="bp-plan-stackup-body",X.setAttribute("data-testid","mgmt-plan-stackup-body"),q){let j=document.createElement("div");j.className="bp-dim",j.textContent=q,X.appendChild(j)}for(let j of K){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=`· ${j}`,X.appendChild(B)}x.appendChild(X)}e.appendChild(x)}let H=(x,S,I,V)=>{let X=document.createElement("button");return X.type="button",X.className="bp-mgmt-btn bp-plan-chip-btn"+(S?" active":""),X.setAttribute("data-testid",I),X.setAttribute("aria-pressed",S?"true":"false"),X.textContent=x,X.addEventListener("click",V),X},he=document.createElement("div");if(he.className="bp-plan-viewbar",he.append(H(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),H(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),H(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let x=document.createElement("span");x.className="bp-plan-sep";let S=document.createElement("span");S.className="bp-plan-sep";let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn bp-plan-mini-btn",I.setAttribute("data-testid","mgmt-plan-fit"),I.textContent=h("gpui.mgmt.plan.fit","Fit"),I.addEventListener("click",()=>this.planCanvas?.fitAll()),he.append(x,H(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),H(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),H(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),S,H(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),I)}let me=document.createElement("span");me.className="bp-mgmt-flex1";let ie=document.createElement("button");ie.type="button",ie.className="bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-expand"),ie.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),ie.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),he.append(me,ie),e.appendChild(he);let we=this.planHydratedKey===i&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},Se=this.planHydratedKey===i&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},Te=(Se.bands??[]).map((x)=>{let S=this.planOptimistic.get(x.id);if(!S)return{...x};return{...x,...S,edited:!0,state:x.state==="proposed"?"edited":x.state}}),ge=(Se.regions??[]).map((x)=>{let S=this.planOptimistic.get(x.id);if(!S)return{...x};return{...x,...S,edited:!0,state:x.state==="proposed"?"edited":x.state}}),Be=[],T=(t.layers??[]).map((x)=>{let S=[];for(let I of x.items??[]){let V=this.planOptimistic.get(I.id);if(!V){S.push(I);continue}let X={...I,width:typeof V.width==="number"?V.width:I.width,locked:typeof V.locked==="boolean"?V.locked:I.locked,edited:!0,state:I.state==="proposed"?"edited":I.state};if(typeof V.layer==="string"&&V.layer!==x.layer)Be.push({target:V.layer,item:X});else S.push(X)}return{...x,items:S}});for(let x of Be){let S=T.find((I)=>I.layer===x.target);if(S)S.items=[...S.items??[],x.item]}let re=Rt(T,t.copper_layers),ee=this.planGridMode==="all"?re.map((x)=>x.layer):this.planGridMode==="single"?[this.planShownLayers.find((x)=>re.some((S)=>S.layer===x))??rt(re)[0]??re[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((x)=>re.some((S)=>S.layer===x))?this.planShownLayers.slice(0,2):rt(re);if(this.planViewMode!=="list"&&re.length>1){let x=document.createElement("div");x.className="bp-plan-layerbar";for(let S of re){let I=ee.includes(S.layer);x.appendChild(H(S.title||S.layer,I,`mgmt-plan-layerpill-${S.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"){if(!ee.includes(S.layer))this.planShownLayers=ee.length>=2?[ee[0],S.layer]:[...ee,S.layer]}else this.planGridMode="single",this.planShownLayers=[S.layer];this.render()}))}e.appendChild(x)}let Y=(x,S)=>{let I=this.planOptimistic.get(x)??{};if(this.planOptimistic.set(x,{...I,...S}),typeof S.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"&&!ee.includes(S.layer))this.planShownLayers=ee.length>=2?[ee[0],S.layer]:[...ee,S.layer]}let V={...S};if(Array.isArray(S.outline)&&Array.isArray(S.outline[0])&&typeof S.outline[0][0]==="number"){let j=ge.find((B)=>B.id===x);if(j?.holes&&j.holes.length>0)V.outline=[S.outline,...j.holes]}let X=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:x,fields:V}],...X!==void 0?{base:X}:{}})};if(this.planCommitFields=Y,this.planSelectedId){let x="",S=null;for(let I of T){let V=(I.items??[]).find((X)=>X.id===this.planSelectedId);if(V){x=I.layer,S=V;break}}if(S){let I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let V=document.createElement("div");V.className="bp-plan-ins-row";let X=document.createElement("span");X.className="bp-plan-ins-sw",X.style.background=S.kind==="corridor"?vt(S.name||S.id,S.color||""):ft(S.name||S.id,S.color||"");let j=document.createElement("span");j.className="bp-mgmt-strong",j.textContent=S.name||S.id;let B=document.createElement("span");if(B.className="bp-dim",B.textContent=x,V.append(X,j,B),S.edited||S.state==="edited"){let ae=document.createElement("span");ae.className="bp-plan-ins-pill warn",ae.textContent=h("gpui.mgmt.plan.edited","Edited"),V.appendChild(ae)}if(S.locked){let ae=document.createElement("span");ae.className="bp-plan-ins-pill",ae.textContent=h("gpui.mgmt.plan.locked","Locked"),V.appendChild(ae)}let je=document.createElement("span");je.className="bp-mgmt-flex1",V.appendChild(je);let ke=document.createElement("button");if(ke.type="button",ke.className="bp-mgmt-btn bp-plan-mini-btn",ke.setAttribute("data-testid","mgmt-plan-lock"),ke.textContent=S.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),ke.addEventListener("click",()=>Y(S.id,{locked:!S.locked})),V.appendChild(ke),S.state==="proposed"||S.state==="edited"){let ae=document.createElement("button");ae.type="button",ae.className="primary bp-mgmt-btn bp-plan-mini-btn",ae.textContent=h("android.hub.machines.approve","Approve"),ae.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!0}));let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.textContent=h("gpui.mgmt.plan.reject","Reject"),Ae.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!1})),V.append(ae,Ae)}let ce=document.createElement("button");ce.type="button",ce.className="bp-mgmt-btn bp-plan-mini-btn",ce.setAttribute("data-testid","mgmt-plan-note-toggle"),ce.textContent=h("gpui.mgmt.plan.addnote","Add note"),ce.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Pe=document.createElement("button");if(Pe.type="button",Pe.className="icon",Pe.textContent="×",Pe.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),V.append(ce,Pe),I.appendChild(V),!S.locked){let ae=document.createElement("div");if(ae.className="bp-plan-ins-row",S.kind==="corridor"){let de=typeof S.width==="number"?S.width:1.5,fe=document.createElement("span");fe.className="bp-dim",fe.textContent=h("gpui.mgmt.plan.width","Width");let ue=document.createElement("button");ue.type="button",ue.className="bp-mgmt-btn bp-plan-mini-btn",ue.setAttribute("data-testid","mgmt-plan-w-down"),ue.textContent="-",ue.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,de-0.25)*100)/100;Y(S.id,{width:Ue})});let Z=document.createElement("span");Z.className="bp-plan-ins-val",Z.textContent=`${de.toFixed(2)}mm`;let pe=document.createElement("button");pe.type="button",pe.className="bp-mgmt-btn bp-plan-mini-btn",pe.setAttribute("data-testid","mgmt-plan-w-up"),pe.textContent="+",pe.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,de+0.25)*100)/100;Y(S.id,{width:Ue})});let We=document.createElement("span");We.className="bp-plan-sep",ae.append(fe,ue,Z,pe,We)}let Ae=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((de)=>de.layer):T.map((de)=>de.layer);if(Ae.length>0){let de=document.createElement("span");de.className="bp-dim",de.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),ae.appendChild(de);for(let fe of Ae)ae.appendChild(H(fe,fe===x,`mgmt-plan-move-${fe}`,()=>{if(fe!==x)Y(S.id,{layer:fe})}))}I.appendChild(ae)}if(this.planNoteOpen){let ae=document.createElement("form");ae.className="bp-plan-note-form";let Ae=document.createElement("input");Ae.type="text",Ae.className="bp-plan-note-input",Ae.setAttribute("data-testid","mgmt-plan-note-input"),Ae.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let de=document.createElement("button");de.type="submit",de.className="primary bp-mgmt-btn bp-plan-mini-btn",de.setAttribute("data-testid","mgmt-plan-note-submit"),de.textContent=h("gpui.mgmt.plan.addnote","Add note"),ae.append(Ae,de),ae.addEventListener("submit",(fe)=>{fe.preventDefault();let ue=Ae.value.trim();if(!ue)return;Ae.value="",this.planNoteOpen=!1;let Z=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:S.id,text:ue}],...Z!==void 0?{base:Z}:{}})}),I.appendChild(ae)}if(this.planViewMode!=="list"&&!S.locked){let ae=document.createElement("div");ae.className="bp-plan-hint",ae.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(ae)}e.appendChild(I)}}let le=document.createElement("div");le.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),le.setAttribute("data-testid","mgmt-plan-rows");let F=h("gpui.mgmt.plan.done","done");for(let x of T){let S=x.items??[],I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let V=document.createElement("div");V.className="bp-mgmt-row-line";let X=document.createElement("span");X.className="bp-mgmt-strong",X.textContent=x.layer;let j=document.createElement("span");if(j.className="bp-dim bp-mgmt-flex1",j.textContent=`${x.role?`${x.role} · `:""}${x.done??0}/${S.length} ${F}`,V.append(X,j),x.status!=="approved"&&S.length>0){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=h("gpui.mgmt.plan.layer","Approve layer"),B.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=h("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:x.layer,ids:[],approve:!1})),V.append(B,je)}if(I.appendChild(V),x.stackup){let B=document.createElement("div");B.className="bp-plan-layer-stackup",B.textContent=x.stackup,I.appendChild(B)}le.appendChild(I);for(let B of S){if(this.planHideDone&&qn(B))continue;let je=this.planSelectedId===B.id,ke=document.createElement("div");ke.className="bp-mgmt-row bp-plan-row"+(je?" active":""),ke.setAttribute("data-testid",`mgmt-plan-row-${B.id}`);let ce=document.createElement("div");ce.className="bp-mgmt-row-line";let Pe=document.createElement("span");Pe.className=`bp-plan-swatch bp-plan-st-${B.state||"proposed"}`,Pe.style.setProperty("--swatch-color",B.color||"#8a8a8a");let ae=document.createElement("span");ae.className="bp-mgmt-flex1"+(B.state==="blocked"||B.state==="failed"?" bp-tone-bad":B.state==="edited"?" bp-tone-warn":B.state==="rejected"||B.state==="routed"||B.state==="verified"?" bp-dim":""),ae.textContent=`${B.name||B.id}${B.locked?" \uD83D\uDD12":""}`;let Ae=[];if(B.kind==="plane"){if(B.reference)Ae.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:B.reference}))}else{let ue=B.nets??0;Ae.push(ue===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:ue}))}if(typeof B.width==="number"&&Number.isFinite(B.width))Ae.push(`${B.width.toFixed(2)}mm`);if(B.impedance)Ae.push(B.impedance);let de=Ae.join(" · "),fe=document.createElement("span");if(fe.className="bp-plan-mark "+(B.state==="blocked"||B.state==="failed"?"bp-tone-bad":B.state==="verified"||B.state==="routed"?"bp-tone-ok":B.state==="approved"?"bp-tone-accent":"bp-dim"),fe.textContent=Kn(B),ce.append(Pe,ae,fe),B.state==="proposed"||B.state==="edited"){let ue=document.createElement("button");ue.type="button",ue.className="bp-mgmt-btn",ue.textContent="✓",ue.title=h("gpui.mgmt.plan.layer","Approve layer"),ue.addEventListener("click",(pe)=>{pe.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!0})});let Z=document.createElement("button");Z.type="button",Z.className="bp-mgmt-btn",Z.textContent="✗",Z.title=h("gpui.mgmt.plan.reject","Reject"),Z.addEventListener("click",(pe)=>{pe.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!1})}),ce.append(ue,Z)}if(ke.appendChild(ce),de){let ue=document.createElement("div");ue.className="bp-mgmt-row-sub bp-plan-detail bp-dim",ue.textContent=de,ke.appendChild(ue)}if(B.state==="routing"&&typeof B.total==="number"&&B.total>0){let ue=document.createElement("div");ue.className="bp-plan-microbar";let Z=document.createElement("div");Z.className="bp-plan-microbar-fill";let pe=Math.max(0,Math.min(100,Math.round((B.routed??0)/B.total*100)));Z.style.width=`${pe}%`,ue.appendChild(Z),ke.appendChild(ue)}if(B.problem_text){let ue=document.createElement("div");ue.className="bp-plan-problem",ue.textContent=B.problem_text,ke.appendChild(ue)}ke.addEventListener("click",()=>{this.planSelectedId=B.id,n("plan.focus",{id:B.id}),this.render()}),le.appendChild(ke)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new tn({onSelect:(V)=>{if(this.planSelectedId=V,!V)this.planNoteOpen=!1;this.render()},onFocusItem:(V)=>{n("plan.focus",{id:V})},onOptimisticPatch:(V,X)=>{let j=this.planOptimistic.get(V)??{};this.planOptimistic.set(V,{...j,...X})},onCommitFields:(V,X)=>{(this.planCommitFields??Y)(V,X)},onApproveLayer:(V,X)=>{n("plan.approve",{layer:V,ids:[],approve:X})},onQuickApprove:(V,X)=>{n("plan.approve",{layer:"",ids:V,approve:X})}});let x=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,S=this.planExpanded||this.panelEl.clientWidth>=540||x;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:ee,selectedId:this.planSelectedId,board:we,bands:Te,regions:ge,layers:re,copperLayers:t.copper_layers},S);let I=document.createElement("div");I.className="bp-plan-canvas-scroll",I.appendChild(this.planCanvas.root),e.appendChild(I)}if(this.planViewMode!=="canvas")e.appendChild(le);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let x=document.createElement("div");x.className="bp-plan-footer",x.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(x)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,C={})=>{let k=this.watchGen,A=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:A,action:E,...C}).catch((N)=>{if(k!==this.watchGen||A!==this.project)return;this.fabStatus=N instanceof Error?N.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Xn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span"),p=(l?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),u.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(u),l?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(E)}if(!l?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),c.appendChild(E)}if(l?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(E)}m.appendChild(c),o.appendChild(m);let d=Yn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(d.button?"bp-tone-warn":"bp-dim"),f.textContent=d.text,y.appendChild(f),d.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=d.button,E.addEventListener("click",()=>n("drc")),y.appendChild(E)}b.appendChild(y),o.appendChild(b);for(let E of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=E,o.appendChild(C)}for(let E of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.fab.apply","Apply"),N.addEventListener("click",()=>n("apply",{key:E.key})),k.append(A,N),C.appendChild(k),o.appendChild(C)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let k=t.stackup.by==="proposed",A=document.createElement("span");if(A.className="bp-mgmt-flex1 "+(k?"bp-tone-warn":"bp-dim"),A.textContent=`${k?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(A),k){let N=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:N})),C.appendChild(M)}E.appendChild(C),o.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let k=document.createElement("span");k.className="bp-mgmt-flex1 bp-tone-warn",k.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=h("gpui.mgmt.fab.seen","Seen"),A.addEventListener("click",()=>n("seen")),C.append(k,A),E.appendChild(C);for(let N of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=N,E.appendChild(M)}o.appendChild(E)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=h("gpui.mgmt.fab.limit","Limit");let k=document.createElement("span");k.className="bp-mgmt-col",k.textContent=h("gpui.mgmt.fab.free","Base price");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=h("gpui.mgmt.fab.extra","Costs more");let N=document.createElement("span");N.className="bp-mgmt-col bp-mgmt-col-read",N.textContent=h("gpui.mgmt.fab.readcol","Read"),E.append(C,k,A,N),o.appendChild(E);for(let D of g){let q=document.createElement("div");q.className="bp-mgmt-row";let K=document.createElement("div");K.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(D.changed?" bp-tone-warn":D.inherited?" bp-dim":""),H.textContent=`${D.changed?"• ":""}${D.label??""}`;let he=document.createElement("span");he.className="bp-mgmt-col",he.textContent=D.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=D.extra?.text||"—";let ie=D.free&&typeof D.free==="object"?D.free:D.extra,we=ie?.fetched??"",Se=Boolean(we)&&ie?.confidence!=="published",Te=we?Se?`${we}*`:we:"—",ge=ie?.source??"",Be;if(ge.startsWith("https://")&&we){let T=document.createElement("a");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",T.href=ge,T.target="_blank",T.rel="noopener noreferrer",T.textContent=Te,Be=T}else{let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",T.textContent=Te,Be=T}K.append(H,he,me,Be),q.appendChild(K),o.appendChild(q)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Es={trs:(e)=>e,t:(e,t)=>t},xs=new Set(["/settle"]);function di(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function mi(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ui(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function hi(e,t=Es){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=xs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:m}=pi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:m,dotClass:mi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function bi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let b of i)p.set(b.id,b.title||b.id);let d=new Set;for(let b of l)if(b.action.type==="thread")d.add(b.action.id);for(let b of n.threads){if(!b.id||d.has(b.id))continue;d.add(b.id);let{urgency:y,want:f}=pi(b);l.push({label:b.title||"Untitled thread",place:b.project?p.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:mi(b),action:{type:"thread",id:b.id}})}}let m=[];for(let p=0;p0)m.push({score:f,index:p,item:d})}m.sort((p,d)=>{if(o){let f=(d.item.urgency??0)-(p.item.urgency??0);if(f!==0)return f}if(d.score!==p.score)return d.score-p.score;let b=p.item.kind==="thread"?0:1,y=d.item.kind==="thread"?0:1;if(b!==y)return b-y;return p.index-d.index});let c=new Set,u=[];for(let p of m){let d=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(c.has(d))continue;if(c.add(d),u.push(p.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=hi(t,{t:h,trs:xe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=bi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,p)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(p,d),m.appendChild(b),d{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var ks=new Set(["resume","raise","retry","move","signin"]);function vi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function jt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(ks.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function yi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class rn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let c=document.createElement("div");c.className="bp-set-head",c.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";d.textContent=b,p.appendChild(d);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(p.appendChild(y),u.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(c,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let l=document.createElement("div");l.className="bp-set-head",l.textContent="Paired devices",o.appendChild(l);try{let m=await this.cb.onLoadDevices();if(m.length===0){let c=document.createElement("div");c.className="bp-dim",c.textContent="No devices listed.",o.appendChild(c)}else for(let c of m){let u=document.createElement("div");u.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div");if(d.textContent=c.title||c.head||"",p.appendChild(d),c.text||c.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=c.text||c.detail||"",p.appendChild(b)}if(u.appendChild(p),c.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of c.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let c=document.createElement("div");c.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";c.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(c)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function Ce(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=Ce("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function on(e){return Ce("pre","bp-context-code",e)}function Ss(e){return Ce("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,xe(e))}function Ht(e,t){let n=Ce("div","bp-context-row");return n.append(Ce("strong",void 0,e),Ss(t)),n}class ln{fetchContext;dialog=Ce("dialog","bp-context");title=Ce("h2");cwd=Ce("div","bp-context-path");tabs=Ce("div","bp-context-tabs");body=Ce("div","bp-context-body");notice=Ce("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ce("div","bp-context-head"),i=Ce("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ce("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ce("details","bp-context-card"),i=Ce("summary");if(i.append(Ht(t.path,t.status),Ce("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,on(t.preview)),t.note)n.append(Ce("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ce("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ce("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ce("h3",void 0,i),on(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ce("h3",void 0,xe(t)));for(let i of n){let s=Ce("article","bp-context-card");s.append(Ht(i.name,i.status),Ce("p",void 0,i.description),Ce("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ce("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ce("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ce("article","bp-context-card");n.append(Ht(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Ht(s.name,s.status),on(a)),s.cwd)n.append(Ce("small","bp-context-path",s.cwd))}if(t.error)n.append(Ce("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ce("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var wi="http://www.w3.org/2000/svg";function Ei(){let e=document.createElementNS(wi,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(wi,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Ls(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function xi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class cn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=h("thread.new","New thread"),l.setAttribute("aria-label",h("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${Ls(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?vi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,l.appendChild(m);for(let u of r.actions){if(!jt(u,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=u.label,p.setAttribute("data-testid",`need-${u.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(d)=>{d.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(p)}o.append(n,l);let c=this.needErr.get(e.id);if(c){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=c,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let l=document.createElement("section");l.className="bp-side-section",l.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),l.appendChild(m);for(let c of o)l.appendChild(this.renderSectionThreadRow(c,!1));e.appendChild(l);continue}if(r.kind==="projects"){let o=r.rows.filter((c)=>{if(!t)return!0;if((c.title||c.id).toLowerCase().includes(t))return!0;if((c.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((c.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),l=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!l&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),l){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,p=r.open?"▾":"▸";if(c.textContent=`${r.title.toUpperCase()} (${u}) ${p}`,r.hint)c.title=r.hint;c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(c)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!l||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let c=document.createElement("div");c.className="bp-side-empty",c.textContent="No projects yet.",m.appendChild(c)}for(let c of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(c.off?" bp-dim":""),u.setAttribute("data-project-id",c.id),c.nav||c.key)u.setAttribute("data-project-key",c.nav||c.key||"");let p=document.createElement("div");p.className="bp-proj-head";let d=document.createElement("button");d.type="button",d.className="bp-proj-toggle";let b=Ei();if(c.css)b.style.color=c.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=c.title||c.id,d.append(b,y),c.fold==="project-fold"&&c.nav)d.addEventListener("click",()=>this.cb.onToggleProjectFold?.(c.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${c.id}`),c.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(c.id)}),p.append(d,f),u.appendChild(p),!c.folded||Boolean(t)){let g=Boolean(t)&&(c.title||c.id).toLowerCase().includes(t);for(let E of c.swarms??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(E,!0))}for(let E of c.threads??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(E,!0))}if(s&&s.project===c.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:xi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!t,m=Ei();if(i.css)m.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(m,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!l)for(let p of s)a.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:xi(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let c of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(c.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",c.color)p.style.backgroundColor=c.color;let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`@${c.name}`,u.append(p,d),u.addEventListener("click",()=>this.cb.onSelectBot(c)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let l=document.createElement("span");l.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(l,m),r.appendChild(o);for(let c of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${c.name}`,u.appendChild(p),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function As(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ps(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/m:0));s[a]=c<0?c*32768:c*32767}return s}class dn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?As(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Ps(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var Ci=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ki=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Si=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Li=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ns=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ms=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Ts=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class pn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,p},r=(u)=>{let p=0,d=0,b=0;for(let y=1;y<=u.maxBits;y++){p|=a(1);let f=u.counts[y];if(p-f{let p=l+u;if(p>t)throw Error("inflated frame exceeds limit");if(p<=o.length)return;let d=o.length;while(d{m(1),o[l++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),p=a(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let d=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(d^65535)!==b)throw Error("invalid stored block length");if(n+d>e.length)throw Error("truncated stored payload");m(d);for(let y=0;y=e.length)break}else if(p===1||p===2){let d=Ms,b=Ts;if(p===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,E=new Uint8Array(19);for(let M=0;Mk)throw Error("code length overflow");for(let K=0;Kk)throw Error("code length overflow");N+=D}else if(M===18){let D=a(7)+11;if(N+D>k)throw Error("code length overflow");N+=D}else throw Error("invalid code length symbol")}d=Et(A,y),b=Et(A.subarray(y),f)}while(!0){let y=r(d);if(y<256)c(y);else if(y===256)break;else{let f=y-257;if(f>=Ci.length)throw Error("invalid length symbol");let g=Ci[f]+(ki[f]?a(ki[f]):0),E=r(b);if(E>=Si.length)throw Error("invalid distance symbol");let C=Si[E]+(Li[E]?a(Li[E]):0);m(g);let k=this.winPos-C&32767;for(let A=0;A{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new pn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(l))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Bs=new TextDecoder;function Ai(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Pi(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,m=i(o&31);if(m===null)return null;switch(l){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let c=e.subarray(t,t+m);return t+=m,c}case 3:{if(t+m>e.length)return null;let c=Bs.decode(e.subarray(t,t+m));return t+=m,c}case 4:{if(m>e.length)return null;let c=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Mi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new Ni(m),u=[],p=[],d=0,b=0;while(c.more()){let y=c.nextU32(),f=u.length,g=1/0,E=1/0,C=-1/0,k=-1/0;if(a===2)d=d+c.nextI32()|0,b=b+c.nextI32()|0,u.push(d,b),g=C=d,E=k=b;else{let N=Math.min(c.nextU32(),1048576);for(let M=0;MC)C=d;if(bk)k=b}}let A=(u.length-f)/2;if(A>0){let N=a===2||A===1?2:a===0?0:1,M=a===0?0:o;p.push({info:y,x0:g-M,y0:E-M,x1:C+M,y1:k+M,at:f,n:A,kind:N})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(u),pieces:p}}function Ti(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Bi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,c=(t-l)/r;if(m<0||m>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var Ii=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Ri(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class un{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function ji(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,m=-1,c=null,u=new un,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let d=document.createElement("div");d.className="bp-pane-bar bp-browser-nav";function b(Y,le,F){let x=document.createElement("button");if(x.type="button",x.className="bp-v-btn",x.textContent=Y,x.setAttribute("data-testid",le),F)x.title=F;return x}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let k=b("Go","browser-go","Navigate");k.type="submit",E.append(C,k);let A=b("Take over","browser-takeover");A.classList.add("is-primary"),d.append(y,f,g,E,A);let N=document.createElement("div");N.className="bp-browser-drive-bar",N.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let D=document.createElement("input");D.type="text",D.className="bp-browser-input",D.placeholder="Type text or press Enter/Tab/Arrows…",D.autocomplete="off",D.spellcheck=!1,D.setAttribute("data-testid","browser-keys");let q=b("Send","browser-type-send");M.append(D,q);let K=document.createElement("div");K.className="bp-browser-quick-keys";for(let[Y,le]of Ii){let F=b(Y,`browser-key-${le}`);F.addEventListener("click",()=>ge("press",{key:le})),K.append(F)}N.append(M,K);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let he=document.createElement("div");he.className="bp-browser-stage",he.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",he.append(me,ie);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,p.append(d,N,H,he,we),e.replaceChildren(p);function Se(Y){H.textContent=Y,H.hidden=!Y}function Te(){N.hidden=!s,we.hidden=!s,A.textContent=s?"Hand back":"Take over",A.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),A.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function ge(Y,le={},F){u.enqueue(async()=>{if(!i)return;Se("");try{if(await t.hub.rpc("browser",{thread:n,op:Y,...le}),!i)return;F?.(),re()}catch(x){if(!i)return;Se(x instanceof Error?x.message:String(x))}})}function Be(Y){ge("toolbar",{command:Y},()=>{s=!0,Te()})}y.addEventListener("click",()=>Be("back")),f.addEventListener("click",()=>Be("forward")),g.addEventListener("click",()=>Be("reload")),E.addEventListener("submit",(Y)=>{Y.preventDefault();let le=Ri(C.value);if(!le)return;if(C.value=le,!s)ge("takeover",{},()=>{s=!0,Te()});ge("navigate",{url:le},()=>{s=!0,Te()})}),A.addEventListener("click",()=>{if(s)ge("handback",{},()=>{s=!1,Te()});else ge("takeover",{},()=>{s=!0,Te(),D.focus()})});function T(){let Y=D.value;if(!Y)return;D.value="",ge("type",{text:Y})}q.addEventListener("click",T),D.addEventListener("keydown",(Y)=>{if(!s)return;if(Y.key==="Enter"){if(Y.preventDefault(),D.value)T();ge("press",{key:"Enter"});return}if(Y.key==="Tab"||Y.key==="Escape"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="ArrowLeft"||Y.key==="ArrowRight"||Y.key==="Backspace"&&D.value==="")Y.preventDefault(),ge("press",{key:Y.key})}),me.addEventListener("click",(Y)=>{if(!s||!a)return;let le=me.getBoundingClientRect(),F=Bi(Y.clientX,Y.clientY,{left:le.left,top:le.top,width:le.width,height:le.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!F)return;ge("click",F)}),me.addEventListener("wheel",(Y)=>{if(!s||!a)return;Y.preventDefault();let le=Math.round(Y.deltaX),F=Math.round(Y.deltaY);if(le===0&&F===0)return;ge("scroll",{dx:le,dy:F})},{passive:!1});async function re(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let Y=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(Y.ok){let le=await Y.blob();if(!i)return;let F=URL.createObjectURL(le),x=r;if(r=F,me.src=F,me.hidden=!1,ie.hidden=!0,a=!0,x)URL.revokeObjectURL(x)}else if(!a)me.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)me.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ee=t.hub.onFrame((Y)=>{if(!i)return;if(Y.t==="shot"&&Y.bot===n){if(typeof Y.n==="number"){if(Y.n===m)return;m=Y.n}re()}});return re(),{destroy(){if(i=!1,ee(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function W(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Dt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Di(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Rs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Hi(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function js(e){let t=Di(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Fi(e,t,n,i){let s=!0,a="",r="",o=W("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=W("div","bp-pane-bar"),m=W("div","bp-files-crumbs"),c=W("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void f(a)),l.append(m,c);let u=W("div","bp-files-split"),p=W("div","bp-files-list");p.setAttribute("data-testid","files-list");let d=W("div","bp-files-preview");d.setAttribute("data-testid","files-preview"),d.append(W("div","bp-pane-empty","Select a file to preview")),u.append(p,d),o.append(l,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=W("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let E=a.split("/").filter(Boolean),C="";for(let k of E){C=C?`${C}/${k}`:k;let A=C;m.append(W("span","bp-vh-sep","/"));let N=W("button","bp-crumb-btn",k);N.type="button",N.addEventListener("click",()=>void f(A)),m.append(N)}}async function y(g,E,C){r=g,d.replaceChildren();let k=W("div","bp-files-prev-head");k.append(W("span","bp-files-prev-name",g));let A=W("div","bp-files-prev-acts"),N=js(E);if(N){let K=W("button","bp-v-btn is-primary",`Open in ${N}`);K.type="button",K.setAttribute("data-testid","files-open-viewer"),K.addEventListener("click",()=>i(N,g)),A.append(K)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,D=W("a","bp-v-btn","Download");D.href=M,D.download=E,A.append(D),k.append(A),d.append(k);let q=Di(E);if(Rs(q)){let K=W("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=E,H.src=M,K.append(H),d.append(K);return}if(C>524288&&!Hi(q)){d.append(W("div","bp-pane-empty",`Binary file (${Dt(C)}). Use Download to save.`));return}if(Hi(q)||C<=65536){let K=W("div","bp-pane-empty","Loading…");d.append(K);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||r!==g)return;if(!H.ok){K.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){K.remove();let ee=document.createElement("img");ee.className="bp-files-img",ee.alt=E,ee.src=M,d.append(ee);return}let me=262144,ie=[],we=0,Se=!1;if(H.body){let ee=H.body.getReader();try{while(!0){let{done:Y,value:le}=await ee.read();if(Y||!le)break;if(we+le.byteLength>me){let F=me-we;if(F>0)ie.push(le.subarray(0,F)),we+=F;Se=!0,await ee.cancel();break}ie.push(le),we+=le.byteLength}}finally{ee.releaseLock()}}if(!s||r!==g)return;let Te=new Uint8Array(we),ge=0;for(let ee of ie)Te.set(ee,ge),ge+=ee.byteLength;let Be=!1;for(let ee=0;eek.dir===A.dir?k.name.localeCompare(A.name):k.dir?-1:1),p.replaceChildren(),g){let k=W("button","bp-file-row is-dir");k.type="button",k.append(W("span","bp-file-icon","↰"),W("span","bp-file-name",".."));let A=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";k.addEventListener("click",()=>void f(A)),p.append(k)}if(C.length===0){p.append(W("div","bp-pane-empty","Empty folder"));return}for(let k of C){let A=g?`${g}/${k.name}`:k.name,N=W("button","bp-file-row"+(k.dir?" is-dir":"")+(A===r?" is-sel":""));N.type="button",N.setAttribute("data-testid",`file-row-${k.name}`),N.append(W("span","bp-file-icon",k.dir?"▸":"·"),W("span","bp-file-name",k.name),W("span","bp-file-size",k.dir?"":Dt(k.size))),N.addEventListener("click",()=>{if(k.dir)f(A);else p.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),N.classList.add("is-sel"),y(A,k.name,k.size)}),p.append(N)}}catch(E){if(!s)return;p.replaceChildren(W("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return f(""),{destroy(){s=!1}}}function $i(e,t,n){let i=!0,s=W("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=W("div","bp-pane-bar"),r=W("span","bp-diff-summary","Loading diff…"),o=W("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let l=W("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(W("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof c?.diff==="string"?c.diff:"";if(!u.trim()){r.textContent="Clean working tree",l.append(W("div","bp-pane-empty","No uncommitted changes."));return}let p=u.split(` -`),d=0,b=0,y=0,f=document.createDocumentFragment(),g=W("div","bp-diff-file");for(let E of p){if(E.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=W("div","bp-diff-file"),d++;let C=E.match(/ b\/(.+)$/);g.append(W("div","bp-diff-file-head",C?C[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))g.append(W("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))g.append(W("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))b++,g.append(W("div","bp-diff-line is-add",E));else if(E.startsWith("-"))y++,g.append(W("div","bp-diff-line is-del",E));else g.append(W("div","bp-diff-line",E))}if(g.childNodes.length>0)f.append(g);r.textContent=`${d||1} file${d===1?"":"s"} · +${b} -${y}`,l.append(f)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(W("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return m(),{destroy(){i=!1}}}function Gi(e,t,n){let i=!0,s="checks",a=W("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=W("div","bp-pane-bar"),o=W("div","bp-review-tabs"),l=W("button","bp-v-btn is-on","Checks"),m=W("button","bp-v-btn","BOM"),c=W("button","bp-v-btn","Comments");l.type=m.type=c.type="button",o.append(l,m,c);let u=W("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void y()),r.append(o,u);let p=W("div","bp-review-body");p.setAttribute("data-testid","review-body"),a.append(r,p),e.replaceChildren(a);function d(f){s=f,l.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),y()}l.addEventListener("click",()=>d("checks")),m.addEventListener("click",()=>d("bom")),c.addEventListener("click",()=>d("comments"));function b(f){let g=W("div","bp-review-md"),E=f.split(` -`),C=0;while(C{M.preventDefault();let D=A.value.trim();if(!D)return;N.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:D}).then(()=>{A.value="",N.disabled=!1,y()},()=>{N.disabled=!1})}),p.append(k),C.length===0){p.append(W("div","bp-pane-empty","No review comments yet."));return}for(let M of C){let D=W("div","bp-review-comment"+(M.resolved?" is-resolved":"")),q=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");D.append(W("div","bp-review-comment-meta",q),W("div","bp-review-comment-text",M.text)),p.append(D)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(p.replaceChildren(),g.line||g.gate){let E=W("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));p.append(E)}if(g.err)p.append(W("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let E=W("div","bp-review-tasks");g.tasks.forEach((C,k)=>{let A=W("label","bp-review-task"),N=document.createElement("input");N.type="checkbox",N.checked=!!(C.done??C.checked);let M=typeof C.index==="number"?C.index:k;N.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void y(),()=>{})}),A.append(N,W("span",void 0,C.text||C.label||`Item ${k+1}`)),E.append(A)}),p.append(E)}if(g.md&&g.md.trim())p.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))p.append(W("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;p.replaceChildren(W("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function Ui(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class hn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,m=n*0.5,c=this.scale,u=this.cx,p=this.cy,d=u-l/c,b=u+l/c,y=p-m/c,f=p+m/c,{off:g,dim:E,lift:C}=this.masks,k=[],A=[];for(let M=0;M>>D&1)===1)continue;if(D===C)A.push(M);else k.push(M)}let N=k.concat(A);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>q.layer&1)===1,H=q.alpha*(K?0.25:1);if(H<=0.01)continue;this.drawChunk(r,q,H,d,y,b,f,u,p,c,l,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let D=0;Da||f.y1r)continue;if(f.n<3)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+u;e.moveTo(g,E);for(let C=1;C0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=d,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let E=(p[g.at]-o)*m+c,C=(p[g.at+1]-l)*m+u;e.moveTo(E+b,C),e.arc(E,C,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=d,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+u;if(f.n===1)e.moveTo(g,E),e.lineTo(g+0.01,E);else{e.moveTo(g,E);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,m,c,u,p){let d=t.pts,b=Ui(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(d[f.at]-l)*c+u,E=(d[f.at+1]-m)*c+p;if(f.kind===2){let C=Math.max(1.5,t.r*c);e.fillStyle=b,e.beginPath(),e.arc(g,E,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,E);for(let C=1;C=0;c--){let u=n.chunks[c];if(u.layer<32&&(m>>>u.layer&1)===1)continue;for(let p=0;pd.x1+r||ad.y1+r)continue;let b=(d.x1-d.x0+1)*(d.y1-d.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,u=s-l.left-l.width*0.5,p=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-p/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Oi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Vi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function bn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),l=i.replace(/\\/g,"/");if(l.startsWith("/")||/^[A-Za-z]:\//.test(l))return o===l;return o===l||o.endsWith(`/${l}`)}class gn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Hs=`#version 300 es +`),h=document.createElement("div");h.className="bp-code-block";let p=document.createElement("div");p.className="bp-code-head";let d=document.createElement("span");d.className="bp-code-lang",d.textContent=l||"code";let b=document.createElement("button");b.type="button",b.className="bp-btn-ghost bp-code-copy";let y=u("common.copy","Copy");b.textContent=y,b.addEventListener("click",()=>{navigator.clipboard?.writeText(c).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),p.append(d,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=c,f.appendChild(g),h.append(p,f),t.appendChild(h);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",ut(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ut(l,m.join(` +`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));ut(o,r[l])}t.appendChild(o)}return t}var Bn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qt(e){return e<10000000000?e*1000:e}function rs(e){if(!e)return"";return new Date(qt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function os(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function _t(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Kt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=u("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=u("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=u("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=u("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!_t(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!_t(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(_t(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||u("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=u("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=u("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let h=rs(e.at);if(t)c.textContent=h,i.append(s,...m?[o]:[],c);else{let p=n&&e.at?os(qt(e.at)-qt(n)):"",d=h?p?u("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:p}):u("web.chat.finished","Finished {time}",{time:h}):"";c.textContent=e.live?u("web.chat.streaming","Streaming…"):d,i.append(c,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=u("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=u("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let h=document.createElement("span");if(h.className="bp-tool-name",h.textContent=a.tool.name,c.appendChild(h),a.tool.summary){let p=document.createElement("span");p.className="bp-tool-summary",p.textContent=a.tool.summary,c.appendChild(p)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let h=document.createElement("div");h.className="bp-ask-card",h.setAttribute("data-testid",`ask-${c.id}`);let p=document.createElement("div");if(p.className="bp-ask-q",p.textContent=c.question,h.appendChild(p),c.state==="open"){let d=document.createElement("div");if(d.className="bp-ask-opts",c.options&&c.options.length>0)for(let b of c.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,b.id)),d.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=u("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=u("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(c.id,b.value.trim())}),d.append(b,y)}h.appendChild(d)}else{let d=document.createElement("div");d.className="bp-ask-answered",d.textContent=u("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),h.appendChild(d)}r.appendChild(h),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!m&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=u("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let h=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let p=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(h);else this.goTo(h)};c.addEventListener("click",p),c.addEventListener("keydown",(d)=>{if(d.key==="Enter"||d.key===" ")d.preventDefault(),p()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.textContent=a.text;else c.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(m&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let h of a.attachments)if(h.previewUrl){let p=document.createElement("img");p.className="bp-reply-img",p.src=h.previewUrl,p.alt=h.name||"attachment",c.appendChild(p)}else if(h.path||h.name){let p=document.createElement("span");p.className="bp-tool-pill",p.textContent=h.name||h.path||"image",c.appendChild(p)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let h of a.images){let p=document.createElement("img");p.className="bp-reply-img",p.alt=h;let d=`${a.id}|${h}`,b=this.imageCache.get(d);if(b)p.src=b;else this.cb.onLoadImage(a.id,h).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(d,f),p.src=f});c.appendChild(p)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?u("ask.plan","Proposed plan"):xe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=u("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let h=u("common.copy","Copy"),p=document.createElement("span");p.textContent=h,c.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),p),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),p.textContent=u("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),p.textContent=h},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?u("gpui.c.term.collapse","Collapse"):u("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let h=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),p=document.createElement("button");if(p.type="button",p.className="primary",p.setAttribute("data-testid","plan-implement"),p.textContent=h?.label&&h.label!=="Implement"?xe(h.label):u("approval.implement","Implement"),p.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"implement")}),c.appendChild(p),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(u("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(y)}let d=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=d?.label&&d.label!=="Dismiss"?xe(d.label):u("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,d?.id??"dismiss")}),c.appendChild(b),i.appendChild(c),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=u("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=u("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let E=()=>{let A=f.value.trim();if(!A)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${A}`)},x=()=>{this.closePlanRevise()};y.addEventListener("keydown",(A)=>{if(A.key==="Escape")A.preventDefault(),A.stopPropagation(),x()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(A)=>{if(A.key==="Enter"&&!A.shiftKey)A.preventDefault(),E()}),g.addEventListener("click",E);let k=document.createElement("button");k.type="button",k.className="bp-btn-ghost",k.textContent=u("common.cancel","Cancel"),k.addEventListener("click",x),y.append(f,g,k),i.appendChild(y)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=u("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var In="http://www.w3.org/2000/svg",Rn=4,jn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(In,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(In,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function zt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Hn(){return Pt(["M6 4l14 8-14 8z"])}function ls(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Jt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=u("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=u("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=u("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",u("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=u("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",u("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=u("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=u("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let m=l.clipboardData?.items;if(!m)return;let c=[];for(let h=0;h0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=ls(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=u("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${u("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?Hn():zt()),this.planChipLbl.textContent=s?u("gpui.planmode.chip.building","Building"):t==="pending"?u("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?u("gpui.planmode.chip.once","Plan · 1t"):u("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?u("gpui.mgmt.plan.tab","Plan"):u("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?Hn():zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?u("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?u("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?u("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?u("gpui.planmode.bar.pending","Proposed plan awaits review below"):u("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let c=(h,p,d,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(p?" active":""),y.textContent=h,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(d)),y};m.append(c(u("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(u("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(u("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(m)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=u("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=u("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=u("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=u("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",u("web.composer.attach","Attach image")),this.voiceBtn.title=u("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",u("web.composer.voice","Voice dictation")),this.sendBtn.textContent=u("composer.send","Send"),this.stopBtn.textContent=u("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!jn.has(t.type)){this.showError(u("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Rn){this.showError(u("web.composer.maximages","At most {max} images per message.",{max:Rn}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=u("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Dn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var cs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&cs.has(t.id))}function On(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var ds=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ps=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Un(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(ds.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ps.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function Vn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Wn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function _n(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Yt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function qn(e){return e.state==="routed"||e.state==="verified"}function Kn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function zn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Jn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Yn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Xn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Xt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Zn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Zt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Fn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],$n=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Qn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Fn[Qn(i)%Fn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return $n[Qn(e)%$n.length]}function ei(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function Je(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ti(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ni(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[m,c]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function ii(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function si(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Qt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ms(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+m*r,h=i+m*o;return(e-c)*(e-c)+(t-h)*(t-h)}function Gn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(l-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function en(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,l){if(i){for(let p of e){if(p.layer!==n||p.id!==i||p.locked)continue;let d=p.path??[];for(let b=0;b=3)for(let b=0;b=0;p--){let d=t[p];if(d.layer!==n)continue;let b=d.outline??[];if(!Gn(c,h,b))continue;if(!(d.holes??[]).some((f)=>Gn(c,h,f)))return{kind:"region",id:d.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,l=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function ai(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[c,h]=Je(t,m.b[0],m.b[1],n,i),[p,d]=Je(t,m.b[2],m.b[3],n,i),b=Math.abs(p-c),y=Math.abs(d-h);if(b<13||y<9)continue;let f=(c+p)*0.5,g=(h+d)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,c)=>c.score-m.score);let o=[],l=[];for(let m of r){let c=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((p)=>!(c[2]<=p[0]||c[0]>=p[2]||c[3]<=p[1]||c[1]>=p[3])))o.push(c),l.push({text:m.text,cx:m.cx,cy:m.cy})}return l}function ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Rt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}function oi(e,t,n,i,s,a,r,o){return e===t&&n===i&&s===a&&(o===void 0||r>=o)}var li="#111917",hs="#16201d",us="rgba(212, 224, 219, 0.92)",bs="rgba(61, 80, 73, 0.72)",gs="rgba(82, 107, 97, 0.85)",fs="rgba(143, 163, 155, 0.88)",ci="#f59e0b",vs="#eef5f2",di="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function ys(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function ws(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function Es(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class tn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Rt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??rt(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):rt(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ei(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=u("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=u("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,m);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let h=document.createElement("div");h.className="bp-plan-card-canvas-wrap";let p=document.createElement("canvas");p.className="bp-plan-card-canvas",p.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let d=document.createElement("div");d.className="bp-plan-hover-hud bp-hidden",h.append(p,d);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,h,b);let y=p.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(h),this.attachPointerListeners(p,e.layer);let g={layer:e.layer,el:t,canvas:p,ctx:y,legendEl:b,okBtn:l,noBtn:m,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:d,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=Es(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=u(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let l=document.createElement("button");l.type="button";let m=this.state?.selectedId===o.id;l.className="bp-plan-legend-chip"+(m?" active":"");let c=document.createElement("span");c.className="bp-plan-legend-sw",c.style.background=ft(o.net||o.id,o.color||"");let h=document.createElement("span");h.textContent=o.net||o.id,l.append(c,h),l.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(l)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height),c=this.getCam(t,l,m),h=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o);if(i.button===2){if(h?.kind==="vertex"){let p=this.getItemPts(h.id,h.isPlane),d=Qt(p,h.idx,h.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(h.id,{[h.isPlane?"outline":"path"]:d})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},h?.kind==="vertex"){let p=this.getItemPts(h.id,h.isPlane),d=p.map((b)=>[b[0],b[1]]);this.selectedVertex={id:h.id,idx:h.idx},this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:h.idx,pts:p.map((b)=>[b[0],b[1]]),origPts:d,moved:!1},this.scheduleDraw()}else if(h?.kind==="midpoint"){let p=this.getItemPts(h.id,h.isPlane),d=p.map((f)=>[f[0],f[1]]),b=si(p,h.segIdx,h.pos,h.isPlane),y=h.isPlane&&h.segIdx+1>=p.length?b.length-1:Math.min(h.segIdx+1,b.length-1);this.selectedVertex={id:h.id,idx:y},this.patchLocalItem(h.id,h.isPlane,b),this.cb.onOptimisticPatch(h.id,{[h.isPlane?"outline":"path"]:b}),this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:y,pts:b,origPts:d,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let k=this.getCam(t,l,m);this.setCam(t,ti(k,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let y=this.getCam(t,l,m),[f,g]=Bt(y,r,o,l,m),E=[Math.round(f*1000)/1000,Math.round(g*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let x=this.drag.pts.map((k)=>[k[0],k[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:x}),this.scheduleDraw();return}let c=this.getCam(t,l,m),h=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o),p=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=this.hover?.hit.kind??"",b=h?h.id:"";if(this.hover=h?{layer:t,hit:h}:null,e.style.cursor=h?"pointer":"crosshair",p!==b||(h?.kind??"")!==d)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"){let s=i.origPts.map((a)=>[a[0],a[1]]);this.patchLocalItem(i.id,i.isPlane,s),this.cb.onRevertOptimistic?.(i.id)}else this.cb.onDragEnd?.();this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,m=i.clientY-o.top,c=Math.max(1,o.width),h=Math.max(1,o.height),p=this.getCam(t,c,h),d=It(s.bands,s.regions,t,s.selectedId,p,c,h,l,m);if(d&&(d.kind==="band"||d.kind==="region")){this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);return}if(!d&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),m=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ni(m,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=Qt(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(d,b)=>Je(a,d,b,n,i);e.fillStyle=li,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((d)=>d.length>=3);if(e.fillStyle=hs,o.length>0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let d of l){let b=d.outline??[];if(b.length<3)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ws(d.state||"proposed",y,f),E=ft(d.net||d.id,d.color||"");e.beginPath();for(let x=0;x0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),p=[];for(let d of h){for(let b of d.from??[])p.push(b);for(let b of d.to??[])p.push(b)}e.fillStyle=fs,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let d of ai(c,a,n,i,p))e.fillText(d.text,d.cx,d.cy);for(let d of h){let b=d.guides??[];if(b.length===0)continue;let y=s.selectedId===d.id||m?.id===d.id,f=vt(d.name||d.id,d.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[E,x]=r(g[0],g[1]),[k,A]=r(g[2],g[3]);e.moveTo(E,x),e.lineTo(k,A)}e.stroke()}for(let d of h){let b=d.path??[];if(b.length<2)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ys(d.state||"proposed",y,f),E=vt(d.name||d.id,d.color||""),x=en(d.width??1.5,a.scale),k=()=>{e.beginPath();for(let N=0;N0){let N=ii(b);if(N){let[M,D]=r(N[0],N[1]),W=String(A),_=Math.max(16,W.length*6.5+8),H=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(M-_*0.5,D-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":E,e.strokeRect(M-_*0.5,D-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,M,D+0.5)}}}if(s.selectedId){let d=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let m=document.createElement("span");m.textContent=xe(r.label),o.appendChild(m);let c=this.getPanelData(r.id),h=On(c);if(h){let p=document.createElement("span");p.className=`bp-mgmt-badge bp-tone-${h.tone}`,p.textContent=h.text,o.appendChild(p)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=u("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",u("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),a=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,a.appendChild(r)}switch(this.openPanel){case"bom":a.appendChild(this.renderBom());break;case"checks":a.appendChild(this.renderChecks());break;case"life":a.appendChild(this.renderLife());break;case"plan":a.appendChild(this.renderPlan());break;case"fab":a.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(a),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=xe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),m.appendChild(c),e.appendChild(m)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=Wn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),l.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=u("gpui.mgmt.bom.dnp","DNP"),l.appendChild(y)}else{let y=Vn(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,l.appendChild(f)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let p=[`${a.qty??r.length}×`,a.value??"",Un(a.footprint??"")].filter(Boolean).join(" · "),d=document.createElement("span");d.className="bp-dim",d.textContent=p;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=u("gpui.mgmt.bom.nompn","no MPN");if(h.append(d,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),h.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=xe(a.stock.class),h.appendChild(y)}o.append(l,h),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(p,d=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!Xt(b,o()))return;this.bomLastUndo=!d&&(y.changed??0)>0?{project:p.project,editId:b.editId,refs:p.refs.slice(),field:p.field,was:typeof y.was==="string"?y.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=d?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Xt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(c,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn",d.textContent="Undo",d.addEventListener("click",()=>{l(Zn(p),!0)}),m.appendChild(d)}if(t.append(i,r,m),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),a=(p)=>t.sources?.[p]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=u("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let p of i){let d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),d.textContent=s(p)+(a(p)?" · judged":""),d.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),r.appendChild(d)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=u("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let p=this.watchGen,d=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:d}).then(()=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(l,m),e.appendChild(r),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let h=_n(n,this.checksSource);if(h.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let p of h){let d=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${d}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(p.source)} · ${p.rule}`;let g=document.createElement("span");g.className=`bp-tone-${d}`,g.textContent=String(p.n),b.append(y,f,g),c.appendChild(b);for(let E of p.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let k=document.createElement("div");if(k.textContent=xe(E.title??""),x.appendChild(k),E.names||this.checksSelectedId===E.id){let A=document.createElement("div");A.className="bp-mgmt-row-sub";let N=document.createElement("span");if(N.className="bp-dim bp-mgmt-flex1",N.textContent=E.names??"",A.appendChild(N),this.checksSelectedId===E.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=u("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(D)=>{D.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:E.id}).then((_)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(W,H))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(W,H))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),A.appendChild(M)}x.appendChild(A)}x.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),c.appendChild(x)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let m=i[l]??0,c=Yt(l),h=document.createElement("span");h.className=m>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",h.textContent=`${c.label} ${m}`,n.appendChild(h)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(l,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],m=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${at(l[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let m=this.lifeSelectedKey===l.key,c=Yt(l.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(m?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let d=document.createElement("span");d.className="bp-mgmt-strong",d.textContent=Mt(l.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=l.mpn||l.key;let y=document.createElement("span");if(y.className=`bp-tone-${c.tone}`,y.textContent=c.label,p.append(d,b,y),typeof l.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(l.stock),p.appendChild(f)}if(h.appendChild(p),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=u("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=u("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(f)}h.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((f)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(u("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(C,S)=>{let R=this.watchGen,q=this.project;this.planStatus="",this.cb.hub.rpc(C,{pro:q,...S}).catch((T)=>{if(R!==this.watchGen||q!==this.project)return;this.planOptimistic.clear(),this.planStatus=T instanceof Error?T.message:u("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let C=this.watchGen,S=++this.planHydrateGen,R=this.project,q=t.revision??0;this.cb.hub.rpc("plan.get",{pro:R,board:!0}).then((T)=>{let z=ri(T);if(!z)return;let J=typeof z.revision==="number"?z.revision:q;if(!oi(C,this.watchGen,S,this.planHydrateGen,R,this.project,J,this.planHydratedRev))return;this.planHydratedRev=J,this.planHydratedKey=`${R}:${J}`,this.planHydratedBoard=z.board??null,this.planHydratedDraw=z.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=u("gpui.mgmt.plan.before","Plan before routing"),r.title=a?u("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):u("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=u("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),l.setAttribute("data-testid","mgmt-plan-off"),l.setAttribute("aria-pressed",!a?"true":"false"),l.textContent=u("gpui.bots.recall.off","Off"),l.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,l),e.appendChild(s);for(let C of t.elsewhere??[]){let S=document.createElement("div");S.className="bp-plan-elsewhere";let R=document.createElement("span");R.className="bp-tone-warn bp-mgmt-flex1",R.textContent=u("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:C.name||C.rel||""}),S.appendChild(R),e.appendChild(S)}if(t.empty){let C=document.createElement("div");C.className="bp-mgmt-note";let S=document.createElement("div");S.className="bp-dim",S.textContent=u("gpui.mgmt.plan.noboard","No routing plan for this board.");let R=document.createElement("div");return R.className="bp-mgmt-faint",R.textContent=u("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),C.append(S,R),e.appendChild(C),e}let m=t.awaiting??0,c=t.blocked??0,h=t.done??0,p=t.total??0,d=t.revision??0,b=zn(t),y=Jn(t),f=y.reduce((C,S)=>C+S.count,0),g=document.createElement("div");g.className="bp-plan-status";let E=document.createElement("div");E.className="bp-plan-status-top";let x=document.createElement("span");if(x.className=`bp-plan-status-badge tone-${b.tone}`,x.textContent=u(b.key,b.label),E.appendChild(x),d>0){let C=document.createElement("span");C.className="bp-dim",C.textContent=`v${d}`,E.appendChild(C)}let k=document.createElement("span");if(k.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":c>0?"bp-tone-bad":"bp-dim"),k.textContent=p>0?`${h}/${p} ${u("gpui.mgmt.plan.done","done")}`:m>0?u("web.plan.awaiting","{n} awaiting approval",{n:m}):u("gpui.mgmt.plan.nothing","Nothing awaits your approval"),E.appendChild(k),!t.live){let C=document.createElement("span");C.className="bp-mgmt-pill",C.textContent=u("gpui.mgmt.plan.saved","saved plan"),E.appendChild(C)}if(g.appendChild(E),f>0){let C=document.createElement("div");C.className="bp-plan-segbar";for(let S of y){if(S.count<=0)continue;let R=document.createElement("div");R.className=`bp-plan-seg bp-tone-bg-${S.tone}`,R.style.flexGrow=String(S.count),C.appendChild(R)}g.appendChild(C)}e.appendChild(g);let A=document.createElement("div");if(A.className="bp-mgmt-head",m>0){let C=document.createElement("button");C.type="button",C.className="primary bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-approve-all"),C.textContent=u("gpui.mgmt.plan.all","Approve all"),C.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(C)}if(t.routing){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-stop"),C.textContent=u("gpui.mgmt.plan.stop","Stop routing"),C.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(C)}if(t.live&&h>0){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-verify"),C.textContent=u("gpui.mgmt.plan.verify","Verify"),C.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(C)}let N=document.createElement("span");N.className="bp-mgmt-flex1";let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.setAttribute("data-testid","mgmt-plan-hide"),M.textContent=this.planHideDone?u("gpui.mgmt.plan.show","Show done"):u("gpui.mgmt.plan.hide","Hide done"),M.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.append(N,M),e.appendChild(A);let D=Array.isArray(t.asks)?t.asks:[];if(D.length>0){let C=D.map((z)=>z.what||"").filter(Boolean).join(", "),S=D[0]?.note||"",R=document.createElement("div");R.className="bp-plan-elsewhere";let q=document.createElement("div");q.className="bp-plan-ask-col";let T=document.createElement("div");if(T.className="bp-tone-warn",T.textContent=C?u("gpui.mgmt.plan.requested","Approval requested: {what}",{what:C}):u("gpui.mgmt.plan.reqplain","Approval requested"),q.appendChild(T),S){let z=document.createElement("div");z.className="bp-dim",z.textContent=S,q.appendChild(z)}R.appendChild(q),e.appendChild(R)}if(this.planStatus){let C=document.createElement("div");C.className="bp-mgmt-note bp-plan-err bp-tone-bad";let S=document.createElement("span");S.className="bp-mgmt-flex1",S.textContent=this.planStatus==="KiCad refused"?u("gpui.mgmt.plan.refused","KiCad refused"):xe(this.planStatus);let R=document.createElement("button");R.type="button",R.className="icon",R.textContent="×",R.title=u("common.close","Close"),R.addEventListener("click",()=>{this.planStatus="",this.render()}),C.append(S,R),e.appendChild(C)}if(t.keys_note){let C=document.createElement("div");C.className="bp-mgmt-note bp-dim";let S="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";C.textContent=t.keys_note===S?u("gpui.mgmt.plan.keysnote",S):xe(t.keys_note),e.appendChild(C)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let C=document.createElement("div");C.className="bp-plan-stackup";let S=document.createElement("button");S.type="button",S.className="bp-plan-stackup-head",S.setAttribute("data-testid","mgmt-plan-stackup-toggle"),S.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let R=document.createElement("span");R.className="bp-plan-chev",R.textContent=this.planStackupOpen?"▾":"▸";let q=document.createElement("span");if(q.textContent=u("gpui.mgmt.plan.stackup","Stackup & impedances"),S.append(R,q),S.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),C.appendChild(S),this.planStackupOpen){let T=document.createElement("div");if(T.className="bp-plan-stackup-body",T.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let z=document.createElement("div");z.className="bp-dim",z.textContent=W,T.appendChild(z)}for(let z of _){let J=document.createElement("div");J.className="bp-mgmt-faint",J.textContent=`· ${z}`,T.appendChild(J)}C.appendChild(T)}e.appendChild(C)}let H=(C,S,R,q)=>{let T=document.createElement("button");return T.type="button",T.className="bp-mgmt-btn bp-plan-chip-btn"+(S?" active":""),T.setAttribute("data-testid",R),T.setAttribute("aria-pressed",S?"true":"false"),T.textContent=C,T.addEventListener("click",q),T},ue=document.createElement("div");if(ue.className="bp-plan-viewbar",ue.append(H(u("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),H(u("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),H(u("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let C=document.createElement("span");C.className="bp-plan-sep";let S=document.createElement("span");S.className="bp-plan-sep";let R=document.createElement("button");R.type="button",R.className="bp-mgmt-btn bp-plan-mini-btn",R.setAttribute("data-testid","mgmt-plan-fit"),R.textContent=u("gpui.mgmt.plan.fit","Fit"),R.addEventListener("click",()=>this.planCanvas?.fitAll()),ue.append(C,H(u("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),H(u("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),H(u("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),S,H(u("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),R)}let me=document.createElement("span");me.className="bp-mgmt-flex1";let se=document.createElement("button");se.type="button",se.className="bp-mgmt-btn bp-plan-mini-btn",se.setAttribute("data-testid","mgmt-plan-expand"),se.textContent=this.planExpanded?u("gpui.mgmt.plan.compact","Compact"):u("gpui.mgmt.plan.expand","Expand"),se.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),ue.append(me,se),e.appendChild(ue);let ye=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),Le=ye&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},Ae=ye&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(Ae.bands??[]).map((C)=>{let S=this.planOptimistic.get(C.id);if(!S)return{...C};return{...C,...S,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Be=(Ae.regions??[]).map((C)=>{let S=this.planOptimistic.get(C.id);if(!S)return{...C};return{...C,...S,edited:!0,state:C.state==="proposed"?"edited":C.state}}),B=[],pe=(t.layers??[]).map((C)=>{let S=[];for(let R of C.items??[]){let q=this.planOptimistic.get(R.id);if(!q){S.push(R);continue}let T={...R,width:typeof q.width==="number"?q.width:R.width,locked:typeof q.locked==="boolean"?q.locked:R.locked,edited:!0,state:R.state==="proposed"?"edited":R.state};if(typeof q.layer==="string"&&q.layer!==C.layer)B.push({target:q.layer,item:T});else S.push(T)}return{...C,items:S}});for(let C of B){let S=pe.find((R)=>R.layer===C.target);if(S)S.items=[...S.items??[],C.item]}let ne=Rt(pe,t.copper_layers),Z=this.planGridMode==="all"?ne.map((C)=>C.layer):this.planGridMode==="single"?[this.planShownLayers.find((C)=>ne.some((S)=>S.layer===C))??rt(ne)[0]??ne[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((C)=>ne.some((S)=>S.layer===C))?this.planShownLayers.slice(0,2):rt(ne);if(this.planViewMode!=="list"&&ne.length>1){let C=document.createElement("div");C.className="bp-plan-layerbar";for(let S of ne){let R=Z.includes(S.layer);C.appendChild(H(S.title||S.layer,R,`mgmt-plan-layerpill-${S.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"){if(!Z.includes(S.layer))this.planShownLayers=Z.length>=2?[Z[0],S.layer]:[...Z,S.layer]}else this.planGridMode="single",this.planShownLayers=[S.layer];this.render()}))}e.appendChild(C)}let le=(C,S)=>{let R=this.planOptimistic.get(C)??{};if(this.planOptimistic.set(C,{...R,...S}),typeof S.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"&&!Z.includes(S.layer))this.planShownLayers=Z.length>=2?[Z[0],S.layer]:[...Z,S.layer]}let q=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:C,fields:S}],...q!==void 0?{base:q}:{}})};if(this.planCommitFields=le,this.planSelectedId){let C="",S=null;for(let R of pe){let q=(R.items??[]).find((T)=>T.id===this.planSelectedId);if(q){C=R.layer,S=q;break}}if(S){let R=document.createElement("div");R.className="bp-plan-inspector",R.setAttribute("data-testid","mgmt-plan-inspector");let q=document.createElement("div");q.className="bp-plan-ins-row";let T=document.createElement("span");T.className="bp-plan-ins-sw",T.style.background=S.kind==="corridor"?vt(S.name||S.id,S.color||""):ft(S.name||S.id,S.color||"");let z=document.createElement("span");z.className="bp-mgmt-strong",z.textContent=S.name||S.id;let J=document.createElement("span");if(J.className="bp-dim",J.textContent=C,q.append(T,z,J),S.edited||S.state==="edited"){let be=document.createElement("span");be.className="bp-plan-ins-pill warn",be.textContent=u("gpui.mgmt.plan.edited","Edited"),q.appendChild(be)}if(S.locked){let be=document.createElement("span");be.className="bp-plan-ins-pill",be.textContent=u("gpui.mgmt.plan.locked","Locked"),q.appendChild(be)}let Me=document.createElement("span");Me.className="bp-mgmt-flex1",q.appendChild(Me);let re=document.createElement("button");if(re.type="button",re.className="bp-mgmt-btn bp-plan-mini-btn",re.setAttribute("data-testid","mgmt-plan-lock"),re.textContent=S.locked?u("gpui.mgmt.plan.unlock","Unlock"):u("gpui.mgmt.plan.lock","Lock"),re.addEventListener("click",()=>le(S.id,{locked:!S.locked})),q.appendChild(re),S.state==="proposed"||S.state==="edited"){let be=document.createElement("button");be.type="button",be.className="primary bp-mgmt-btn bp-plan-mini-btn",be.textContent=u("android.hub.machines.approve","Approve"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!0}));let de=document.createElement("button");de.type="button",de.className="bp-mgmt-btn bp-plan-mini-btn",de.textContent=u("gpui.mgmt.plan.reject","Reject"),de.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!1})),q.append(be,de)}let ke=document.createElement("button");ke.type="button",ke.className="bp-mgmt-btn bp-plan-mini-btn",ke.setAttribute("data-testid","mgmt-plan-note-toggle"),ke.textContent=u("gpui.mgmt.plan.addnote","Add note"),ke.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let He=document.createElement("button");if(He.type="button",He.className="icon",He.textContent="×",He.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),q.append(ke,He),R.appendChild(q),!S.locked){let be=document.createElement("div");if(be.className="bp-plan-ins-row",S.kind==="corridor"){let he=typeof S.width==="number"?S.width:1.5,Re=document.createElement("span");Re.className="bp-dim",Re.textContent=u("gpui.mgmt.plan.width","Width");let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn bp-plan-mini-btn",X.setAttribute("data-testid","mgmt-plan-w-down"),X.textContent="-",X.addEventListener("click",()=>{let Ke=Math.round(Math.max(0.15,he-0.25)*100)/100;le(S.id,{width:Ke})});let oe=document.createElement("span");oe.className="bp-plan-ins-val",oe.textContent=`${he.toFixed(2)}mm`;let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn bp-plan-mini-btn",je.setAttribute("data-testid","mgmt-plan-w-up"),je.textContent="+",je.addEventListener("click",()=>{let Ke=Math.round(Math.min(25,he+0.25)*100)/100;le(S.id,{width:Ke})});let We=document.createElement("span");We.className="bp-plan-sep",be.append(Re,X,oe,je,We)}let de=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((he)=>he.layer):pe.map((he)=>he.layer);if(de.length>0){let he=document.createElement("span");he.className="bp-dim",he.textContent=u("gpui.mgmt.plan.layer.move","Move to layer"),be.appendChild(he);for(let Re of de)be.appendChild(H(Re,Re===C,`mgmt-plan-move-${Re}`,()=>{if(Re!==C)le(S.id,{layer:Re})}))}R.appendChild(be)}if(this.planNoteOpen){let be=document.createElement("form");be.className="bp-plan-note-form";let de=document.createElement("input");de.type="text",de.className="bp-plan-note-input",de.setAttribute("data-testid","mgmt-plan-note-input"),de.placeholder=u("gpui.mgmt.plan.note.placeholder","Steering note for router…");let he=document.createElement("button");he.type="submit",he.className="primary bp-mgmt-btn bp-plan-mini-btn",he.setAttribute("data-testid","mgmt-plan-note-submit"),he.textContent=u("gpui.mgmt.plan.addnote","Add note"),be.append(de,he),be.addEventListener("submit",(Re)=>{Re.preventDefault();let X=de.value.trim();if(!X)return;de.value="",this.planNoteOpen=!1;let oe=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:S.id,text:X}],...oe!==void 0?{base:oe}:{}})}),R.appendChild(be)}if(this.planViewMode!=="list"&&!S.locked){let be=document.createElement("div");be.className="bp-plan-hint",be.textContent=u("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),R.appendChild(be)}e.appendChild(R)}}let j=document.createElement("div");j.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),j.setAttribute("data-testid","mgmt-plan-rows");let Y=u("gpui.mgmt.plan.done","done");for(let C of pe){let S=C.items??[],R=document.createElement("div");R.className="bp-mgmt-group-head bp-plan-layer-head";let q=document.createElement("div");q.className="bp-mgmt-row-line";let T=document.createElement("span");T.className="bp-mgmt-strong",T.textContent=C.layer;let z=document.createElement("span");if(z.className="bp-dim bp-mgmt-flex1",z.textContent=`${C.role?`${C.role} · `:""}${C.done??0}/${S.length} ${Y}`,q.append(T,z),C.status!=="approved"&&S.length>0){let J=document.createElement("button");J.type="button",J.className="bp-mgmt-btn",J.textContent=u("gpui.mgmt.plan.layer","Approve layer"),J.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!0}));let Me=document.createElement("button");Me.type="button",Me.className="bp-mgmt-btn",Me.textContent=u("gpui.mgmt.plan.reject","Reject"),Me.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!1})),q.append(J,Me)}if(R.appendChild(q),C.stackup){let J=document.createElement("div");J.className="bp-plan-layer-stackup",J.textContent=C.stackup,R.appendChild(J)}j.appendChild(R);for(let J of S){if(this.planHideDone&&qn(J))continue;let Me=this.planSelectedId===J.id,re=document.createElement("div");re.className="bp-mgmt-row bp-plan-row"+(Me?" active":""),re.setAttribute("data-testid",`mgmt-plan-row-${J.id}`);let ke=document.createElement("div");ke.className="bp-mgmt-row-line";let He=document.createElement("span");He.className=`bp-plan-swatch bp-plan-st-${J.state||"proposed"}`,He.style.setProperty("--swatch-color",J.color||"#8a8a8a");let be=document.createElement("span");be.className="bp-mgmt-flex1"+(J.state==="blocked"||J.state==="failed"?" bp-tone-bad":J.state==="edited"?" bp-tone-warn":J.state==="rejected"||J.state==="routed"||J.state==="verified"?" bp-dim":""),be.textContent=`${J.name||J.id}${J.locked?" \uD83D\uDD12":""}`;let de=[];if(J.kind==="plane"){if(J.reference)de.push(u("gpui.mgmt.plan.reference","over {layer}",{layer:J.reference}))}else{let X=J.nets??0;de.push(X===1?u("web.plan.net.one","1 net"):u("web.plan.nets","{n} nets",{n:X}))}if(typeof J.width==="number"&&Number.isFinite(J.width))de.push(`${J.width.toFixed(2)}mm`);if(J.impedance)de.push(J.impedance);let he=de.join(" · "),Re=document.createElement("span");if(Re.className="bp-plan-mark "+(J.state==="blocked"||J.state==="failed"?"bp-tone-bad":J.state==="verified"||J.state==="routed"?"bp-tone-ok":J.state==="approved"?"bp-tone-accent":"bp-dim"),Re.textContent=Kn(J),ke.append(He,be,Re),J.state==="proposed"||J.state==="edited"){let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn",X.textContent="✓",X.title=u("gpui.mgmt.plan.layer","Approve layer"),X.addEventListener("click",(je)=>{je.stopPropagation(),n("plan.approve",{layer:"",ids:[J.id],approve:!0})});let oe=document.createElement("button");oe.type="button",oe.className="bp-mgmt-btn",oe.textContent="✗",oe.title=u("gpui.mgmt.plan.reject","Reject"),oe.addEventListener("click",(je)=>{je.stopPropagation(),n("plan.approve",{layer:"",ids:[J.id],approve:!1})}),ke.append(X,oe)}if(re.appendChild(ke),he){let X=document.createElement("div");X.className="bp-mgmt-row-sub bp-plan-detail bp-dim",X.textContent=he,re.appendChild(X)}if(J.state==="routing"&&typeof J.total==="number"&&J.total>0){let X=document.createElement("div");X.className="bp-plan-microbar";let oe=document.createElement("div");oe.className="bp-plan-microbar-fill";let je=Math.max(0,Math.min(100,Math.round((J.routed??0)/J.total*100)));oe.style.width=`${je}%`,X.appendChild(oe),re.appendChild(X)}if(J.problem_text){let X=document.createElement("div");X.className="bp-plan-problem",X.textContent=J.problem_text,re.appendChild(X)}re.addEventListener("click",()=>{this.planSelectedId=J.id,n("plan.focus",{id:J.id}),this.render()}),j.appendChild(re)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new tn({onSelect:(q)=>{if(this.planSelectedId=q,!q)this.planNoteOpen=!1;this.render()},onFocusItem:(q)=>{n("plan.focus",{id:q})},onOptimisticPatch:(q,T)=>{let z=this.planOptimistic.get(q)??{};this.planOptimistic.set(q,{...z,...T})},onRevertOptimistic:(q)=>{if(this.planOptimistic.delete(q)||this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(q,T)=>{(this.planCommitFields??le)(q,T)},onApproveLayer:(q,T)=>{n("plan.approve",{layer:q,ids:[],approve:T})},onQuickApprove:(q,T)=>{n("plan.approve",{layer:"",ids:q,approve:T})}});let C=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,S=this.planExpanded||this.panelEl.clientWidth>=540||C;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:Z,selectedId:this.planSelectedId,board:Le,bands:we,regions:Be,layers:ne,copperLayers:t.copper_layers},S);let R=document.createElement("div");R.className="bp-plan-canvas-scroll",R.appendChild(this.planCanvas.root),e.appendChild(R)}if(this.planViewMode!=="canvas")e.appendChild(j);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let C=document.createElement("div");C.className="bp-plan-footer",C.textContent=u("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(C)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,x={})=>{let k=this.watchGen,A=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:A,action:E,...x}).catch((N)=>{if(k!==this.watchGen||A!==this.project)return;this.fabStatus=N instanceof Error?N.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=u("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Xn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=u("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let h=document.createElement("span"),p=(l?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),h.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(h),l?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(E)}if(!l?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),c.appendChild(E)}if(l?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(E)}m.appendChild(c),o.appendChild(m);let d=Yn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(d.button?"bp-tone-warn":"bp-dim"),f.textContent=d.text,y.appendChild(f),d.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=d.button,E.addEventListener("click",()=>n("drc")),y.appendChild(E)}b.appendChild(y),o.appendChild(b);for(let E of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=E,o.appendChild(x)}for(let E of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=u("gpui.mgmt.fab.apply","Apply"),N.addEventListener("click",()=>n("apply",{key:E.key})),k.append(A,N),x.appendChild(k),o.appendChild(x)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let k=t.stackup.by==="proposed",A=document.createElement("span");if(A.className="bp-mgmt-flex1 "+(k?"bp-tone-warn":"bp-dim"),A.textContent=`${k?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(A),k){let N=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=u("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:N})),x.appendChild(M)}E.appendChild(x),o.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let k=document.createElement("span");k.className="bp-mgmt-flex1 bp-tone-warn",k.textContent=u("gpui.mgmt.fab.changed","Changed since you last looked");let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=u("gpui.mgmt.fab.seen","Seen"),A.addEventListener("click",()=>n("seen")),x.append(k,A),E.appendChild(x);for(let N of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=N,E.appendChild(M)}o.appendChild(E)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=u("gpui.mgmt.fab.limit","Limit");let k=document.createElement("span");k.className="bp-mgmt-col",k.textContent=u("gpui.mgmt.fab.free","Base price");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=u("gpui.mgmt.fab.extra","Costs more");let N=document.createElement("span");N.className="bp-mgmt-col bp-mgmt-col-read",N.textContent=u("gpui.mgmt.fab.readcol","Read"),E.append(x,k,A,N),o.appendChild(E);for(let D of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(D.changed?" bp-tone-warn":D.inherited?" bp-dim":""),H.textContent=`${D.changed?"• ":""}${D.label??""}`;let ue=document.createElement("span");ue.className="bp-mgmt-col",ue.textContent=D.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=D.extra?.text||"—";let se=D.free&&typeof D.free==="object"?D.free:D.extra,ye=se?.fetched??"",Le=Boolean(ye)&&se?.confidence!=="published",Ae=ye?Le?`${ye}*`:ye:"—",we=se?.source??"",Be;if(we.startsWith("https://")&&ye){let B=document.createElement("a");B.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",B.href=we,B.target="_blank",B.rel="noopener noreferrer",B.textContent=Ae,Be=B}else{let B=document.createElement("span");B.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",B.textContent=Ae,Be=B}_.append(H,ue,me,Be),W.appendChild(_),o.appendChild(W)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=u("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var xs={trs:(e)=>e,t:(e,t)=>t},Cs=new Set(["/settle"]);function pi(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function hi(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ui(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function bi(e,t=xs){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=Cs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:m}=mi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:m,dotClass:hi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function gi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let b of i)p.set(b.id,b.title||b.id);let d=new Set;for(let b of l)if(b.action.type==="thread")d.add(b.action.id);for(let b of n.threads){if(!b.id||d.has(b.id))continue;d.add(b.id);let{urgency:y,want:f}=mi(b);l.push({label:b.title||"Untitled thread",place:b.project?p.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:hi(b),action:{type:"thread",id:b.id}})}}let m=[];for(let p=0;p0)m.push({score:f,index:p,item:d})}m.sort((p,d)=>{if(o){let f=(d.item.urgency??0)-(p.item.urgency??0);if(f!==0)return f}if(d.score!==p.score)return d.score-p.score;let b=p.item.kind==="thread"?0:1,y=d.item.kind==="thread"?0:1;if(b!==y)return b-y;return p.index-d.index});let c=new Set,h=[];for(let p of m){let d=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(c.has(d))continue;if(c.add(d),h.push(p.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=bi(t,{t:u,trs:xe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=gi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=u("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,p)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(p,d),m.appendChild(b),d{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var Ss=new Set(["resume","raise","retry","move","signin"]);function yi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function jt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Ss.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function wi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class rn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${u("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",u("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${u("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",u("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let c=document.createElement("div");c.className="bp-set-head",c.textContent=u("home.machine","Home machine");let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";d.textContent=b,p.appendChild(d);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?u("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):u("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?u("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):u("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?u("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):u("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(p.appendChild(y),h.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=u("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),h.appendChild(f)}m.append(c,h),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=u("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=u("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let l=document.createElement("div");l.className="bp-set-head",l.textContent="Paired devices",o.appendChild(l);try{let m=await this.cb.onLoadDevices();if(m.length===0){let c=document.createElement("div");c.className="bp-dim",c.textContent="No devices listed.",o.appendChild(c)}else for(let c of m){let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div");if(d.textContent=c.title||c.head||"",p.appendChild(d),c.text||c.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=c.text||c.detail||"",p.appendChild(b)}if(h.appendChild(p),c.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of c.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||u("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}h.appendChild(b)}o.appendChild(h)}}catch(m){let c=document.createElement("div");c.className="bp-dim";let h=m instanceof Error&&m.message?m.message:"Not available from a browser";c.textContent=`${h} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(c)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function Ce(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=Ce("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function on(e){return Ce("pre","bp-context-code",e)}function Ls(e){return Ce("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,xe(e))}function Ht(e,t){let n=Ce("div","bp-context-row");return n.append(Ce("strong",void 0,e),Ls(t)),n}class ln{fetchContext;dialog=Ce("dialog","bp-context");title=Ce("h2");cwd=Ce("div","bp-context-path");tabs=Ce("div","bp-context-tabs");body=Ce("div","bp-context-body");notice=Ce("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ce("div","bp-context-head"),i=Ce("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(u("common.refresh","Refresh"),()=>{this.load()}),yt(u("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=u("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=u("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[u("thread.context.instructions","Instructions"),u("thread.context.system","System Prompt"),u("thread.context.skills","Skills"),u("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ce("p","bp-dim",u("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ce("details","bp-context-card"),i=Ce("summary");if(i.append(Ht(t.path,t.status),Ce("small","bp-dim",u("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,on(t.preview)),t.note)n.append(Ce("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ce("div","bp-context-row"),n=yt(u("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=u("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ce("p","bp-dim",u("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[u("thread.context.base","Backplane"),e.sections.base],[u("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[u("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ce("h3",void 0,i),on(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ce("h3",void 0,xe(t)));for(let i of n){let s=Ce("article","bp-context-card");s.append(Ht(i.name,i.status),Ce("p",void 0,i.description),Ce("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ce("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ce("p","bp-dim",u("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ce("article","bp-context-card");n.append(Ht(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Ht(s.name,s.status),on(a)),s.cwd)n.append(Ce("small","bp-context-path",s.cwd))}if(t.error)n.append(Ce("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?u("thread.context.trust","Trust and enable"):i==="disable"?u("thread.context.disable","Disable"):u("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ce("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var Ei="http://www.w3.org/2000/svg";function xi(){let e=document.createElementNS(Ei,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ei,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function As(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ci(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class cn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=u("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=u("thread.new","New thread"),l.setAttribute("aria-label",u("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?u("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):u("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?u("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):u("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=u("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=u("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=u("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=u("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=u("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=u("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),n.appendChild(h)}let i=document.createElement("span");i.className=`bp-dot ${As(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let h=document.createElement("span");if(h.className="bp-badge-need",h.textContent=e.want==="approval"?"!":"•",e.say)h.title=e.say;n.appendChild(h)}else if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=u("tools.pinned","Pinned");n.appendChild(h)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?yi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,l.appendChild(m);for(let h of r.actions){if(!jt(h,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=h.label,p.setAttribute("data-testid",`need-${h.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(d)=>{d.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(h).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(p)}o.append(n,l);let c=this.needErr.get(e.id);if(c){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=c,o.appendChild(h)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let l=document.createElement("section");l.className="bp-side-section",l.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),l.appendChild(m);for(let c of o)l.appendChild(this.renderSectionThreadRow(c,!1));e.appendChild(l);continue}if(r.kind==="projects"){let o=r.rows.filter((c)=>{if(!t)return!0;if((c.title||c.id).toLowerCase().includes(t))return!0;if((c.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((c.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),l=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!l&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),l){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let h=r.count??o.length,p=r.open?"▾":"▸";if(c.textContent=`${r.title.toUpperCase()} (${h}) ${p}`,r.hint)c.title=r.hint;c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(c)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!l||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let c=document.createElement("div");c.className="bp-side-empty",c.textContent="No projects yet.",m.appendChild(c)}for(let c of o){let h=document.createElement("div");if(h.className="bp-proj-group"+(c.off?" bp-dim":""),h.setAttribute("data-project-id",c.id),c.nav||c.key)h.setAttribute("data-project-key",c.nav||c.key||"");let p=document.createElement("div");p.className="bp-proj-head";let d=document.createElement("button");d.type="button",d.className="bp-proj-toggle";let b=xi();if(c.css)b.style.color=c.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=c.title||c.id,d.append(b,y),c.fold==="project-fold"&&c.nav)d.addEventListener("click",()=>this.cb.onToggleProjectFold?.(c.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=u("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${c.id}`),c.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(c.id)}),p.append(d,f),h.appendChild(p),!c.folded||Boolean(t)){let g=Boolean(t)&&(c.title||c.id).toLowerCase().includes(t);for(let E of c.swarms??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(E,!0))}for(let E of c.threads??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(E,!0))}if(s&&s.project===c.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Ci(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(h)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!t,m=xi();if(i.css)m.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(m,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=u("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${i.id}`),h.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,h),a.appendChild(r),!l)for(let p of s)a.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:Ci(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=u("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let c of this.bots){let h=document.createElement("div");h.className="bp-thread-row"+(c.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",c.color)p.style.backgroundColor=c.color;let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`@${c.name}`,h.append(p,d),h.addEventListener("click",()=>this.cb.onSelectBot(c)),n.appendChild(h)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let l=document.createElement("span");l.textContent=u("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(l,m),r.appendChild(o);for(let c of this.rooms){let h=document.createElement("div");h.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${c.name}`,h.appendChild(p),r.appendChild(h)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ps(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ns(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/m:0));s[a]=c<0?c*32768:c*32767}return s}class dn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ps(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Ns(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var ki=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Si=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Li=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Ai=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ms=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ts=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Bs=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class pn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,p},r=(h)=>{let p=0,d=0,b=0;for(let y=1;y<=h.maxBits;y++){p|=a(1);let f=h.counts[y];if(p-f{let p=l+h;if(p>t)throw Error("inflated frame exceeds limit");if(p<=o.length)return;let d=o.length;while(d{m(1),o[l++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=a(1),p=a(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let d=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(d^65535)!==b)throw Error("invalid stored block length");if(n+d>e.length)throw Error("truncated stored payload");m(d);for(let y=0;y=e.length)break}else if(p===1||p===2){let d=Ts,b=Bs;if(p===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,E=new Uint8Array(19);for(let M=0;Mk)throw Error("code length overflow");for(let _=0;_k)throw Error("code length overflow");N+=D}else if(M===18){let D=a(7)+11;if(N+D>k)throw Error("code length overflow");N+=D}else throw Error("invalid code length symbol")}d=Et(A,y),b=Et(A.subarray(y),f)}while(!0){let y=r(d);if(y<256)c(y);else if(y===256)break;else{let f=y-257;if(f>=ki.length)throw Error("invalid length symbol");let g=ki[f]+(Si[f]?a(Si[f]):0),E=r(b);if(E>=Li.length)throw Error("invalid distance symbol");let x=Li[E]+(Ai[E]?a(Ai[E]):0);m(g);let k=this.winPos-x&32767;for(let A=0;A{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new pn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(l))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Is=new TextDecoder;function Pi(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ni(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,m=i(o&31);if(m===null)return null;switch(l){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let c=e.subarray(t,t+m);return t+=m,c}case 3:{if(t+m>e.length)return null;let c=Is.decode(e.subarray(t,t+m));return t+=m,c}case 4:{if(m>e.length)return null;let c=Array(m);for(let h=0;h=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Ti(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new Mi(m),h=[],p=[],d=0,b=0;while(c.more()){let y=c.nextU32(),f=h.length,g=1/0,E=1/0,x=-1/0,k=-1/0;if(a===2)d=d+c.nextI32()|0,b=b+c.nextI32()|0,h.push(d,b),g=x=d,E=k=b;else{let N=Math.min(c.nextU32(),1048576);for(let M=0;Mx)x=d;if(bk)k=b}}let A=(h.length-f)/2;if(A>0){let N=a===2||A===1?2:a===0?0:1,M=a===0?0:o;p.push({info:y,x0:g-M,y0:E-M,x1:x+M,y1:k+M,at:f,n:A,kind:N})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(h),pieces:p}}function Bi(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Ii(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,c=(t-l)/r;if(m<0||m>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var Ri=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ji(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class hn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Hi(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,m=-1,c=null,h=new hn,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let d=document.createElement("div");d.className="bp-pane-bar bp-browser-nav";function b(Z,le,j){let Y=document.createElement("button");if(Y.type="button",Y.className="bp-v-btn",Y.textContent=Z,Y.setAttribute("data-testid",le),j)Y.title=j;return Y}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let k=b("Go","browser-go","Navigate");k.type="submit",E.append(x,k);let A=b("Take over","browser-takeover");A.classList.add("is-primary"),d.append(y,f,g,E,A);let N=document.createElement("div");N.className="bp-browser-drive-bar",N.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let D=document.createElement("input");D.type="text",D.className="bp-browser-input",D.placeholder="Type text or press Enter/Tab/Arrows…",D.autocomplete="off",D.spellcheck=!1,D.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");M.append(D,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[Z,le]of Ri){let j=b(Z,`browser-key-${le}`);j.addEventListener("click",()=>we("press",{key:le})),_.append(j)}N.append(M,_);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ue=document.createElement("div");ue.className="bp-browser-stage",ue.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let se=document.createElement("div");se.className="bp-pane-empty",se.setAttribute("data-testid","browser-empty"),se.textContent="Loading browser screen…",ue.append(me,se);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,p.append(d,N,H,ue,ye),e.replaceChildren(p);function Le(Z){H.textContent=Z,H.hidden=!Z}function Ae(){N.hidden=!s,ye.hidden=!s,A.textContent=s?"Hand back":"Take over",A.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),A.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function we(Z,le={},j){h.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:Z,...le}),!i)return;j?.(),pe()}catch(Y){if(!i)return;Le(Y instanceof Error?Y.message:String(Y))}})}function Be(Z){we("toolbar",{command:Z},()=>{s=!0,Ae()})}y.addEventListener("click",()=>Be("back")),f.addEventListener("click",()=>Be("forward")),g.addEventListener("click",()=>Be("reload")),E.addEventListener("submit",(Z)=>{Z.preventDefault();let le=ji(x.value);if(!le)return;if(x.value=le,!s)we("takeover",{},()=>{s=!0,Ae()});we("navigate",{url:le},()=>{s=!0,Ae()})}),A.addEventListener("click",()=>{if(s)we("handback",{},()=>{s=!1,Ae()});else we("takeover",{},()=>{s=!0,Ae(),D.focus()})});function B(){let Z=D.value;if(!Z)return;D.value="",we("type",{text:Z})}W.addEventListener("click",B),D.addEventListener("keydown",(Z)=>{if(!s)return;if(Z.key==="Enter"){if(Z.preventDefault(),D.value)B();we("press",{key:"Enter"});return}if(Z.key==="Tab"||Z.key==="Escape"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="ArrowLeft"||Z.key==="ArrowRight"||Z.key==="Backspace"&&D.value==="")Z.preventDefault(),we("press",{key:Z.key})}),me.addEventListener("click",(Z)=>{if(!s||!a)return;let le=me.getBoundingClientRect(),j=Ii(Z.clientX,Z.clientY,{left:le.left,top:le.top,width:le.width,height:le.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!j)return;we("click",j)}),me.addEventListener("wheel",(Z)=>{if(!s||!a)return;Z.preventDefault();let le=Math.round(Z.deltaX),j=Math.round(Z.deltaY);if(le===0&&j===0)return;we("scroll",{dx:le,dy:j})},{passive:!1});async function pe(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let Z=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(Z.ok){let le=await Z.blob();if(!i)return;let j=URL.createObjectURL(le),Y=r;if(r=j,me.src=j,me.hidden=!1,se.hidden=!0,a=!0,Y)URL.revokeObjectURL(Y)}else if(!a)me.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)me.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ne=t.hub.onFrame((Z)=>{if(!i)return;if(Z.t==="shot"&&Z.bot===n){if(typeof Z.n==="number"){if(Z.n===m)return;m=Z.n}pe()}});return pe(),{destroy(){if(i=!1,ne(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function U(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Dt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Fi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function js(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Di(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Hs(e){let t=Fi(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function $i(e,t,n,i){let s=!0,a="",r="",o=U("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=U("div","bp-pane-bar"),m=U("div","bp-files-crumbs"),c=U("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void f(a)),l.append(m,c);let h=U("div","bp-files-split"),p=U("div","bp-files-list");p.setAttribute("data-testid","files-list");let d=U("div","bp-files-preview");d.setAttribute("data-testid","files-preview"),d.append(U("div","bp-pane-empty","Select a file to preview")),h.append(p,d),o.append(l,h),e.replaceChildren(o);function b(){m.replaceChildren();let g=U("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let E=a.split("/").filter(Boolean),x="";for(let k of E){x=x?`${x}/${k}`:k;let A=x;m.append(U("span","bp-vh-sep","/"));let N=U("button","bp-crumb-btn",k);N.type="button",N.addEventListener("click",()=>void f(A)),m.append(N)}}async function y(g,E,x){r=g,d.replaceChildren();let k=U("div","bp-files-prev-head");k.append(U("span","bp-files-prev-name",g));let A=U("div","bp-files-prev-acts"),N=Hs(E);if(N){let _=U("button","bp-v-btn is-primary",`Open in ${N}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(N,g)),A.append(_)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,D=U("a","bp-v-btn","Download");D.href=M,D.download=E,A.append(D),k.append(A),d.append(k);let W=Fi(E);if(js(W)){let _=U("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=E,H.src=M,_.append(H),d.append(_);return}if(x>524288&&!Di(W)){d.append(U("div","bp-pane-empty",`Binary file (${Dt(x)}). Use Download to save.`));return}if(Di(W)||x<=65536){let _=U("div","bp-pane-empty","Loading…");d.append(_);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||r!==g)return;if(!H.ok){_.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){_.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=E,ne.src=M,d.append(ne);return}let me=262144,se=[],ye=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:Z,value:le}=await ne.read();if(Z||!le)break;if(ye+le.byteLength>me){let j=me-ye;if(j>0)se.push(le.subarray(0,j)),ye+=j;Le=!0,await ne.cancel();break}se.push(le),ye+=le.byteLength}}finally{ne.releaseLock()}}if(!s||r!==g)return;let Ae=new Uint8Array(ye),we=0;for(let ne of se)Ae.set(ne,we),we+=ne.byteLength;let Be=!1;for(let ne=0;nek.dir===A.dir?k.name.localeCompare(A.name):k.dir?-1:1),p.replaceChildren(),g){let k=U("button","bp-file-row is-dir");k.type="button",k.append(U("span","bp-file-icon","↰"),U("span","bp-file-name",".."));let A=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";k.addEventListener("click",()=>void f(A)),p.append(k)}if(x.length===0){p.append(U("div","bp-pane-empty","Empty folder"));return}for(let k of x){let A=g?`${g}/${k.name}`:k.name,N=U("button","bp-file-row"+(k.dir?" is-dir":"")+(A===r?" is-sel":""));N.type="button",N.setAttribute("data-testid",`file-row-${k.name}`),N.append(U("span","bp-file-icon",k.dir?"▸":"·"),U("span","bp-file-name",k.name),U("span","bp-file-size",k.dir?"":Dt(k.size))),N.addEventListener("click",()=>{if(k.dir)f(A);else p.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),N.classList.add("is-sel"),y(A,k.name,k.size)}),p.append(N)}}catch(E){if(!s)return;p.replaceChildren(U("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return f(""),{destroy(){s=!1}}}function Gi(e,t,n){let i=!0,s=U("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=U("div","bp-pane-bar"),r=U("span","bp-diff-summary","Loading diff…"),o=U("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let l=U("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(U("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof c?.diff==="string"?c.diff:"";if(!h.trim()){r.textContent="Clean working tree",l.append(U("div","bp-pane-empty","No uncommitted changes."));return}let p=h.split(` +`),d=0,b=0,y=0,f=document.createDocumentFragment(),g=U("div","bp-diff-file");for(let E of p){if(E.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=U("div","bp-diff-file"),d++;let x=E.match(/ b\/(.+)$/);g.append(U("div","bp-diff-file-head",x?x[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))g.append(U("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))g.append(U("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))b++,g.append(U("div","bp-diff-line is-add",E));else if(E.startsWith("-"))y++,g.append(U("div","bp-diff-line is-del",E));else g.append(U("div","bp-diff-line",E))}if(g.childNodes.length>0)f.append(g);r.textContent=`${d||1} file${d===1?"":"s"} · +${b} -${y}`,l.append(f)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(U("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return m(),{destroy(){i=!1}}}function Oi(e,t,n){let i=!0,s="checks",a=U("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=U("div","bp-pane-bar"),o=U("div","bp-review-tabs"),l=U("button","bp-v-btn is-on","Checks"),m=U("button","bp-v-btn","BOM"),c=U("button","bp-v-btn","Comments");l.type=m.type=c.type="button",o.append(l,m,c);let h=U("button","bp-v-btn","Refresh");h.type="button",h.addEventListener("click",()=>void y()),r.append(o,h);let p=U("div","bp-review-body");p.setAttribute("data-testid","review-body"),a.append(r,p),e.replaceChildren(a);function d(f){s=f,l.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),y()}l.addEventListener("click",()=>d("checks")),m.addEventListener("click",()=>d("bom")),c.addEventListener("click",()=>d("comments"));function b(f){let g=U("div","bp-review-md"),E=f.split(` +`),x=0;while(x{M.preventDefault();let D=A.value.trim();if(!D)return;N.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:D}).then(()=>{A.value="",N.disabled=!1,y()},()=>{N.disabled=!1})}),p.append(k),x.length===0){p.append(U("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let D=U("div","bp-review-comment"+(M.resolved?" is-resolved":"")),W=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");D.append(U("div","bp-review-comment-meta",W),U("div","bp-review-comment-text",M.text)),p.append(D)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(p.replaceChildren(),g.line||g.gate){let E=U("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));p.append(E)}if(g.err)p.append(U("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let E=U("div","bp-review-tasks");g.tasks.forEach((x,k)=>{let A=U("label","bp-review-task"),N=document.createElement("input");N.type="checkbox",N.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:k;N.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void y(),()=>{})}),A.append(N,U("span",void 0,x.text||x.label||`Item ${k+1}`)),E.append(A)}),p.append(E)}if(g.md&&g.md.trim())p.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))p.append(U("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;p.replaceChildren(U("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function Ui(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class un{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,m=n*0.5,c=this.scale,h=this.cx,p=this.cy,d=h-l/c,b=h+l/c,y=p-m/c,f=p+m/c,{off:g,dim:E,lift:x}=this.masks,k=[],A=[];for(let M=0;M>>D&1)===1)continue;if(D===x)A.push(M);else k.push(M)}let N=k.concat(A);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>W.layer&1)===1,H=W.alpha*(_?0.25:1);if(H<=0.01)continue;this.drawChunk(r,W,H,d,y,b,f,h,p,c,l,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let D=0;Da||f.y1r)continue;if(f.n<3)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+h;e.moveTo(g,E);for(let x=1;x0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=d,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let E=(p[g.at]-o)*m+c,x=(p[g.at+1]-l)*m+h;e.moveTo(E+b,x),e.arc(E,x,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=d,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+h;if(f.n===1)e.moveTo(g,E),e.lineTo(g+0.01,E);else{e.moveTo(g,E);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,m,c,h,p){let d=t.pts,b=Ui(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(d[f.at]-l)*c+h,E=(d[f.at+1]-m)*c+p;if(f.kind===2){let x=Math.max(1.5,t.r*c);e.fillStyle=b,e.beginPath(),e.arc(g,E,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,E);for(let x=1;x=0;c--){let h=n.chunks[c];if(h.layer<32&&(m>>>h.layer&1)===1)continue;for(let p=0;pd.x1+r||ad.y1+r)continue;let b=(d.x1-d.x0+1)*(d.y1-d.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,h=s-l.left-l.width*0.5,p=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-h/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-p/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Vi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Wi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function bn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),l=i.replace(/\\/g,"/");if(l.startsWith("/")||/^[A-Za-z]:\//.test(l))return o===l;return o===l||o.endsWith(`/${l}`)}class gn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Ds=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,Ds=`#version 300 es +`,Fs=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,Fs=`#version 300 es +`,$s=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,$s=`#version 300 es +`,Gs=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Gs=[qe(77),qe(83),qe(94)],Us=[qe(53),qe(58),qe(67)],Os=[qe(245),qe(246),qe(248)],Vs=[qe(225),qe(228),qe(233)];function Wi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function _i(e,t,n){let i=Wi(e,e.VERTEX_SHADER,t),s=Wi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Ws(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function _s(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function qi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function Ki(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function fn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class vn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=_i(n,Hs,Ds),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=_i(n,Fs,$s),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Mi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,d=0,b=0;for(let g=0;g>>24&255,k=1-C/255,A=(E>>>16&255)/255,N=(E>>>8&255)/255,M=(E&255)/255,D=g*9;if(C===0&&o&&l&&m){let q=d*9;for(let H=0;H<9;H++)o[q+H]=e[D+H],l[q+H]=t[D+H];let K=d*12;for(let H=0;H<3;H++)m[K+H*4]=A,m[K+H*4+1]=N,m[K+H*4+2]=M,m[K+H*4+3]=1;d++}else if(c&&u&&p){let q=b*9;for(let H=0;H<9;H++)c[q+H]=e[D+H],u[q+H]=t[D+H];let K=b*12;for(let H=0;H<3;H++)p[K+H*4]=A,p[K+H*4+1]=N,p[K+H*4+2]=M,p[K+H*4+3]=k;b++}}let y=o&&l&&m?this.createSubBatch(o,l,m,a*3):null,f=c&&u&&p?this.createSubBatch(c,u,p,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Vi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let q=this.lightTheme?Os:Gs,K=this.lightTheme?Vs:Us;t.uniform3f(this.uBgTop,q[0],q[1],q[2]),t.uniform3f(this.uBgBot,K[0],K[1],K[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),m=Math.sin(this.pitch),c=Math.cos(this.yaw),u=Math.sin(this.yaw),p=[this.target[0]+this.dist*l*u,this.target[1]-this.dist*l*c,this.target[2]+this.dist*m],d=qi([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),b=Math.abs(d[2])>0.99?[0,1,0]:[0,0,1],y=qi(Ki(d,b)),f=Ki(y,d),g=new Float32Array([y[0],f[0],-d[0],0,y[1],f[1],-d[1],0,y[2],f[2],-d[2],0,-fn(y,p),-fn(f,p),fn(d,p),1]),E=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),k=_s(35*Math.PI/180,r/o,E,C),A=Ws(k,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,A),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,d[0],d[1],d[2]);let N=!1,M=[],D=[];for(let q of this.partBatches){let K=e-q.fadeStartMs,H=q.fadeStartMs===0?1:Math.min(1,Math.max(0,K/300));if(H<1){if(N=!0,H>0)D.push({batch:q,fade:H})}else M.push(q)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let q of M)this.drawSubBatch(q.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let q of M)this.drawSubBatch(q.translucent);for(let{batch:q,fade:K}of D)t.uniform1f(this.uFade,K),this.drawSubBatch(q.opaque),this.drawSubBatch(q.translucent);return t.depthMask(!0),t.bindVertexArray(null),N}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var zi=64,qs=16777216;function Ks(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ji(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function yn(e){return e==="board"||e==="schematic"||e==="gerbers"}function zs(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function wn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let d=document.createElement("div");d.className="bp-v-layers",d.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,c.append(u,p,d,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,l,m,c,y);let f="",g="",E=0,C=!1,k=new Set,A=[],N=0,M=new Map,D=new Map,q={},K=[],H="",he="",me=!1,ie=!1,we=0,Se=!1,Te=0,ge="",Be=0,T=null,re=null,ee=null,Y=null,le=null,F=new gn,x=0,S=!1,I="",V="",X="",j="";document.addEventListener("click",(R)=>{if(!S)return;if(R.target instanceof Node&&y.contains(R.target))return;S=!1,ce()}),document.addEventListener("keydown",(R)=>{if(S&&R.key==="Escape")S=!1,ce()});function B(){if(x)window.clearInterval(x),x=0;F.playing=!1}function je(){let R=g==="3d"||g==="mech";if(l.hidden=!R,!R)return;if(l.childElementCount>0)return;for(let O of Oi){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent=O.label,U.setAttribute("data-testid",`solid-view-${O.id}`),U.addEventListener("click",()=>{ee?.setView(O.id)}),l.append(U)}let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent="Snap view",G.setAttribute("data-testid","solid-snap"),G.addEventListener("click",()=>{if(!ee)return;ee.snapPng().then((O)=>{if(!O)return;let U=URL.createObjectURL(O),z=document.createElement("a");z.href=U;let Q=(ue()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");z.download=`${Q}-snap.png`,z.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),l.append(G)}async function ke(){if(!f||g!=="board"&&g!=="schematic")return;ce();let R=F.compareRequest();if(!R){I="",V="",X="",j="",await $e(!1);return}let G=`${g}|${R.commit}|${R.bits}|${he}`;if(G===j&&k.size>0){fe(F.highlightEdits?`Comparing against ${F.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${F.activeRef()?.label||R.commit.slice(0,7)}`,!1);return}let O=++E;k.clear(),M.clear(),Ye(),C=!0,I="",V=R.commit,X="",j=G;try{let U=he||(g==="schematic"?q.sch:q.pcb)||"";if(!U){let ve=await t.hub.rpc("viewer.files",{thread:f});if(O!==E)return;q=ve||{},Z(),U=(g==="schematic"?q.sch:q.pcb)||""}if(!U)throw Error(`Unable to resolve ${g} file path for compare`);let z=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:R.commit,bits:R.bits,...he?{path:he}:{}});if(O!==E)return;let Q=typeof z?.root==="string"?z.root:"",te=g==="schematic"?"1":"0";I=Q?`${te}|${Q}|diff -`:`${te}|`,V=R.commit,X=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Q?U:`${Q.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,C=!1;let be=A;Ye();for(let ve of be)if(ve.kind==="bin")Ge(ve.buf);else Oe(ve.key,ve.none,ve.retryable);fe(F.highlightEdits?`Comparing against ${F.activeRef()?.label||R.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${F.activeRef()?.label||R.commit.slice(0,7)}`,!1)}catch(U){if(O!==E)return;C=!1,I="",V="",X="",j="",Ye(),fe(U instanceof Error?U.message:String(U),!0)}}function ce(){let R=g==="board"||g==="schematic";if(y.hidden=!R,!R)return;let G=document.createElement("div");G.className="bp-history-group";let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="<",O.title="Older snapshot",O.disabled=F.refs.length===0||F.index>=F.refs.length-1,O.setAttribute("data-testid","history-prev"),O.addEventListener("click",()=>{if(B(),F.step(1))ke()});let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(F.playing?" is-on":""),U.textContent=F.playing?"⏸":"▶",U.title=F.playing?"Pause history":"Play history",U.disabled=F.refs.length===0,U.setAttribute("data-testid","history-play"),U.addEventListener("click",()=>{if(F.playing){B(),ce();return}if(F.refs.length===0)return;if(F.playing=!0,F.isLive())F.index=F.refs.length-1,ke();else ce();x=window.setInterval(()=>{if(!F.playing||g!=="board"&&g!=="schematic"){B(),ce();return}if(F.step(-1))ke();else B(),ce()},1400)});let z=document.createElement("button");z.type="button",z.className="bp-v-btn",z.textContent=">",z.title="Newer snapshot",z.disabled=F.isLive(),z.setAttribute("data-testid","history-next"),z.addEventListener("click",()=>{if(B(),F.step(-1))ke()});let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn"+(F.isLive()?" is-on":""),Q.textContent="Live",Q.setAttribute("data-testid","history-live"),Q.addEventListener("click",()=>{if(B(),F.goLive())fe("",!1),ke()});let te=document.createElement("span");te.className="bp-history-label",te.setAttribute("data-testid","history-label");let be=F.activeRef();te.textContent=be?be.label||be.commit.slice(0,7):F.refs.length>0?`Live (${F.refs.length} saved)`:"Live",G.append(O,U,z,Q,te);let ve=document.createElement("div");ve.className="bp-history-group";let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(F.highlightEdits?" is-on":""),Ne.textContent="Highlight edits",Ne.disabled=F.refs.length===0,Ne.setAttribute("data-testid","history-highlight"),Ne.addEventListener("click",()=>{B(),F.toggleHighlight(),ke()});let Ee=document.createElement("div");Ee.className="bp-history-menu-wrap";let Ie=document.createElement("button");if(Ie.type="button",Ie.className="bp-v-btn"+(S||!F.isLive()?" is-on":""),Ie.disabled=F.refs.length===0,Ie.setAttribute("data-testid","history-compare"),Ie.setAttribute("aria-haspopup","menu"),Ie.setAttribute("aria-expanded",String(S)),Ie.textContent=be?`Compare: ${be.label||be.commit.slice(0,7)} ▾`:"Compare ▾",Ie.addEventListener("click",(Re)=>{Re.stopPropagation(),S=!S,ce()}),Ee.append(Ie),S&&F.refs.length>0){let Re=document.createElement("div");Re.className="bp-history-menu",Re.setAttribute("role","menu"),Re.setAttribute("data-testid","history-compare-menu");let _e=(De,Xe,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Xe),Ve.textContent=De,Ve.addEventListener("click",()=>{if(S=!1,B(),F.selectCommit(Xe)){if(F.isLive())fe("",!1);ke()}else ce()}),Re.append(Ve)};_e("Live (working tree)","",F.isLive());for(let De of F.refs)_e(De.label||De.commit.slice(0,7),De.commit,be?.commit===De.commit);Ee.append(Re)}ve.append(Ne,Ee),y.replaceChildren(G,ve)}async function Pe(R){if(!R)return;try{let G=await t.hub.rpc("viewer.refs",{thread:R});if(R!==f)return;F.setRefs(Array.isArray(G?.refs)?G.refs:[]),ce()}catch{if(R!==f)return;F.setRefs([]),ce()}}function ae(){return document.documentElement.classList.contains("light")}let Ae=new MutationObserver(()=>{let R=ae();re?.setTheme(R),ee?.setTheme(R),le?.setTheme(R)});Ae.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function de(R,G="",O=!1){if(R==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${R}`;let U=document.createElement("div");U.className="bp-v-state-card";let z=document.createElement("div");if(z.className="bp-v-state-msg",z.textContent=G,U.append(z),O){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn is-primary",Q.textContent=h("tools.retry","Retry"),Q.addEventListener("click",()=>void $e(!0)),U.append(Q)}p.replaceChildren(U)}function fe(R,G){m.textContent=R,m.hidden=!R,m.classList.toggle("is-warn",G)}function ue(){if(he)return xt(he);if(g==="board"||g==="3d")return xt(q.pcb);if(g==="schematic")return xt(q.sch);if(g==="mech")return xt(H);return""}function Z(){s.textContent=Ji(g);let R=ue();if(a.hidden=!R,r.hidden=!R,r.textContent=R,o.replaceChildren(),g==="mech"&&K.length>1){let O=document.createElement("select");O.className="bp-v-select",O.setAttribute("aria-label",h("viewer.mech","Mech"));for(let U of K){let z=document.createElement("option");z.value=U,z.textContent=xt(U),z.selected=U===H,O.append(z)}O.addEventListener("change",()=>{H=O.value,Z(),$e(!1)}),o.append(O)}if(yn(g)){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(Se?" is-on":""),O.textContent=T?.layerHead||"Layers",O.setAttribute("data-testid","viewer-layers-btn"),O.addEventListener("click",()=>{if(Se=!Se,d.hidden=!Se,O.classList.toggle("is-on",Se),Se)We("","")}),o.append(O)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="Fit",O.setAttribute("data-testid","viewer-fit-btn"),O.addEventListener("click",()=>{re?.fit(),ee?.fit()}),o.append(O)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(me&&!ie?" is-on":""),O.textContent=me?ie?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",O.setAttribute("data-testid","viewer-follow-btn"),O.addEventListener("click",()=>void nt()),o.append(O)}let G=document.createElement("button");G.type="button",G.className="bp-v-btn bp-v-close",G.textContent="✕",G.title=h("common.close","Close"),G.setAttribute("aria-label",h("common.close","Close")),G.setAttribute("data-testid","viewer-close-btn"),G.addEventListener("click",()=>t.closeViewer()),o.append(G)}function pe(){if(!T){d.replaceChildren();return}let R=document.createDocumentFragment(),G=document.createElement("div");G.className="bp-v-layers-head";let O=document.createElement("span");if(O.textContent=T.layerHead||"Layers",G.append(O),T.layerReset){let te=document.createElement("button");te.type="button",te.className="bp-v-btn",te.textContent="Reset",te.addEventListener("click",()=>void We("reset","")),G.append(te)}if(R.append(G),T.layerModes){let te=document.createElement("div");te.className="bp-v-layers-modes",["All","Dim","Only"].forEach((be,ve)=>{let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(T?.layerMode===ve?" is-on":""),Ne.textContent=be,Ne.addEventListener("click",()=>void We("mode",String(ve))),te.append(Ne)}),R.append(te)}let U=re?.presentColors()??new Map,z=(T.layerList||[]).concat(T.layerMarks||[]),Q=document.createElement("div");Q.className="bp-v-layers-list";for(let te of z){let be=U.get(te.layer);if(be===void 0)continue;let ve=document.createElement("div");ve.className="bp-v-layer-row"+(te.active?" is-focus":"");let Ne=document.createElement("input");Ne.type="checkbox",Ne.checked=te.on!==!1,Ne.addEventListener("change",()=>void We("toggle",String(te.layer)));let Ee=document.createElement("span");Ee.className="bp-v-layer-swatch";let Ie=be>>>16&255,Re=be>>>8&255,_e=be&255;Ee.style.background=te.on!==!1?`rgb(${Ie},${Re},${_e})`:`rgba(${Ie},${Re},${_e},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=te.name,De.addEventListener("click",()=>void We("pick",String(te.layer))),ve.append(Ne,Ee,De),Q.append(ve)}R.append(Q),d.replaceChildren(R)}async function We(R,G){if(!yn(g))return;let O=E;try{let U=await t.hub.rpc("viewer.layers",{kind:g,present:Be,off:Te,focus:ge,...R?{action:R,value:G}:{}});if(O!==E||!U)return;Te=Number(U.own)||0,ge=typeof U.focus==="string"?U.focus:"",T=U;let z={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(re?.setLayers(z),Z(),Se)pe()}catch{}}async function Ue(){if(!me||ie||!f||!t.hub.hasFeature("follow"))return;ie=!0,Z();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function nt(){if(!f||!t.hub.hasFeature("follow"))return;let R=!me?"on":ie?"resume":"off";try{let G=await t.hub.rpc("viewer.follow",{thread:f,action:R});if(me=!!G.on,ie=!!G.paused,Z(),G.on&&!G.paused&&G.focus&&Array.isArray(G.focus.box)&&G.focus.box.length===4&&(G.seq||0)>we)we=G.seq||we,re?.zoomToBoxMm([G.focus.box[0],G.focus.box[1],G.focus.box[2],G.focus.box[3]])}catch{}}function oe(){b.hidden=!0,b.replaceChildren(),re?.setHighlights([])}function lt(R){let G=R.split(";").filter(Boolean),O=G.shift()||R,U=[],z="",Q="";for(let Ee of G){if(Ee.startsWith("g="))continue;let Ie=Ee.indexOf("=");if(Ie>0){let Re=Ee.slice(0,Ie),_e=Ee.slice(Ie+1);if((Re==="ref"||Re==="symbol")&&!z)z=_e;if(Re==="net"&&!Q)Q=_e;U.push([Re,_e])}else U.push([Ee,""])}let te=document.createElement("div");te.className="bp-v-info-head";let be=document.createElement("span");be.className="bp-v-info-title",be.textContent=O;let ve=document.createElement("button");ve.type="button",ve.className="bp-v-info-x",ve.textContent="×",ve.setAttribute("aria-label","Clear selection"),ve.addEventListener("click",oe),te.append(be,ve);let Ne=document.createElement("div");Ne.className="bp-v-info-rows";for(let[Ee,Ie]of U){let Re=document.createElement("span");Re.className="bp-v-info-chip",Re.textContent=Ie?`${Ee}: ${Ie}`:Ee,Ne.append(Re)}return b.replaceChildren(te,...U.length>0?[Ne]:[]),b.hidden=!1,{ref:z||void 0,net:Q||void 0}}async function Je(R){if(!R){oe();return}let G=Array.from(k)[0]||"";if(!G)return;let O=E;try{let U=await t.hub.rpc("viewer.info",{key:G,at:R.at,idx:R.idx});if(O!==E)return;let z=typeof U.info==="string"?U.info:"";if(!z){oe();return}let{ref:Q,net:te}=lt(z),be=[];if(Q)be.push(["ref",Q]);if(te)be.push(["net",te]);let ve=[[R.at,R.idx]];for(let[Ne,Ee]of be){let Ie=await t.hub.rpc("viewer.probe",{key:G,name:Ne,value:Ee});if(O!==E)return;if(Array.isArray(Ie.matches))for(let Re of Ie.matches)ve.push(Re)}re?.setHighlights(ve)}catch{oe()}}function ct(){Y?.destroy(),Y=null,le?.destroy(),le=null,re?.destroy(),re=null,ee?.destroy(),ee=null,u.replaceChildren(),Se=!1,d.hidden=!0,b.hidden=!0,b.replaceChildren(),fe("",!1),de("none")}function Ye(){A=[],N=0}async function $e(R){if(!f||!g)return;let G=++E;if(k.clear(),C=!1,Ye(),ct(),Z(),je(),ce(),(g==="board"||g==="schematic")&&f)Pe(f);if(zs(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")Y=Fi(u,t,f,(z,Q)=>{if(g=z,he=Q,z==="mech")H=Q;$e(!1)});else if(g==="diff")Y=$i(u,t,f);else if(g==="review")Y=Gi(u,t,f);else if(g==="browser")Y=ji(u,t,f);else if(g==="terminal")de("loading","Loading terminal…"),import("/assets/terminal.js").then((Q)=>{if(G!==E)return;if(de("none"),Q?.mountTerminalPane)le=Q.mountTerminalPane(u,t,f,ae());else de("error","Terminal chunk missing",!0)},(Q)=>{if(G!==E)return;de("error",Q instanceof Error?Q.message:String(Q),!0)});return}if(de("loading","Loading…"),!q.root)try{let z=await t.hub.rpc("viewer.files",{thread:f});if(G!==E)return;q=z||{},Z()}catch{}if(g==="gerbers"&&q.hasGerbers===!1){de("empty","No Gerbers in this project",!1);return}let O=ae();if(g==="3d"||g==="mech")ee=new vn(u,{onStatus:(z,Q)=>{if(Q)de("none"),fe(z,!1);else if(z)de("loading",z);else de("none"),fe("",!1)},onUserMove:()=>void Ue()}),ee.setTheme(O);else if(g==="board"||g==="schematic"||g==="gerbers")re=new hn(u,{onPick:(z)=>void Je(z),onUserMove:()=>void Ue()}),re.setTheme(O);else{de("empty",`${Ji(g)} is not available in this viewer`,!1);return}let U={thread:f};if(R)U.force=!0;if(g==="mech"){if(K.length===0)try{let z=await t.hub.rpc("mech.list",{thread:f});if(G!==E)return;if(K=Array.isArray(z.parts)?z.parts:[],!H)H=z.primary||K[0]||"";Z()}catch(z){if(G!==E)return;de("error",z instanceof Error?z.message:String(z),!0);return}if(!H){de("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=H}else{if(U.kind=g,he&&(g==="board"||g==="schematic"))U.path=he;if(g==="3d"&&!R&&ee){let z=ee.keptToken();if(z)U.kept=z}if((g==="board"||g==="schematic"||g==="gerbers")&&!R&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(D.keys())}C=!0,I="",V="",X="",j="";try{let z=await t.hub.rpc("viewer.watch",U);if(G!==E)return;k=new Set(Array.isArray(z.keys)?z.keys:[]),C=!1;let Q=A;Ye();for(let te of Q)if(te.kind==="bin")Ge(te.buf);else Oe(te.key,te.none,te.retryable)}catch(z){if(G!==E)return;C=!1,k.clear(),Ye();let Q=z instanceof Error?z.message:String(z),te=/no gerbers|not in this project|another machine/i.test(Q);de(te?"empty":"error",Q,!te)}}function Oe(R,G,O){if(C){if(A.length{if(R.t==="plot"&&typeof R.none==="string"&&typeof R.key==="string")Oe(R.key,R.none,R.retryable===!0)}),Ft=At(()=>{if(g)Z()}),kt=(R)=>{if(R.key==="Escape"&&g&&!b.hidden)oe()};return window.addEventListener("keydown",kt),{open(R,G){if(G!==f){if(f=G,q={},K=[],H="",M.clear(),me=!1,ie=!1,we=0,Te=0,ge="",Be=0,T=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:G}).then((O)=>{if(G!==f)return;if(me=!!O.on,ie=!!O.paused,we=Number(O.seq)||0,g)Z()}).catch(()=>{})}if(R!==g)B(),F.goLive(),Te=0,ge="",Be=0,T=null;g=R,he="",$e(!1)},reconcileHas(R){if(g&&!Ks(g,R))t.closeViewer()},close(){if(E++,C=!1,B(),S=!1,I="",V="",X="",j="",F.goLive(),l.hidden=!0,y.hidden=!0,Ye(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",k.clear(),ct()}}}var Yi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(Yi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Yi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Js(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Xi(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Zi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function Ys(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Qi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,m,c);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let p=document.createElement("span");p.className="bp-top-state-lbl",p.textContent="STATE";let d=document.createElement("span");d.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(p,d,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=h("menu.settle","Settle"),E.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);let k=document.createElement("div");k.className="bp-menu-wrap";let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost bp-top-act",A.textContent="▾",A.title="Thread menu",A.setAttribute("aria-label","Thread menu"),A.setAttribute("data-testid","thread-menu-btn");let N=document.createElement("div");N.className="bp-popover bp-hidden",N.setAttribute("data-testid","thread-menu"),k.append(A,N),y.append(f,E,k);let M=document.createElement("div");M.className="bp-top-right";let D=document.createElement("button");D.type="button",D.className="bp-btn-ghost bp-top-act bp-hide-tablet",D.setAttribute("data-testid","improvements-btn");let q=document.createElement("span");q.textContent=h("gpui.improvements","Improvements"),D.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),q);let K=document.createElement("button");K.type="button",K.className="bp-cmd-box bp-hide-tablet",K.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let he=document.createElement("button");he.type="button",he.className="icon bp-top-icon",he.title=h("palette.settings","Settings"),he.setAttribute("aria-label",h("palette.settings","Settings")),he.setAttribute("data-testid","settings-btn"),he.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(D,K,H,he),t.append(n,i,u,y,M);let me=document.createElement("div");me.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Se=document.createElement("div");Se.className="bp-right-area bp-hidden",Se.setAttribute("data-testid","right-area");let Te=document.createElement("div");Te.className="bp-right-top";let ge=document.createElement("section");ge.className="bp-viewer-pane bp-hidden",ge.setAttribute("data-testid","viewer-pane"),Te.appendChild(ge),Se.appendChild(Te);let Be=document.createElement("nav");Be.className="bp-rail",Be.setAttribute("aria-label","Viewer rail"),Be.setAttribute("data-testid","viewer-rail"),me.append(ie,we,Se,Be),e.append(t,me);let T=new mn,re=null,ee=new Set,Y=0,le=null,F=[],x=[],S=[],I=[],V=[],X=[],j="",B=0,je=0,ke=null,ce=null,Pe="",ae=null,Ae=20,de={},fe=new Map;function ue(v,w){fe.delete(v),fe.set(v,w);while(fe.size>Ae){let L=fe.keys().next().value;if(L!==void 0)fe.delete(L);else break}}let Z=new cn(ie,{onSelectThread:(v)=>{if(v===j&&ke!==null){ie.classList.remove("bp-sidebar-open");return}Ee(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{Ee(v.thread)},onThreadAct:(v,w)=>{Qe(v,w)},onToggleSection:(v)=>{if(ee.has(v))ee.delete(v);else ee.add(v);be()},onToggleProjectFold:(v)=>{T.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>be()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let w=jt(v,!1);if(!w)return;if(w.kind==="thread"){Ee(w.id);return}if(w.kind!=="call")return;let L=yi(await T.rpc(w.method,w.params));if(L?.kind==="thread")Ee(L.id);be()},hasRoomView:!1,onAddProject:()=>Oe.open({mode:"folder"})}),pe=new Kt(we,{onLoadOlder:()=>{_e()},onGoToEntry:(v)=>{Re(v)},onAnswerAsk:(v,w)=>{T.rpc("ask.answer",{ask:v,answer:w}).catch((L)=>{oe.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!j)return;let w=B;T.rpc("thread.review",{thread:j,on:v}).then((L)=>{if(w===B)pe.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,w)=>{if(!j)return;if(v==="again"||v==="thread-again")T.rpc("thread.again",{thread:j,value:w}).catch(()=>{});else T.rpc("thread.act",{thread:j,action:v,value:w}).catch(()=>{})},onReplyEntry:(v)=>{if(!T.hasFeature("reply")){let w=(v.text||"").split(` -`)[0]?.slice(0,100)??"";if(w)oe.prependDraft(`> ${w} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,w)=>{try{let L={entry:v,path:w};if(T.hasFeature("blobs"))L.metaOnly=!0;let P=await T.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function We(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,w){if(!j)return;let L=B,P=j;T.rpc(v,w).then((_)=>{if(L!==B||j!==P)return;if(_.thread){let ne=x.findIndex((ye)=>ye.id===_.thread.id);if(ne>=0)x[ne]=_.thread;else x.unshift(_.thread);Z.setData(F,x,S,I),pe.updateThreadMeta(_.thread),R(),oe.setState(!0,_.thread.state==="working")}}).catch((_)=>{if(L===B&&j===P)oe.showError(_ instanceof Error?_.message:"Could not change Plan mode")})}let nt,oe=new Jt(we,{onSend:(v,w)=>{En(v,w)},onRunCommand:(v)=>{xn(v)},onInterrupt:()=>{if(j)T.rpc("turn.interrupt",{thread:j}).catch(()=>{})},onQueryMentions:async(v,w)=>{try{return(await T.rpc("mentions.list",{q:v,kind:w,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=x.find((L)=>L.id===j)??null,w=We(v);if(!w||!j)return;if(w.interaction!=="plan")Ue("thread.planonce",{thread:j,on:!0});else if(w.once)Ue("thread.pick",{thread:j,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:j,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!j)return;if(v==="once")Ue("thread.planonce",{thread:j,on:!0});else if(v==="always")Ue("thread.pick",{thread:j,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:j,action:"interaction",value:"default"})}});nt=new dn(T,{getThreadId:()=>j,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function lt(){let v=Pe!=="",w=Je.isOpen();Se.classList.toggle("bp-hidden",!v&&!w),Se.classList.toggle("bp-has-viewer",v),Se.classList.toggle("bp-has-mgmt",w)}let Je=new nn(Te,Se,{hub:T,getThreadId:()=>j,getThreadGen:()=>B,onSendText:(v)=>{En(v)},onOpenChange:()=>lt()});function ct(v){let w=window.prompt("Rename thread",v.title||"");if(!w||!w.trim())return;T.rpc("thread.act",{thread:v.id,action:"rename",title:w.trim()}).then((L)=>{if(L.thread)x=x.map((P)=>P.id===L.thread.id?L.thread:P),R(),be()}).catch((L)=>{oe.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ee(v.id);break;case"rail":if(!j&&v.id!=="terminal")break;if(Pe===v.id)G();else O(v.id);break;case"thread-act":if(j)Qe(j,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let w=x.find((L)=>L.id===j);if(w)ct(w);break}case"prev-thread":case"next-thread":{let w=x.filter((ne)=>!ne.archived&&!ne.swarm);if(w.length<2)break;let L=w.findIndex((ne)=>ne.id===j),P=v.type==="next-thread"?1:-1,_=w[(L<0?0:L+P+w.length)%w.length];if(_)Ee(_.id);break}case"command":if(v.runDirectly)xn(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":kt();break;case"settings":Ke.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let $e=new sn(e,{getState:()=>({selectedThreadId:j,threads:x,projects:F,bots:S,railItems:V,commands:X}),onSearch:async(v)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:v,limit:20})},onExecute:Ye}),Oe=new Wt(e,{hub:T,onProjectAdded:(v)=>{if(be(),v.id)De(v.id)},onCloneDone:(v)=>{if(be(),v.thread)Ee(v.thread)}}),Ge=new an(Be,(v)=>{if(v==="commands"){$e.open();return}if(!j)return;if(Pe===v)G();else O(v)}),it=null,Ke=new rn(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,w)=>{await T.rpc("devices.page.act",{action:v,value:w})},onGetHome:()=>it,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>Dn(()=>{T.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=x.find((w)=>w.id===j);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let v=x.find((w)=>w.id===j);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let Ft=new ln(e,(v,w)=>w?T.rpc("thread.context.mcp",{thread:v,...w}):T.rpc("thread.context",{thread:v}));A.addEventListener("click",(v)=>{v.stopPropagation();let w=x.find((_)=>_.id===j);if(!w)return;if(!N.classList.contains("bp-hidden")){N.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ct(w)},{label:w.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{Qe(w.id,w.pinned?"unpin":"pin")}},{label:w.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{Qe(w.id,w.settled?"unsettle":"settle")}},{label:w.archived?"Unarchive":"Archive",run:()=>{Qe(w.id,w.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(w.id,"delete")}}];if(T.hasFeature("threadContext"))L.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Ft.open(w.id)});let P=document.createDocumentFragment();for(let _ of L){let ne=document.createElement("button");ne.type="button",ne.className="bp-popover-item"+(_.danger?" danger":""),ne.textContent=_.label,ne.addEventListener("click",()=>{N.classList.add("bp-hidden"),_.run()}),P.appendChild(ne)}N.replaceChildren(P),N.classList.remove("bp-hidden")}),document.addEventListener("click",()=>N.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let w=document.createElement("div");w.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let _=document.createElement("button");_.type="button",_.className="icon",_.textContent="×",_.addEventListener("click",()=>v.remove()),L.append(P,_);let ne=document.createElement("div");ne.className="bp-modal-body",ne.textContent="Loading…",w.append(L,ne),v.appendChild(w),v.addEventListener("click",(ye)=>{if(ye.target===v)v.remove()}),e.appendChild(v);try{let ye=await T.rpc("improvements.projects",{}),He=ye.projects??[];if(He.length===0){ne.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Le of He){let se=document.createElement("div");se.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Le.title||Le.name||Le.id;let tt=document.createElement("button");tt.type="button",tt.className=Le.id===ye.project?"primary":"",tt.textContent=Le.id===ye.project?"Active":"Select",tt.addEventListener("click",()=>{T.rpc("improvements.project",{project:Le.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Ze,tt),et.appendChild(se)}ne.replaceChildren(et)}catch(ye){ne.textContent=ye instanceof Error?ye.message:"Could not load Improvements."}}D.addEventListener("click",()=>{kt()}),K.addEventListener("click",()=>$e.open()),H.addEventListener("click",()=>$e.open()),he.addEventListener("click",()=>{Ke.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function R(){let v=x.find((P)=>P.id===j)??null,w=v?F.find((P)=>P.id===v.project):void 0;o.textContent=w?.title??"",r.classList.toggle("bp-hidden",!w),l.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let L=We(v);if(oe.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?h("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?h("gpui.planmode.top.planning","Planning"):L.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){d.className=`bp-dot ${Js(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),C.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;oe.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function G(v=!0){if(je++,Pe="",Ge.setActive(""),ge.classList.add("bp-hidden"),ae?.close(),lt(),v&&j&&T.getState()==="connected")T.rpc("viewer.watch",{thread:j,kind:""}).catch(()=>{})}function O(v){if(je++,Pe=v,Ge.setActive(v),ge.classList.remove("bp-hidden"),lt(),!ae&&typeof wn==="function")ae=wn(ge,{hub:T,getThreadId:()=>j,closeViewer:()=>G(!0)});if(ae)ae.open(v,j);else{let w=document.createElement("div");w.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let _=document.createElement("button");_.type="button",_.className="icon",_.textContent="×",_.addEventListener("click",()=>G(!0)),L.append(P,_);let ne=document.createElement("div");ne.className="bp-dim bp-viewer-msg",ne.textContent=`Viewer pane (${v}).`,w.append(L,ne),ge.replaceChildren(w)}}async function U(v,w){if(!v||!T.hasFeature("rail")){if(w===B)V=[],Ge.setItems([]);return}let L=++je;try{let P=await T.rpc("viewer.rail",{thread:v,page:Pe});if(w!==B||L!==je)return;let _=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(V=_,Ge.setItems(_),P.has){if(ae?.reconcileHas?.(P.has),Pe&&!Xi(P.has,Pe))G(!0)}}catch{if(w===B&&L===je)V=[],Ge.setItems([])}}function z(v){for(let w of v)if(w.kind==="threads"){for(let L of w.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(w.kind==="projects"){for(let L of w.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function Q(v,w){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===w))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((_)=>(_.nav||_.id)===w))return!0}return!1}function te(v){let w=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)w.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(w.length>0)F=w}async function be(){if(!T.hasFeature("sections"))return!1;let v=++Y;try{let w=await T.rpc("sidebar.sections",{open:Array.from(ee)});if(v!==Y)return!0;let L=Array.isArray(w.sections)?w.sections:[];return re=L,te(L),Z.setData(F,x,S,I),Z.setSections(L,S,I),R(),!0}catch{return!1}}function ve(){if(!T.hasFeature("sections"))return;if(le!==null)window.clearTimeout(le);le=window.setTimeout(()=>{le=null,be()},150)}async function Ne(){if(ke=null,T.hasFeature("bots"))try{let w=await T.rpc("bots.list",{});S=w.bots??[],I=w.rooms??[]}catch{}if(T.hasFeature("shell")){let w=await T.rpc("shell.sync",{have:de,settled:25}),L=new Set(w.removed??[]),P=new Set((w.projects??[]).map((_)=>_.id));if(L.size>0||P.size>0)F=[...F.filter((_)=>!L.has(_.id)&&!P.has(_.id)),...w.projects??[]],x=[...x.filter((_)=>!L.has(_.project)&&!P.has(_.project)),...w.threads??[]];else if(Array.isArray(w.threads)&&w.threads.length>0){let _=new Map(x.map((ne)=>[ne.id,ne]));for(let ne of w.threads)_.set(ne.id,ne);x=Array.from(_.values())}if(w.sections!==void 0){let _=Array.isArray(w.sections)?w.sections:Array.isArray(w.sections?.sections)?w.sections.sections:null;if(_)re=_,te(_)}if(w.h)de=w.h;Z.setData(F,x,S,I),Z.setSections(re,S,I)}else if(T.hasFeature("sections")){let[w,L]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(ee)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(x=L.threads??[],w&&Array.isArray(w.sections)){let P=w.sections;if(!P.some((ne)=>ne.kind==="projects"&&ne.rows.length>0)){let ne=P.find((ye)=>ye.kind==="projects"&&ye.fold&&ye.toggle&&(ye.count??0)>0);if(ne?.toggle&&!ee.has(ne.toggle)){ee.add(ne.toggle);let ye=await T.rpc("sidebar.sections",{open:Array.from(ee)}).catch(()=>null);if(ye&&Array.isArray(ye.sections))P=ye.sections}}re=P,te(P),Z.setData(F,x,S,I),Z.setSections(P,S,I)}else re=null,F=(await T.rpc("projects.list",{limit:100})).projects??[],Z.setSections(null,S,I),Z.setData(F,x,S,I);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{re=null;let[w,L]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);F=w.projects??[],x=L.threads??[],Z.setSections(null,S,I),Z.setData(F,x,S,I),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=j;if(!v){let w="";try{w=localStorage.getItem("bp.lastThread")||""}catch{}if(w&&(re&&Q(re,w)||x.some((L)=>L.id===w)))v=w;else if(re)v=z(re);if(!v)v=(x.find((P)=>!P.archived&&!P.swarm&&!P.settled)??x.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(re&&Q(re,v)||x.some((w)=>w.id===v)))await Ee(v);else j="",V=[],Ge.setItems([]),oe.setState(!1,!1),R()}async function Ee(v){if(j&&j!==v){nt.cancel();let Le=pe.getEntries();if(Le.length>0){let se=fe.get(j);ue(j,{entries:Le,ids:se?.ids??Le.map((Ze)=>Ze.id),olderCursor:ce,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??V,hashes:se?.hashes??{}})}}let w=++B;je++,Ve(null);let L=ke;if(ke=null,L!==null)T.rpc("unsubscribe",{sub:L}).catch(()=>{});j=v;let P=fe.get(v);ce=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}Z.setSelected(v),ie.classList.remove("bp-sidebar-open"),R();let _=x.find((Le)=>Le.id===v)??null;if(P)pe.setThread(_,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),V=P.rail,Ge.setItems(P.rail);else pe.setLoading(_),V=[],Ge.setItems([]);if(oe.setState(!0,_?.state==="working"),T.hasFeature("open")){let Le={};if(P){for(let[Me,pt]of Object.entries(P.hashes))Le[Me]=pt;for(let Me of P.entries)if(Me.h)Le[Me.id]=Me.h}let se;try{se=await T.rpc("thread.open",{thread:v,limit:40,have:Le})}catch(Me){if(w===B){let pt=Me instanceof Error&&Me.message?Me.message:"Could not load messages.";pe.setError(_,pt,()=>{Ee(v)})}return}if(w!==B){if(se.sub!==void 0&&se.sub!==null)T.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(ke=se.sub??null,se.thread){_=se.thread;let Me=x.findIndex((pt)=>pt.id===se.thread.id);if(Me>=0)x[Me]=se.thread;else x.unshift(se.thread);R(),oe.setState(!0,_.state==="working")}if("next"in se)ce=se.next??null;let Ze=new Map;if(P)for(let Me of P.entries)Ze.set(Me.id,Me);for(let Me of se.entries??[])Ze.set(Me.id,Me);let tt=se.ids??P?.ids??(se.entries??[]).map((Me)=>Me.id),kn=tt.map((Me)=>Ze.get(Me)).filter((Me)=>Boolean(Me)),dt=P?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))dt=se.rail;else if(dt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(ae?.reconcileHas?.(se.rail.has),Pe&&!Xi(se.rail.has,Pe))G(!0)}}V=dt,Ge.setItems(dt);let $t=P?.review??null;if(T.hasFeature("reviewmode"))try{let Me=await T.rpc("thread.review",{thread:v});if(w!==B)return;$t=Me.review??null}catch{}if(w!==B)return;let Sn="unanswered"in se?se.unanswered??null:P?.unanswered??null,es=se.h??P?.hashes??{};if(ue(v,{entries:kn,ids:tt,olderCursor:ce,review:$t,unanswered:Sn,rail:dt,hashes:es}),pe.setThread(_,kn,Boolean(ce),$t,Sn),Ie(v,w),Pe)O(Pe);return}let ne;try{ne=await T.rpc("thread.entries",{thread:v,limit:40})}catch(Le){if(w===B){let se=Le instanceof Error&&Le.message?Le.message:"Could not load messages.";pe.setError(_,se,()=>{Ee(v)})}return}if(w!==B)return;if(ne.thread){let Le=x.findIndex((se)=>se.id===ne.thread.id);if(Le>=0)x[Le]=ne.thread;else x.unshift(ne.thread);R()}ce=ne.next??null;let ye=null;if(T.hasFeature("reviewmode"))try{let Le=await T.rpc("thread.review",{thread:v});if(w!==B)return;ye=Le.review??null}catch{}if(w!==B)return;let He=ne.entries??[],et=ne.unanswered??null;ue(v,{entries:He,ids:He.map((Le)=>Le.id),olderCursor:ce,review:ye,unanswered:et,rail:P?.rail??[],hashes:P?.hashes??{}}),pe.setThread(_,He,Boolean(ce),ye,et);try{let se=(await T.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(w!==B){T.rpc("unsubscribe",{sub:se}).catch(()=>{});return}ke=se}}catch{}if(w!==B)return;if(U(v,w),Ie(v,w),Pe)O(Pe)}async function Ie(v,w){if(!v||!T.hasFeature("mgmt")){if(w===B)Je.clear();return}let L=x.find((_)=>_.id===v),P=L?.project?F.find((_)=>_.id===L.project)?.root??"":"";if(!P&&T.hasFeature("viewers"))try{let _=await T.rpc("viewer.files",{thread:v});if(w!==B)return;P=_.pcb||_.sch||_.root||""}catch{}if(w!==B)return;if(P)await Je.watchProject(P);else Je.clear()}async function Re(v){let w=B;for(let L=0;L<25&&w===B;L++){if(pe.goTo(v))return;if(!ce)return;let P=ce;if(await _e(),ce===P)return}}async function _e(){if(!j||!ce){pe.clearLoadingOlder();return}let v=B,w=j,L=ce;try{let P=await T.rpc("thread.entries",{thread:w,limit:40,before:L});if(v!==B||j!==w)return;ce=P.next??null,pe.prependEntries(P.entries??[],Boolean(ce))}catch{if(v===B)pe.clearLoadingOlder()}}async function De(v){try{let w=await T.rpc("thread.create",{project:v});if(w.thread)x=[w.thread,...x.filter((L)=>L.id!==w.thread.id)],Z.setData(F,x,S,I),be(),await Ee(w.thread.id),oe.focus()}catch(w){oe.showError(w instanceof Error?w.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` -`).map((w)=>w.trim()).find((w)=>w.length>0)??"").slice(0,200)}function Ve(v){Xe=v,oe.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Re(Xe.id)},()=>Ve(null))}async function En(v,w=[]){if(!j)return;let L=B,P=j,_=Ys(),ne=`local-${_}`,ye=Xe&&v.trim()&&T.hasFeature("reply")?Xe:null;if(ye)Ve(null);pe.upsertEntry({id:ne,kind:"user",text:v,at:Date.now(),clientId:_,...ye?{replyTo:{id:ye.id,quote:St(ye.text)}}:{},attachments:w.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:P,text:v,clientId:_};if(w.length>0)He.attachments=w;if(ye)He.replyTo={id:ye.id,text:ye.text};let et=await T.rpc("message.send",He);if(L!==B||j!==P)return;if(et.entry)pe.upsertEntry(et.entry)}catch(He){if(L===B&&j===P){if(pe.removeEntry(ne),oe.setDraft(v),ye&&!Xe)Ve(ye);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function xn(v){if(!j)return;let w=B,L=j;try{let P=await T.rpc("composer.run",{thread:L,text:v});if(w!==B||j!==L)return;if(P.error)oe.setDraft(v),oe.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")oe.setDraft(P.text);else if(P.kind==="project")Oe.open({mode:"folder"});else if(P.kind==="clone")Oe.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(w===B&&j===L)oe.setDraft(v),oe.showError(P instanceof Error?P.message:"Command refused")}}async function Qe(v,w){try{let L=await T.rpc("thread.act",{thread:v,action:w});if(L.thread){if(x=x.map((P)=>P.id===L.thread.id?L.thread:P),Z.setData(F,x,S,I),L.thread.id===j)pe.updateThreadMeta(L.thread),R()}be()}catch(L){oe.showError(L instanceof Error?L.message:`Action "${w}" not allowed`)}}function Cn(v,w){if(!v||!v.text||w-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return h("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function Lt(v){if(v==="connected")Z.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Cn(T.restarting,Date.now()))Z.setConnStatus(Cn(T.restarting,Date.now()),"");else if(v==="reconnecting")Z.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")Z.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Z.setConnStatus("Connecting…","")}At(()=>{Lt(T.getState()),q.textContent=h("gpui.improvements","Improvements"),he.title=h("palette.settings","Settings"),he.setAttribute("aria-label",h("palette.settings","Settings")),R(),Z.refreshLocale(),pe.refreshLocale(),oe.refreshLocale(),Ge.render(),Ke.refreshLocale(),Oe.refreshLocale()}),T.onState((v,w)=>{if(v==="connected"&&w){if(w.locale)Tn(w.locale);if(w.theme)Zi(w.theme);if(w.name)Z.setHostName(w.name);if(it=w.home??null,Z.setHome(it),Ke.isOpen())Ke.refresh();Lt(v);let L=typeof w.hubBack==="string"?String(w.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")Z.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Lt(T.getState()),6000)}catch{}if(oe.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(w.commands))X=w.commands,oe.setCommands(X);else X=[];Ne(),Oe.reconcile()}else nt.cancel(),Lt(v)}),T.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let w=v;if(w.k==="clone"||w.k==="clone.repos"||w.k==="clone.signin"){Oe.handleFrame(w);return}switch(w.k){case"project":{let L=w.project;if(!L)break;let P=F.findIndex((_)=>_.id===L.id);if(P>=0)F[P]=L;else F.unshift(L);Z.setData(F,x,S,I),R(),ve();break}case"thread":{let L=w.thread;if(!L)break;let P=x.findIndex((_)=>_.id===L.id);if(P>=0)x[P]=L;else x.unshift(L);if(Z.setData(F,x,S,I),L.id===j)pe.updateThreadMeta(L),R(),oe.setState(!0,L.state==="working");ve();break}case"thread.removed":{let L=String(w.id??"");x=x.filter((P)=>P.id!==L),Z.setData(F,x,S,I),ve();break}case"entry":{if(w.thread===j&&w.entry)pe.upsertEntry(w.entry);break}case"text":{if(w.thread===j)pe.appendLiveText(String(w.entry??""),String(w.append??""),Number(w.at??Date.now()));break}case"turn":{if(w.thread===j){let L=String(w.state??"idle");oe.setState(!0,L==="working"),U(j,B)}ve();break}case"btw":{if(w.thread===j)pe.showBtw(String(w.q??""),String(w.a??""));break}case"unanswered":{if(w.thread===j)pe.setUnanswered(w.unanswered??null);break}case"theme":{if(typeof w.theme==="string")Zi(w.theme);break}case"home":{if(it=w.home??null,Z.setHome(it),Ke.isOpen())Ke.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let w=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(w==="k"||v.shiftKey&&w==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Oe.isOpen())Oe.escape();else if(Ke.isOpen())Ke.close();else if(pe.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Qi);else Qi(); +`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Os=[qe(77),qe(83),qe(94)],Us=[qe(53),qe(58),qe(67)],Vs=[qe(245),qe(246),qe(248)],Ws=[qe(225),qe(228),qe(233)];function _i(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function qi(e,t,n){let i=_i(e,e.VERTEX_SHADER,t),s=_i(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function _s(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function qs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Ki(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function zi(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function fn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class vn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=qi(n,Ds,Fs),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=qi(n,$s,Gs),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Ti(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,h=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,d=0,b=0;for(let g=0;g>>24&255,k=1-x/255,A=(E>>>16&255)/255,N=(E>>>8&255)/255,M=(E&255)/255,D=g*9;if(x===0&&o&&l&&m){let W=d*9;for(let H=0;H<9;H++)o[W+H]=e[D+H],l[W+H]=t[D+H];let _=d*12;for(let H=0;H<3;H++)m[_+H*4]=A,m[_+H*4+1]=N,m[_+H*4+2]=M,m[_+H*4+3]=1;d++}else if(c&&h&&p){let W=b*9;for(let H=0;H<9;H++)c[W+H]=e[D+H],h[W+H]=t[D+H];let _=b*12;for(let H=0;H<3;H++)p[_+H*4]=A,p[_+H*4+1]=N,p[_+H*4+2]=M,p[_+H*4+3]=k;b++}}let y=o&&l&&m?this.createSubBatch(o,l,m,a*3):null,f=c&&h&&p?this.createSubBatch(c,h,p,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Wi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Vs:Os,_=this.lightTheme?Ws:Us;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),m=Math.sin(this.pitch),c=Math.cos(this.yaw),h=Math.sin(this.yaw),p=[this.target[0]+this.dist*l*h,this.target[1]-this.dist*l*c,this.target[2]+this.dist*m],d=Ki([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),b=Math.abs(d[2])>0.99?[0,1,0]:[0,0,1],y=Ki(zi(d,b)),f=zi(y,d),g=new Float32Array([y[0],f[0],-d[0],0,y[1],f[1],-d[1],0,y[2],f[2],-d[2],0,-fn(y,p),-fn(f,p),fn(d,p),1]),E=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),k=qs(35*Math.PI/180,r/o,E,x),A=_s(k,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,A),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,d[0],d[1],d[2]);let N=!1,M=[],D=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,H=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(H<1){if(N=!0,H>0)D.push({batch:W,fade:H})}else M.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of M)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of M)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of D)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),N}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var Ji=64,Ks=16777216;function zs(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Yi(e){switch(e){case"board":return u("viewer.board","Board");case"schematic":return u("viewer.schematic","Schematic");case"3d":return u("viewer.solid","3D");case"gerbers":return u("gpui.gerbers","Gerbers");case"mech":return u("viewer.mech","Mech");case"files":return u("viewer.files","Files");case"diff":return u("viewer.diff","Diff");case"review":return u("viewer.review","Review");case"browser":return u("bots.tab.browser","Browser");case"terminal":return u("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function yn(e){return e==="board"||e==="schematic"||e==="gerbers"}function Js(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function wn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let d=document.createElement("div");d.className="bp-v-layers",d.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,c.append(h,p,d,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,l,m,c,y);let f="",g="",E=0,x=!1,k=new Set,A=[],N=0,M=new Map,D=new Map,W={},_=[],H="",ue="",me=!1,se=!1,ye=0,Le=!1,Ae=0,we="",Be=0,B=null,pe=null,ne=null,Z=null,le=null,j=new gn,Y=0,C=!1,S="",R="",q="",T="";document.addEventListener("click",(I)=>{if(!C)return;if(I.target instanceof Node&&y.contains(I.target))return;C=!1,re()}),document.addEventListener("keydown",(I)=>{if(C&&I.key==="Escape")C=!1,re()});function z(){if(Y)window.clearInterval(Y),Y=0;j.playing=!1}function J(){let I=g==="3d"||g==="mech";if(l.hidden=!I,!I)return;if(l.childElementCount>0)return;for(let O of Vi){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=O.label,G.setAttribute("data-testid",`solid-view-${O.id}`),G.addEventListener("click",()=>{ne?.setView(O.id)}),l.append(G)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent="Snap view",F.setAttribute("data-testid","solid-snap"),F.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((O)=>{if(!O)return;let G=URL.createObjectURL(O),K=document.createElement("a");K.href=G;let ee=(Re()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");K.download=`${ee}-snap.png`,K.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),l.append(F)}async function Me(){if(!f||g!=="board"&&g!=="schematic")return;re();let I=j.compareRequest();if(!I){S="",R="",q="",T="",await Ge(!1);return}let F=`${g}|${I.commit}|${I.bits}|${ue}`;if(F===T&&k.size>0){he(j.highlightEdits?`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)}`,!1);return}let O=++E;k.clear(),M.clear(),Xe(),x=!0,S="",R=I.commit,q="",T=F;try{let G=ue||(g==="schematic"?W.sch:W.pcb)||"";if(!G){let fe=await t.hub.rpc("viewer.files",{thread:f});if(O!==E)return;W=fe||{},X(),G=(g==="schematic"?W.sch:W.pcb)||""}if(!G)throw Error(`Unable to resolve ${g} file path for compare`);let K=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:I.commit,bits:I.bits,...ue?{path:ue}:{}});if(O!==E)return;let ee=typeof K?.root==="string"?K.root:"",te=g==="schematic"?"1":"0";S=ee?`${te}|${ee}|diff +`:`${te}|`,R=I.commit,q=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!ee?G:`${ee.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,x=!1;let ge=A;Xe();for(let fe of ge)if(fe.kind==="bin")Oe(fe.buf);else Ue(fe.key,fe.none,fe.retryable);he(j.highlightEdits?`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${j.activeRef()?.label||I.commit.slice(0,7)}`,!1)}catch(G){if(O!==E)return;x=!1,S="",R="",q="",T="",Xe(),he(G instanceof Error?G.message:String(G),!0)}}function re(){let I=g==="board"||g==="schematic";if(y.hidden=!I,!I)return;let F=document.createElement("div");F.className="bp-history-group";let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="<",O.title="Older snapshot",O.disabled=j.refs.length===0||j.index>=j.refs.length-1,O.setAttribute("data-testid","history-prev"),O.addEventListener("click",()=>{if(z(),j.step(1))Me()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(j.playing?" is-on":""),G.textContent=j.playing?"⏸":"▶",G.title=j.playing?"Pause history":"Play history",G.disabled=j.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(j.playing){z(),re();return}if(j.refs.length===0)return;if(j.playing=!0,j.isLive())j.index=j.refs.length-1,Me();else re();Y=window.setInterval(()=>{if(!j.playing||g!=="board"&&g!=="schematic"){z(),re();return}if(j.step(-1))Me();else z(),re()},1400)});let K=document.createElement("button");K.type="button",K.className="bp-v-btn",K.textContent=">",K.title="Newer snapshot",K.disabled=j.isLive(),K.setAttribute("data-testid","history-next"),K.addEventListener("click",()=>{if(z(),j.step(-1))Me()});let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn"+(j.isLive()?" is-on":""),ee.textContent="Live",ee.setAttribute("data-testid","history-live"),ee.addEventListener("click",()=>{if(z(),j.goLive())he("",!1),Me()});let te=document.createElement("span");te.className="bp-history-label",te.setAttribute("data-testid","history-label");let ge=j.activeRef();te.textContent=ge?ge.label||ge.commit.slice(0,7):j.refs.length>0?`Live (${j.refs.length} saved)`:"Live",F.append(O,G,K,ee,te);let fe=document.createElement("div");fe.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(j.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=j.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{z(),j.toggleHighlight(),Me()});let Ee=document.createElement("div");Ee.className="bp-history-menu-wrap";let Te=document.createElement("button");if(Te.type="button",Te.className="bp-v-btn"+(C||!j.isLive()?" is-on":""),Te.disabled=j.refs.length===0,Te.setAttribute("data-testid","history-compare"),Te.setAttribute("aria-haspopup","menu"),Te.setAttribute("aria-expanded",String(C)),Te.textContent=ge?`Compare: ${ge.label||ge.commit.slice(0,7)} ▾`:"Compare ▾",Te.addEventListener("click",(Ie)=>{Ie.stopPropagation(),C=!C,re()}),Ee.append(Te),C&&j.refs.length>0){let Ie=document.createElement("div");Ie.className="bp-history-menu",Ie.setAttribute("role","menu"),Ie.setAttribute("data-testid","history-compare-menu");let _e=(Fe,Ze,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Ze),Ve.textContent=Fe,Ve.addEventListener("click",()=>{if(C=!1,z(),j.selectCommit(Ze)){if(j.isLive())he("",!1);Me()}else re()}),Ie.append(Ve)};_e("Live (working tree)","",j.isLive());for(let Fe of j.refs)_e(Fe.label||Fe.commit.slice(0,7),Fe.commit,ge?.commit===Fe.commit);Ee.append(Ie)}fe.append(Pe,Ee),y.replaceChildren(F,fe)}async function ke(I){if(!I)return;try{let F=await t.hub.rpc("viewer.refs",{thread:I});if(I!==f)return;j.setRefs(Array.isArray(F?.refs)?F.refs:[]),re()}catch{if(I!==f)return;j.setRefs([]),re()}}function He(){return document.documentElement.classList.contains("light")}let be=new MutationObserver(()=>{let I=He();pe?.setTheme(I),ne?.setTheme(I),le?.setTheme(I)});be.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function de(I,F="",O=!1){if(I==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${I}`;let G=document.createElement("div");G.className="bp-v-state-card";let K=document.createElement("div");if(K.className="bp-v-state-msg",K.textContent=F,G.append(K),O){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn is-primary",ee.textContent=u("tools.retry","Retry"),ee.addEventListener("click",()=>void Ge(!0)),G.append(ee)}p.replaceChildren(G)}function he(I,F){m.textContent=I,m.hidden=!I,m.classList.toggle("is-warn",F)}function Re(){if(ue)return xt(ue);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(H);return""}function X(){s.textContent=Yi(g);let I=Re();if(a.hidden=!I,r.hidden=!I,r.textContent=I,o.replaceChildren(),g==="mech"&&_.length>1){let O=document.createElement("select");O.className="bp-v-select",O.setAttribute("aria-label",u("viewer.mech","Mech"));for(let G of _){let K=document.createElement("option");K.value=G,K.textContent=xt(G),K.selected=G===H,O.append(K)}O.addEventListener("change",()=>{H=O.value,X(),Ge(!1)}),o.append(O)}if(yn(g)){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(Le?" is-on":""),O.textContent=B?.layerHead||"Layers",O.setAttribute("data-testid","viewer-layers-btn"),O.addEventListener("click",()=>{if(Le=!Le,d.hidden=!Le,O.classList.toggle("is-on",Le),Le)je("","")}),o.append(O)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="Fit",O.setAttribute("data-testid","viewer-fit-btn"),O.addEventListener("click",()=>{pe?.fit(),ne?.fit()}),o.append(O)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(me&&!se?" is-on":""),O.textContent=me?se?u("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",O.setAttribute("data-testid","viewer-follow-btn"),O.addEventListener("click",()=>void Ke()),o.append(O)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn bp-v-close",F.textContent="✕",F.title=u("common.close","Close"),F.setAttribute("aria-label",u("common.close","Close")),F.setAttribute("data-testid","viewer-close-btn"),F.addEventListener("click",()=>t.closeViewer()),o.append(F)}function oe(){if(!B){d.replaceChildren();return}let I=document.createDocumentFragment(),F=document.createElement("div");F.className="bp-v-layers-head";let O=document.createElement("span");if(O.textContent=B.layerHead||"Layers",F.append(O),B.layerReset){let te=document.createElement("button");te.type="button",te.className="bp-v-btn",te.textContent="Reset",te.addEventListener("click",()=>void je("reset","")),F.append(te)}if(I.append(F),B.layerModes){let te=document.createElement("div");te.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ge,fe)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(B?.layerMode===fe?" is-on":""),Pe.textContent=ge,Pe.addEventListener("click",()=>void je("mode",String(fe))),te.append(Pe)}),I.append(te)}let G=pe?.presentColors()??new Map,K=(B.layerList||[]).concat(B.layerMarks||[]),ee=document.createElement("div");ee.className="bp-v-layers-list";for(let te of K){let ge=G.get(te.layer);if(ge===void 0)continue;let fe=document.createElement("div");fe.className="bp-v-layer-row"+(te.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=te.on!==!1,Pe.addEventListener("change",()=>void je("toggle",String(te.layer)));let Ee=document.createElement("span");Ee.className="bp-v-layer-swatch";let Te=ge>>>16&255,Ie=ge>>>8&255,_e=ge&255;Ee.style.background=te.on!==!1?`rgb(${Te},${Ie},${_e})`:`rgba(${Te},${Ie},${_e},0.2)`;let Fe=document.createElement("button");Fe.type="button",Fe.className="bp-v-layer-name",Fe.textContent=te.name,Fe.addEventListener("click",()=>void je("pick",String(te.layer))),fe.append(Pe,Ee,Fe),ee.append(fe)}I.append(ee),d.replaceChildren(I)}async function je(I,F){if(!yn(g))return;let O=E;try{let G=await t.hub.rpc("viewer.layers",{kind:g,present:Be,off:Ae,focus:we,...I?{action:I,value:F}:{}});if(O!==E||!G)return;Ae=Number(G.own)||0,we=typeof G.focus==="string"?G.focus:"",B=G;let K={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(pe?.setLayers(K),X(),Le)oe()}catch{}}async function We(){if(!me||se||!f||!t.hub.hasFeature("follow"))return;se=!0,X();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function Ke(){if(!f||!t.hub.hasFeature("follow"))return;let I=!me?"on":se?"resume":"off";try{let F=await t.hub.rpc("viewer.follow",{thread:f,action:I});if(me=!!F.on,se=!!F.paused,X(),F.on&&!F.paused&&F.focus&&Array.isArray(F.focus.box)&&F.focus.box.length===4&&(F.seq||0)>ye)ye=F.seq||ye,pe?.zoomToBoxMm([F.focus.box[0],F.focus.box[1],F.focus.box[2],F.focus.box[3]])}catch{}}function ce(){b.hidden=!0,b.replaceChildren(),pe?.setHighlights([])}function lt(I){let F=I.split(";").filter(Boolean),O=F.shift()||I,G=[],K="",ee="";for(let Ee of F){if(Ee.startsWith("g="))continue;let Te=Ee.indexOf("=");if(Te>0){let Ie=Ee.slice(0,Te),_e=Ee.slice(Te+1);if((Ie==="ref"||Ie==="symbol")&&!K)K=_e;if(Ie==="net"&&!ee)ee=_e;G.push([Ie,_e])}else G.push([Ee,""])}let te=document.createElement("div");te.className="bp-v-info-head";let ge=document.createElement("span");ge.className="bp-v-info-title",ge.textContent=O;let fe=document.createElement("button");fe.type="button",fe.className="bp-v-info-x",fe.textContent="×",fe.setAttribute("aria-label","Clear selection"),fe.addEventListener("click",ce),te.append(ge,fe);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Ee,Te]of G){let Ie=document.createElement("span");Ie.className="bp-v-info-chip",Ie.textContent=Te?`${Ee}: ${Te}`:Ee,Pe.append(Ie)}return b.replaceChildren(te,...G.length>0?[Pe]:[]),b.hidden=!1,{ref:K||void 0,net:ee||void 0}}async function Ye(I){if(!I){ce();return}let F=Array.from(k)[0]||"";if(!F)return;let O=E;try{let G=await t.hub.rpc("viewer.info",{key:F,at:I.at,idx:I.idx});if(O!==E)return;let K=typeof G.info==="string"?G.info:"";if(!K){ce();return}let{ref:ee,net:te}=lt(K),ge=[];if(ee)ge.push(["ref",ee]);if(te)ge.push(["net",te]);let fe=[[I.at,I.idx]];for(let[Pe,Ee]of ge){let Te=await t.hub.rpc("viewer.probe",{key:F,name:Pe,value:Ee});if(O!==E)return;if(Array.isArray(Te.matches))for(let Ie of Te.matches)fe.push(Ie)}pe?.setHighlights(fe)}catch{ce()}}function ct(){Z?.destroy(),Z=null,le?.destroy(),le=null,pe?.destroy(),pe=null,ne?.destroy(),ne=null,h.replaceChildren(),Le=!1,d.hidden=!0,b.hidden=!0,b.replaceChildren(),he("",!1),de("none")}function Xe(){A=[],N=0}async function Ge(I){if(!f||!g)return;let F=++E;if(k.clear(),x=!1,Xe(),ct(),X(),J(),re(),(g==="board"||g==="schematic")&&f)ke(f);if(Js(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")Z=$i(h,t,f,(K,ee)=>{if(g=K,ue=ee,K==="mech")H=ee;Ge(!1)});else if(g==="diff")Z=Gi(h,t,f);else if(g==="review")Z=Oi(h,t,f);else if(g==="browser")Z=Hi(h,t,f);else if(g==="terminal")de("loading","Loading terminal…"),import("/assets/terminal.js").then((ee)=>{if(F!==E)return;if(de("none"),ee?.mountTerminalPane)le=ee.mountTerminalPane(h,t,f,He());else de("error","Terminal chunk missing",!0)},(ee)=>{if(F!==E)return;de("error",ee instanceof Error?ee.message:String(ee),!0)});return}if(de("loading","Loading…"),!W.root)try{let K=await t.hub.rpc("viewer.files",{thread:f});if(F!==E)return;W=K||{},X()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){de("empty","No Gerbers in this project",!1);return}let O=He();if(g==="3d"||g==="mech")ne=new vn(h,{onStatus:(K,ee)=>{if(ee)de("none"),he(K,!1);else if(K)de("loading",K);else de("none"),he("",!1)},onUserMove:()=>void We()}),ne.setTheme(O);else if(g==="board"||g==="schematic"||g==="gerbers")pe=new un(h,{onPick:(K)=>void Ye(K),onUserMove:()=>void We()}),pe.setTheme(O);else{de("empty",`${Yi(g)} is not available in this viewer`,!1);return}let G={thread:f};if(I)G.force=!0;if(g==="mech"){if(_.length===0)try{let K=await t.hub.rpc("mech.list",{thread:f});if(F!==E)return;if(_=Array.isArray(K.parts)?K.parts:[],!H)H=K.primary||_[0]||"";X()}catch(K){if(F!==E)return;de("error",K instanceof Error?K.message:String(K),!0);return}if(!H){de("empty",u("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=H}else{if(G.kind=g,ue&&(g==="board"||g==="schematic"))G.path=ue;if(g==="3d"&&!I&&ne){let K=ne.keptToken();if(K)G.kept=K}if((g==="board"||g==="schematic"||g==="gerbers")&&!I&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(D.keys())}x=!0,S="",R="",q="",T="";try{let K=await t.hub.rpc("viewer.watch",G);if(F!==E)return;k=new Set(Array.isArray(K.keys)?K.keys:[]),x=!1;let ee=A;Xe();for(let te of ee)if(te.kind==="bin")Oe(te.buf);else Ue(te.key,te.none,te.retryable)}catch(K){if(F!==E)return;x=!1,k.clear(),Xe();let ee=K instanceof Error?K.message:String(K),te=/no gerbers|not in this project|another machine/i.test(ee);de(te?"empty":"error",ee,!te)}}function Ue(I,F,O){if(x){if(A.length{if(I.t==="plot"&&typeof I.none==="string"&&typeof I.key==="string")Ue(I.key,I.none,I.retryable===!0)}),Ft=At(()=>{if(g)X()}),kt=(I)=>{if(I.key==="Escape"&&g&&!b.hidden)ce()};return window.addEventListener("keydown",kt),{open(I,F){if(F!==f){if(f=F,W={},_=[],H="",M.clear(),me=!1,se=!1,ye=0,Ae=0,we="",Be=0,B=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:F}).then((O)=>{if(F!==f)return;if(me=!!O.on,se=!!O.paused,ye=Number(O.seq)||0,g)X()}).catch(()=>{})}if(I!==g)z(),j.goLive(),Ae=0,we="",Be=0,B=null;g=I,ue="",Ge(!1)},reconcileHas(I){if(g&&!zs(g,I))t.closeViewer()},close(){if(E++,x=!1,z(),C=!1,S="",R="",q="",T="",j.goLive(),l.hidden=!0,y.hidden=!0,Xe(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",k.clear(),ct()}}}var Xi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(Xi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Xi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ys(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Zi(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Qi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function Xs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function es(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,m,c);let h=document.createElement("div");h.className="bp-top-state bp-hide-phone bp-hidden";let p=document.createElement("span");p.className="bp-top-state-lbl",p.textContent="STATE";let d=document.createElement("span");d.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",h.append(p,d,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=u("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=u("menu.settle","Settle"),E.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let k=document.createElement("div");k.className="bp-menu-wrap";let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost bp-top-act",A.textContent="▾",A.title="Thread menu",A.setAttribute("aria-label","Thread menu"),A.setAttribute("data-testid","thread-menu-btn");let N=document.createElement("div");N.className="bp-popover bp-hidden",N.setAttribute("data-testid","thread-menu"),k.append(A,N),y.append(f,E,k);let M=document.createElement("div");M.className="bp-top-right";let D=document.createElement("button");D.type="button",D.className="bp-btn-ghost bp-top-act bp-hide-tablet",D.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=u("gpui.improvements","Improvements"),D.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ue=document.createElement("button");ue.type="button",ue.className="icon bp-top-icon",ue.title=u("palette.settings","Settings"),ue.setAttribute("aria-label",u("palette.settings","Settings")),ue.setAttribute("data-testid","settings-btn"),ue.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(D,_,H,ue),t.append(n,i,h,y,M);let me=document.createElement("div");me.className="bp-body";let se=document.createElement("aside");se.className="bp-sidebar",se.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ae=document.createElement("div");Ae.className="bp-right-top";let we=document.createElement("section");we.className="bp-viewer-pane bp-hidden",we.setAttribute("data-testid","viewer-pane"),Ae.appendChild(we),Le.appendChild(Ae);let Be=document.createElement("nav");Be.className="bp-rail",Be.setAttribute("aria-label","Viewer rail"),Be.setAttribute("data-testid","viewer-rail"),me.append(se,ye,Le,Be),e.append(t,me);let B=new mn,pe=null,ne=new Set,Z=0,le=null,j=[],Y=[],C=[],S=[],R=[],q=[],T="",z=0,J=0,Me=null,re=null,ke="",He=null,be=20,de={},he=new Map;function Re(v,w){he.delete(v),he.set(v,w);while(he.size>be){let L=he.keys().next().value;if(L!==void 0)he.delete(L);else break}}let X=new cn(se,{onSelectThread:(v)=>{if(v===T&&Me!==null){se.classList.remove("bp-sidebar-open");return}Ee(v)},onNewThread:(v)=>{Fe(v)},onSelectBot:(v)=>{Ee(v.thread)},onThreadAct:(v,w)=>{et(v,w)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ge()},onToggleProjectFold:(v)=>{B.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ge()).catch(()=>{})},onCollapseSidebar:()=>{se.classList.remove("bp-sidebar-open"),se.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let w=jt(v,!1);if(!w)return;if(w.kind==="thread"){Ee(w.id);return}if(w.kind!=="call")return;let L=wi(await B.rpc(w.method,w.params));if(L?.kind==="thread")Ee(L.id);ge()},hasRoomView:!1,onAddProject:()=>Ue.open({mode:"folder"})}),oe=new Kt(ye,{onLoadOlder:()=>{_e()},onGoToEntry:(v)=>{Ie(v)},onAnswerAsk:(v,w)=>{B.rpc("ask.answer",{ask:v,answer:w}).catch((L)=>{ce.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!T)return;let w=z;B.rpc("thread.review",{thread:T,on:v}).then((L)=>{if(w===z)oe.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,w)=>{if(!T)return;if(v==="again"||v==="thread-again")B.rpc("thread.again",{thread:T,value:w}).catch(()=>{});else B.rpc("thread.act",{thread:T,action:v,value:w}).catch(()=>{})},onReplyEntry:(v)=>{if(!B.hasFeature("reply")){let w=(v.text||"").split(` +`)[0]?.slice(0,100)??"";if(w)ce.prependDraft(`> ${w} +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,w)=>{try{let L={entry:v,path:w};if(B.hasFeature("blobs"))L.metaOnly=!0;let P=await B.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function je(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function We(v,w){if(!T)return;let L=z,P=T;B.rpc(v,w).then((V)=>{if(L!==z||T!==P)return;if(V.thread){let ie=Y.findIndex((ve)=>ve.id===V.thread.id);if(ie>=0)Y[ie]=V.thread;else Y.unshift(V.thread);X.setData(j,Y,C,S),oe.updateThreadMeta(V.thread),I(),ce.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(L===z&&T===P)ce.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let Ke,ce=new Jt(ye,{onSend:(v,w)=>{En(v,w)},onRunCommand:(v)=>{xn(v)},onInterrupt:()=>{if(T)B.rpc("turn.interrupt",{thread:T}).catch(()=>{})},onQueryMentions:async(v,w)=>{try{return(await B.rpc("mentions.list",{q:v,kind:w,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Ke.toggle()},onCyclePlanMode:()=>{let v=Y.find((L)=>L.id===T)??null,w=je(v);if(!w||!T)return;if(w.interaction!=="plan")We("thread.planonce",{thread:T,on:!0});else if(w.once)We("thread.pick",{thread:T,action:"interaction",value:"plan"});else We("thread.pick",{thread:T,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!T)return;if(v==="once")We("thread.planonce",{thread:T,on:!0});else if(v==="always")We("thread.pick",{thread:T,action:"interaction",value:"plan"});else We("thread.pick",{thread:T,action:"interaction",value:"default"})}});Ke=new dn(B,{getThreadId:()=>T,getDraft:()=>ce.getDraft(),getCaret:()=>ce.getCaret(),setDraft:(v)=>ce.setDraft(v),setRecording:(v)=>ce.setVoiceRecording(v),setLevel:(v)=>ce.setVoiceLevel(v),showError:(v)=>ce.showError(v)});function lt(){let v=ke!=="",w=Ye.isOpen();Le.classList.toggle("bp-hidden",!v&&!w),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",w)}let Ye=new nn(Ae,Le,{hub:B,getThreadId:()=>T,getThreadGen:()=>z,onSendText:(v)=>{En(v)},onOpenChange:()=>lt()});function ct(v){let w=window.prompt("Rename thread",v.title||"");if(!w||!w.trim())return;B.rpc("thread.act",{thread:v.id,action:"rename",title:w.trim()}).then((L)=>{if(L.thread)Y=Y.map((P)=>P.id===L.thread.id?L.thread:P),I(),ge()}).catch((L)=>{ce.showError(L instanceof Error?L.message:"Could not rename thread")})}function Xe(v){switch(v.type){case"thread":Ee(v.id);break;case"rail":if(!T&&v.id!=="terminal")break;if(ke===v.id)F();else O(v.id);break;case"thread-act":if(T)et(T,v.action);break;case"new-thread":Fe(v.projectId);break;case"rename":{let w=Y.find((L)=>L.id===T);if(w)ct(w);break}case"prev-thread":case"next-thread":{let w=Y.filter((ie)=>!ie.archived&&!ie.swarm);if(w.length<2)break;let L=w.findIndex((ie)=>ie.id===T),P=v.type==="next-thread"?1:-1,V=w[(L<0?0:L+P+w.length)%w.length];if(V)Ee(V.id);break}case"command":if(v.runDirectly)xn(v.word);else ce.setDraft(`${v.word} `),ce.focus();break;case"improvements":kt();break;case"settings":ze.open();break;case"sidebar":se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed");break}}let Ge=new sn(e,{getState:()=>({selectedThreadId:T,threads:Y,projects:j,bots:C,railItems:R,commands:q}),onSearch:async(v)=>{if(!B.hasFeature("search"))return{threads:[],projects:[],messages:[]};return B.rpc("search",{q:v,limit:20})},onExecute:Xe}),Ue=new Wt(e,{hub:B,onProjectAdded:(v)=>{if(ge(),v.id)Fe(v.id)},onCloneDone:(v)=>{if(ge(),v.thread)Ee(v.thread)}}),Oe=new an(Be,(v)=>{if(v==="commands"){Ge.open();return}if(!T)return;if(ke===v)F();else O(v)}),it=null,ze=new rn(e,{onLoadDevices:async()=>(await B.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,w)=>{await B.rpc("devices.page.act",{action:v,value:w})},onGetHome:()=>it,onMoveHomeHere:async()=>{await B.rpc("home.move",{to:"back"})},onLogout:()=>Dn(()=>{B.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=Y.find((w)=>w.id===T);if(v)et(v.id,v.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let v=Y.find((w)=>w.id===T);if(v)et(v.id,v.settled?"unsettle":"settle")});let Ft=new ln(e,(v,w)=>w?B.rpc("thread.context.mcp",{thread:v,...w}):B.rpc("thread.context",{thread:v}));A.addEventListener("click",(v)=>{v.stopPropagation();let w=Y.find((V)=>V.id===T);if(!w)return;if(!N.classList.contains("bp-hidden")){N.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ct(w)},{label:w.pinned?u("menu.unpin","Unpin"):u("menu.pin","Pin"),run:()=>{et(w.id,w.pinned?"unpin":"pin")}},{label:w.settled?u("phone.unsettle","Unsettle"):u("menu.settle","Settle"),run:()=>{et(w.id,w.settled?"unsettle":"settle")}},{label:w.archived?"Unarchive":"Archive",run:()=>{et(w.id,w.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))et(w.id,"delete")}}];if(B.hasFeature("threadContext"))L.unshift({label:u("thread.context.title","Context & Prompt"),run:()=>Ft.open(w.id)});let P=document.createDocumentFragment();for(let V of L){let ie=document.createElement("button");ie.type="button",ie.className="bp-popover-item"+(V.danger?" danger":""),ie.textContent=V.label,ie.addEventListener("click",()=>{N.classList.add("bp-hidden"),V.run()}),P.appendChild(ie)}N.replaceChildren(P),N.classList.remove("bp-hidden")}),document.addEventListener("click",()=>N.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let w=document.createElement("div");w.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=u("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),L.append(P,V);let ie=document.createElement("div");ie.className="bp-modal-body",ie.textContent="Loading…",w.append(L,ie),v.appendChild(w),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await B.rpc("improvements.projects",{}),De=ve.projects??[];if(De.length===0){ie.textContent="No projects available for Improvements.";return}let tt=document.createDocumentFragment();for(let Se of De){let ae=document.createElement("div");ae.className="bp-set-row";let Qe=document.createElement("div");Qe.className="bp-set-info",Qe.textContent=Se.title||Se.name||Se.id;let nt=document.createElement("button");nt.type="button",nt.className=Se.id===ve.project?"primary":"",nt.textContent=Se.id===ve.project?"Active":"Select",nt.addEventListener("click",()=>{B.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),ae.append(Qe,nt),tt.appendChild(ae)}ie.replaceChildren(tt)}catch(ve){ie.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}D.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>Ge.open()),H.addEventListener("click",()=>Ge.open()),ue.addEventListener("click",()=>{ze.open()}),n.addEventListener("click",()=>{se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed")});function I(){let v=Y.find((P)=>P.id===T)??null,w=v?j.find((P)=>P.id===v.project):void 0;o.textContent=w?.title??"",r.classList.toggle("bp-hidden",!w),l.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let L=je(v);if(ce.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=u("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?u("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?u("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?u("gpui.planmode.top.planning","Planning"):L.phase==="pending"?u("gpui.planmode.top.pending","Review plan"):u("gpui.planmode.top.executing","Building plan");if(h.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){d.className=`bp-dot ${Ys(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?u("menu.unpin","Unpin"):u("menu.pin","Pin"),x.textContent=v.settled?u("phone.unsettle","Unsettle"):u("menu.settle","Settle");let P=v;ce.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),ce.setMemory(v.memory)}else ce.setModelChip("default"),ce.setMemory(null)}function F(v=!0){if(J++,ke="",Oe.setActive(""),we.classList.add("bp-hidden"),He?.close(),lt(),v&&T&&B.getState()==="connected")B.rpc("viewer.watch",{thread:T,kind:""}).catch(()=>{})}function O(v){if(J++,ke=v,Oe.setActive(v),we.classList.remove("bp-hidden"),lt(),!He&&typeof wn==="function")He=wn(we,{hub:B,getThreadId:()=>T,closeViewer:()=>F(!0)});if(He)He.open(v,T);else{let w=document.createElement("div");w.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>F(!0)),L.append(P,V);let ie=document.createElement("div");ie.className="bp-dim bp-viewer-msg",ie.textContent=`Viewer pane (${v}).`,w.append(L,ie),we.replaceChildren(w)}}async function G(v,w){if(!v||!B.hasFeature("rail")){if(w===z)R=[],Oe.setItems([]);return}let L=++J;try{let P=await B.rpc("viewer.rail",{thread:v,page:ke});if(w!==z||L!==J)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(R=V,Oe.setItems(V),P.has){if(He?.reconcileHas?.(P.has),ke&&!Zi(P.has,ke))F(!0)}}catch{if(w===z&&L===J)R=[],Oe.setItems([])}}function K(v){for(let w of v)if(w.kind==="threads"){for(let L of w.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(w.kind==="projects"){for(let L of w.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function ee(v,w){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===w))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===w))return!0}return!1}function te(v){let w=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)w.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(w.length>0)j=w}async function ge(){if(!B.hasFeature("sections"))return!1;let v=++Z;try{let w=await B.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==Z)return!0;let L=Array.isArray(w.sections)?w.sections:[];return pe=L,te(L),X.setData(j,Y,C,S),X.setSections(L,C,S),I(),!0}catch{return!1}}function fe(){if(!B.hasFeature("sections"))return;if(le!==null)window.clearTimeout(le);le=window.setTimeout(()=>{le=null,ge()},150)}async function Pe(){if(Me=null,B.hasFeature("bots"))try{let w=await B.rpc("bots.list",{});C=w.bots??[],S=w.rooms??[]}catch{}if(B.hasFeature("shell")){let w=await B.rpc("shell.sync",{have:de,settled:25}),L=new Set(w.removed??[]),P=new Set((w.projects??[]).map((V)=>V.id));if(L.size>0||P.size>0)j=[...j.filter((V)=>!L.has(V.id)&&!P.has(V.id)),...w.projects??[]],Y=[...Y.filter((V)=>!L.has(V.project)&&!P.has(V.project)),...w.threads??[]];else if(Array.isArray(w.threads)&&w.threads.length>0){let V=new Map(Y.map((ie)=>[ie.id,ie]));for(let ie of w.threads)V.set(ie.id,ie);Y=Array.from(V.values())}if(w.sections!==void 0){let V=Array.isArray(w.sections)?w.sections:Array.isArray(w.sections?.sections)?w.sections.sections:null;if(V)pe=V,te(V)}if(w.h)de=w.h;X.setData(j,Y,C,S),X.setSections(pe,C,S)}else if(B.hasFeature("sections")){let[w,L]=await Promise.all([B.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),B.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(Y=L.threads??[],w&&Array.isArray(w.sections)){let P=w.sections;if(!P.some((ie)=>ie.kind==="projects"&&ie.rows.length>0)){let ie=P.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(ie?.toggle&&!ne.has(ie.toggle)){ne.add(ie.toggle);let ve=await B.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))P=ve.sections}}pe=P,te(P),X.setData(j,Y,C,S),X.setSections(P,C,S)}else pe=null,j=(await B.rpc("projects.list",{limit:100})).projects??[],X.setSections(null,C,S),X.setData(j,Y,C,S);await B.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{pe=null;let[w,L]=await Promise.all([B.rpc("projects.list",{limit:100}),B.rpc("threads.list",{limit:200,archived:!1})]);j=w.projects??[],Y=L.threads??[],X.setSections(null,C,S),X.setData(j,Y,C,S),await B.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=T;if(!v){let w="";try{w=localStorage.getItem("bp.lastThread")||""}catch{}if(w&&(pe&&ee(pe,w)||Y.some((L)=>L.id===w)))v=w;else if(pe)v=K(pe);if(!v)v=(Y.find((P)=>!P.archived&&!P.swarm&&!P.settled)??Y.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(pe&&ee(pe,v)||Y.some((w)=>w.id===v)))await Ee(v);else T="",R=[],Oe.setItems([]),ce.setState(!1,!1),I()}async function Ee(v){if(T&&T!==v){Ke.cancel();let Se=oe.getEntries();if(Se.length>0){let ae=he.get(T);Re(T,{entries:Se,ids:ae?.ids??Se.map((Qe)=>Qe.id),olderCursor:re,review:ae?.review??null,unanswered:ae?.unanswered??null,rail:ae?.rail??R,hashes:ae?.hashes??{}})}}let w=++z;J++,Ve(null);let L=Me;if(Me=null,L!==null)B.rpc("unsubscribe",{sub:L}).catch(()=>{});T=v;let P=he.get(v);re=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}X.setSelected(v),se.classList.remove("bp-sidebar-open"),I();let V=Y.find((Se)=>Se.id===v)??null;if(P)oe.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),R=P.rail,Oe.setItems(P.rail);else oe.setLoading(V),R=[],Oe.setItems([]);if(ce.setState(!0,V?.state==="working"),B.hasFeature("open")){let Se={};if(P){for(let[Ne,pt]of Object.entries(P.hashes))Se[Ne]=pt;for(let Ne of P.entries)if(Ne.h)Se[Ne.id]=Ne.h}let ae;try{ae=await B.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Ne){if(w===z){let pt=Ne instanceof Error&&Ne.message?Ne.message:"Could not load messages.";oe.setError(V,pt,()=>{Ee(v)})}return}if(w!==z){if(ae.sub!==void 0&&ae.sub!==null)B.rpc("unsubscribe",{sub:ae.sub}).catch(()=>{});return}if(Me=ae.sub??null,ae.thread){V=ae.thread;let Ne=Y.findIndex((pt)=>pt.id===ae.thread.id);if(Ne>=0)Y[Ne]=ae.thread;else Y.unshift(ae.thread);I(),ce.setState(!0,V.state==="working")}if("next"in ae)re=ae.next??null;let Qe=new Map;if(P)for(let Ne of P.entries)Qe.set(Ne.id,Ne);for(let Ne of ae.entries??[])Qe.set(Ne.id,Ne);let nt=ae.ids??P?.ids??(ae.entries??[]).map((Ne)=>Ne.id),kn=nt.map((Ne)=>Qe.get(Ne)).filter((Ne)=>Boolean(Ne)),dt=P?.rail??[];if(ae.rail!==void 0){if(Array.isArray(ae.rail))dt=ae.rail;else if(dt=Array.isArray(ae.rail?.rail)?ae.rail.rail:Array.isArray(ae.rail?.items)?ae.rail.items:[],ae.rail?.has){if(He?.reconcileHas?.(ae.rail.has),ke&&!Zi(ae.rail.has,ke))F(!0)}}R=dt,Oe.setItems(dt);let $t=P?.review??null;if(B.hasFeature("reviewmode"))try{let Ne=await B.rpc("thread.review",{thread:v});if(w!==z)return;$t=Ne.review??null}catch{}if(w!==z)return;let Sn="unanswered"in ae?ae.unanswered??null:P?.unanswered??null,ts=ae.h??P?.hashes??{};if(Re(v,{entries:kn,ids:nt,olderCursor:re,review:$t,unanswered:Sn,rail:dt,hashes:ts}),oe.setThread(V,kn,Boolean(re),$t,Sn),Te(v,w),ke)O(ke);return}let ie;try{ie=await B.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(w===z){let ae=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";oe.setError(V,ae,()=>{Ee(v)})}return}if(w!==z)return;if(ie.thread){let Se=Y.findIndex((ae)=>ae.id===ie.thread.id);if(Se>=0)Y[Se]=ie.thread;else Y.unshift(ie.thread);I()}re=ie.next??null;let ve=null;if(B.hasFeature("reviewmode"))try{let Se=await B.rpc("thread.review",{thread:v});if(w!==z)return;ve=Se.review??null}catch{}if(w!==z)return;let De=ie.entries??[],tt=ie.unanswered??null;Re(v,{entries:De,ids:De.map((Se)=>Se.id),olderCursor:re,review:ve,unanswered:tt,rail:P?.rail??[],hashes:P?.hashes??{}}),oe.setThread(V,De,Boolean(re),ve,tt);try{let ae=(await B.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(ae!==null){if(w!==z){B.rpc("unsubscribe",{sub:ae}).catch(()=>{});return}Me=ae}}catch{}if(w!==z)return;if(G(v,w),Te(v,w),ke)O(ke)}async function Te(v,w){if(!v||!B.hasFeature("mgmt")){if(w===z)Ye.clear();return}let L=Y.find((V)=>V.id===v),P=L?.project?j.find((V)=>V.id===L.project)?.root??"":"";if(!P&&B.hasFeature("viewers"))try{let V=await B.rpc("viewer.files",{thread:v});if(w!==z)return;P=V.pcb||V.sch||V.root||""}catch{}if(w!==z)return;if(P)await Ye.watchProject(P);else Ye.clear()}async function Ie(v){let w=z;for(let L=0;L<25&&w===z;L++){if(oe.goTo(v))return;if(!re)return;let P=re;if(await _e(),re===P)return}}async function _e(){if(!T||!re){oe.clearLoadingOlder();return}let v=z,w=T,L=re;try{let P=await B.rpc("thread.entries",{thread:w,limit:40,before:L});if(v!==z||T!==w)return;re=P.next??null,oe.prependEntries(P.entries??[],Boolean(re))}catch{if(v===z)oe.clearLoadingOlder()}}async function Fe(v){try{let w=await B.rpc("thread.create",{project:v});if(w.thread)Y=[w.thread,...Y.filter((L)=>L.id!==w.thread.id)],X.setData(j,Y,C,S),ge(),await Ee(w.thread.id),ce.focus()}catch(w){ce.showError(w instanceof Error?w.message:"Could not create thread")}}let Ze=null;function St(v){return(v.split(` +`).map((w)=>w.trim()).find((w)=>w.length>0)??"").slice(0,200)}function Ve(v){Ze=v,ce.setReply(v?{who:v.role==="user"?u("secret.you","You"):u("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Ze)Ie(Ze.id)},()=>Ve(null))}async function En(v,w=[]){if(!T)return;let L=z,P=T,V=Xs(),ie=`local-${V}`,ve=Ze&&v.trim()&&B.hasFeature("reply")?Ze:null;if(ve)Ve(null);oe.upsertEntry({id:ie,kind:"user",text:v,at:Date.now(),clientId:V,...ve?{replyTo:{id:ve.id,quote:St(ve.text)}}:{},attachments:w.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:P,text:v,clientId:V};if(w.length>0)De.attachments=w;if(ve)De.replyTo={id:ve.id,text:ve.text};let tt=await B.rpc("message.send",De);if(L!==z||T!==P)return;if(tt.entry)oe.upsertEntry(tt.entry)}catch(De){if(L===z&&T===P){if(oe.removeEntry(ie),ce.setDraft(v),ve&&!Ze)Ve(ve);ce.showError(De instanceof Error?De.message:"Failed to send message")}}}async function xn(v){if(!T)return;let w=z,L=T;try{let P=await B.rpc("composer.run",{thread:L,text:v});if(w!==z||T!==L)return;if(P.error)ce.setDraft(v),ce.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")ce.setDraft(P.text);else if(P.kind==="project")Ue.open({mode:"folder"});else if(P.kind==="clone")Ue.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(w===z&&T===L)ce.setDraft(v),ce.showError(P instanceof Error?P.message:"Command refused")}}async function et(v,w){try{let L=await B.rpc("thread.act",{thread:v,action:w});if(L.thread){if(Y=Y.map((P)=>P.id===L.thread.id?L.thread:P),X.setData(j,Y,C,S),L.thread.id===T)oe.updateThreadMeta(L.thread),I()}ge()}catch(L){ce.showError(L instanceof Error?L.message:`Action "${w}" not allowed`)}}function Cn(v,w){if(!v||!v.text||w-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return u("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return u("hub.stopped",v.text);return u("hub.restarting",v.text)}function Lt(v){if(v==="connected")X.setConnStatus(u("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Cn(B.restarting,Date.now()))X.setConnStatus(Cn(B.restarting,Date.now()),"");else if(v==="reconnecting")X.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")X.setConnStatus(u("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else X.setConnStatus("Connecting…","")}At(()=>{Lt(B.getState()),W.textContent=u("gpui.improvements","Improvements"),ue.title=u("palette.settings","Settings"),ue.setAttribute("aria-label",u("palette.settings","Settings")),I(),X.refreshLocale(),oe.refreshLocale(),ce.refreshLocale(),Oe.render(),ze.refreshLocale(),Ue.refreshLocale()}),B.onState((v,w)=>{if(v==="connected"&&w){if(w.locale)Tn(w.locale);if(w.theme)Qi(w.theme);if(w.name)X.setHostName(w.name);if(it=w.home??null,X.setHome(it),ze.isOpen())ze.refresh();Lt(v);let L=typeof w.hubBack==="string"?String(w.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")X.setConnStatus(u("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Lt(B.getState()),6000)}catch{}if(ce.setFeatures(B.hasFeature("images"),B.hasFeature("voice")),Array.isArray(w.commands))q=w.commands,ce.setCommands(q);else q=[];Pe(),Ue.reconcile()}else Ke.cancel(),Lt(v)}),B.onFrame((v)=>{if(v.t==="voice"){Ke.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Ye.handleInfo(v.info);return}if(v.t!=="d")return;let w=v;if(w.k==="clone"||w.k==="clone.repos"||w.k==="clone.signin"){Ue.handleFrame(w);return}switch(w.k){case"project":{let L=w.project;if(!L)break;let P=j.findIndex((V)=>V.id===L.id);if(P>=0)j[P]=L;else j.unshift(L);X.setData(j,Y,C,S),I(),fe();break}case"thread":{let L=w.thread;if(!L)break;let P=Y.findIndex((V)=>V.id===L.id);if(P>=0)Y[P]=L;else Y.unshift(L);if(X.setData(j,Y,C,S),L.id===T)oe.updateThreadMeta(L),I(),ce.setState(!0,L.state==="working");fe();break}case"thread.removed":{let L=String(w.id??"");Y=Y.filter((P)=>P.id!==L),X.setData(j,Y,C,S),fe();break}case"entry":{if(w.thread===T&&w.entry)oe.upsertEntry(w.entry);break}case"text":{if(w.thread===T)oe.appendLiveText(String(w.entry??""),String(w.append??""),Number(w.at??Date.now()));break}case"turn":{if(w.thread===T){let L=String(w.state??"idle");ce.setState(!0,L==="working"),G(T,z)}fe();break}case"btw":{if(w.thread===T)oe.showBtw(String(w.q??""),String(w.a??""));break}case"unanswered":{if(w.thread===T)oe.setUnanswered(w.unanswered??null);break}case"theme":{if(typeof w.theme==="string")Qi(w.theme);break}case"home":{if(it=w.home??null,X.setHome(it),ze.isOpen())ze.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let w=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(w==="k"||v.shiftKey&&w==="p"))if(v.preventDefault(),Ge.isOpen())Ge.close();else Ge.open();else if(v.key==="Escape"){if(Ge.isOpen())Ge.close();else if(Ue.isOpen())Ue.escape();else if(ze.isOpen())ze.close();else if(oe.closePlanRevise());else if(Ye.isOpen())Ye.closePanel()}}),B.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",es);else es(); diff --git a/web/dist/manifest.json b/web/dist/manifest.json index e48828b70c..852739285f 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 200991, + "totalAssetGzipBytes": 201187, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -278,13 +278,13 @@ "web/src/inflate.ts": "bc10ed23159668193d6de6d582e60baf009cae0a619018f0588f836a77dde831", "web/src/logout.ts": "9d29482c4671deee1e868ee477b123e067a4c22f7d8ac30b4c2420cf71b8ebe2", "web/src/md.ts": "c606d1ec598b3ce132c7cc9366383dacafc3fcb71c0fccd97b41ec0e19a96c78", - "web/src/mgmt-model.ts": "89af6290740690cac0bd1fd986098ede9d5bbed96b22f80c5a176f7e625f18ea", - "web/src/mgmt.ts": "1a2ae80790f345a38377833ae2b93724ce3fd1d2ba600e6d44faaa26c7b98744", + "web/src/mgmt-model.ts": "3bf50952af7687afaec3c43e84890176aedf5400a45688fe8ee2e5161040f76b", + "web/src/mgmt.ts": "d4e9fb07c8bfebd4f3308b31f8ff3b3dc31cc2470320f7202fe3831c1f437bed", "web/src/pair.html": "cf7b94703316f910718356e9ff8e99e088b68211db39b5200213b623c9275f6e", "web/src/pair.ts": "af07d19224043f8176f8cd2298d00b6806248eee453fd2f287c183e71a08179b", "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", - "web/src/plan-canvas.ts": "fdd06b67480d731ac7baa4f22de1ad72f9fdc6388198408dcd87efedc7126eb6", + "web/src/plan-canvas.ts": "c4685c70d76fa7b651a9b008017984139a3909afb7370477151f29b0421375d3", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "7b4d8be26fabc6c2a0b8af94a64572a0e3c1e589bf079bfa58c8985a8acd984a", @@ -317,9 +317,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 334768, - "gzipBytes": 94405, - "sha256": "659b1c4303b47a29f1cc08dfbc83ef0e75fe8dd4ff554c3581ee7642ba5686db" + "bytes": 335684, + "gzipBytes": 94601, + "sha256": "83e06d714bcfdd30fcf9ae72446381181cd287b22be1a93ee87a0e2c9b5b48b5" }, "assets/favicon-light.svg": { "bytes": 1207, diff --git a/web/src/mgmt-model.ts b/web/src/mgmt-model.ts index 934d3677dc..2d2e5f7bf0 100644 --- a/web/src/mgmt-model.ts +++ b/web/src/mgmt-model.ts @@ -920,3 +920,21 @@ export function planAllCanvasLayers(layers: PlanLayer[], copperLayers?: PlanCopp } return out; } + +export function isPlanHydrationCurrent( + reqWatchGen: number, + curWatchGen: number, + reqHydGen: number, + curHydGen: number, + reqProject: string, + curProject: string, + panelRev: number, + prevHydratedRev: number | undefined, +): boolean { + return ( + reqWatchGen === curWatchGen && + reqHydGen === curHydGen && + reqProject === curProject && + (prevHydratedRev === undefined || panelRev >= prevHydratedRev) + ); +} diff --git a/web/src/mgmt.ts b/web/src/mgmt.ts index 9ceb558ced..2451192310 100644 --- a/web/src/mgmt.ts +++ b/web/src/mgmt.ts @@ -13,6 +13,7 @@ import { formatUtcDay, isBomWriteCurrent, isChecksFixCurrent, + isPlanHydrationCurrent, lifeWord, mgmtPanelsOf, money, @@ -101,6 +102,9 @@ export class MgmtStrip { private planOptimisticRev: number | undefined = undefined; private planHydratedKey = ""; private planHydrateAskedKey = ""; + private planHydrateGen = 0; + private planHydratedRev: number | undefined = undefined; + private planRenderDeferred = false; private planHydratedBoard: PlanBoardGeom | null = null; private planHydratedDraw: { bands?: PlanBand[]; regions?: PlanRegion[] } | null = null; private planNoteOpen = false; @@ -169,6 +173,9 @@ export class MgmtStrip { this.planOptimisticRev = undefined; this.planHydratedKey = ""; this.planHydrateAskedKey = ""; + this.planHydrateGen++; + this.planHydratedRev = undefined; + this.planRenderDeferred = false; this.planHydratedBoard = null; this.planHydratedDraw = null; this.planNoteOpen = false; @@ -210,6 +217,9 @@ export class MgmtStrip { this.planOptimisticRev = undefined; this.planHydratedKey = ""; this.planHydrateAskedKey = ""; + this.planHydrateGen++; + this.planHydratedRev = undefined; + this.planRenderDeferred = false; this.planHydratedBoard = null; this.planHydratedDraw = null; this.planNoteOpen = false; @@ -302,6 +312,11 @@ export class MgmtStrip { } public render(): void { + if (this.openPanel === "plan" && this.planCanvas?.isDragging()) { + this.planRenderDeferred = true; + return; + } + this.planRenderDeferred = false; const state = this.getStateInfo(); const tabs = mgmtPanelsOf(state); if (!this.digest || tabs.length === 0) { @@ -384,6 +399,12 @@ export class MgmtStrip { this.panelEl.classList.remove("bp-hidden"); this.panelEl.setAttribute("data-testid", `mgmt-panel-${this.openPanel}`); this.cb.onOpenChange?.(true); + const keepCanvasFocus = + this.openPanel === "plan" && + this.planCanvas !== null && + document.activeElement instanceof HTMLElement && + this.panelEl.contains(document.activeElement) && + (document.activeElement === this.planCanvas.root || this.planCanvas.root.contains(document.activeElement)); const body = document.createDocumentFragment(); if (this.errorMsg) { const err = document.createElement("div"); @@ -408,11 +429,6 @@ export class MgmtStrip { body.appendChild(this.renderFab()); break; } - const keepCanvasFocus = - this.planCanvas !== null && - document.activeElement instanceof HTMLElement && - this.panelEl.contains(document.activeElement) && - this.planCanvas.root.contains(document.activeElement); this.panelEl.replaceChildren(body); if (keepCanvasFocus) { this.planCanvas?.root.focus({ preventScroll: true }); @@ -1018,12 +1034,19 @@ export class MgmtStrip { if (d.board_trimmed && this.planHydrateAskedKey !== hydKey && this.project) { this.planHydrateAskedKey = hydKey; const gen = this.watchGen; + const hydGen = ++this.planHydrateGen; const proj = this.project; + const fallbackRev = d.revision ?? 0; void this.cb.hub.rpc("plan.get", { pro: proj, board: true }) .then((res) => { const panel = unwrapPlanGetPanel(res); - if (gen !== this.watchGen || proj !== this.project || !panel) return; - this.planHydratedKey = hydKey; + if (!panel) return; + const panelRev = typeof panel.revision === "number" ? panel.revision : fallbackRev; + if (!isPlanHydrationCurrent(gen, this.watchGen, hydGen, this.planHydrateGen, proj, this.project, panelRev, this.planHydratedRev)) { + return; + } + this.planHydratedRev = panelRev; + this.planHydratedKey = `${proj}:${panelRev}`; this.planHydratedBoard = panel.board ?? null; this.planHydratedDraw = panel.draw ?? null; this.render(); @@ -1352,10 +1375,14 @@ export class MgmtStrip { viewBar.append(viewSpacer, expBtn); wrap.appendChild(viewBar); - const rawBoard: PlanBoardGeom = this.planHydratedKey === hydKey && this.planHydratedBoard + const isHydrated = + Boolean(this.planHydratedBoard) && + this.planHydratedKey.startsWith(`${this.project}:`) && + (this.planHydratedKey === hydKey || (this.planHydratedRev !== undefined && this.planHydratedRev >= (d.revision ?? 0))); + const rawBoard: PlanBoardGeom = isHydrated && this.planHydratedBoard ? this.planHydratedBoard : d.board ?? { bbox: [0, 0, 100, 70], outline: [], parts: [] }; - const rawDraw = this.planHydratedKey === hydKey && this.planHydratedDraw + const rawDraw = isHydrated && this.planHydratedDraw ? this.planHydratedDraw : d.draw ?? { bands: [], regions: [] }; @@ -1460,21 +1487,10 @@ export class MgmtStrip { this.planShownLayers = activeLayers.length >= 2 ? [activeLayers[0], fields.layer] : [...activeLayers, fields.layer]; } } - const wireFields: Record = { ...fields }; - if ( - Array.isArray(fields.outline) && - Array.isArray((fields.outline as unknown[])[0]) && - typeof ((fields.outline as unknown[])[0] as unknown[])[0] === "number" - ) { - const reg = mergedRegions.find((r) => r.id === id); - if (reg?.holes && reg.holes.length > 0) { - wireFields.outline = [fields.outline, ...reg.holes]; - } - } const baseRev = typeof d.revision === "number" ? d.revision : undefined; this.render(); sendPlan("plan.update", { - ops: [{ op: "set", id, fields: wireFields }], + ops: [{ op: "set", id, fields }], ...(baseRev !== undefined ? { base: baseRev } : {}), }); }; @@ -1820,6 +1836,19 @@ export class MgmtStrip { const prev = this.planOptimistic.get(id) ?? {}; this.planOptimistic.set(id, { ...prev, ...fields }); }, + onRevertOptimistic: (id) => { + const had = this.planOptimistic.delete(id); + if (had || this.planRenderDeferred) { + this.planRenderDeferred = false; + this.render(); + } + }, + onDragEnd: () => { + if (this.planRenderDeferred) { + this.planRenderDeferred = false; + this.render(); + } + }, onCommitFields: (id, fields) => { (this.planCommitFields ?? commitItemFields)(id, fields); }, diff --git a/web/src/plan-canvas.ts b/web/src/plan-canvas.ts index 9606c1542b..226a51c474 100644 --- a/web/src/plan-canvas.ts +++ b/web/src/plan-canvas.ts @@ -46,6 +46,8 @@ export interface PlanCanvasCallbacks { onSelect: (id: string) => void; onFocusItem: (id: string) => void; onOptimisticPatch: (id: string, fields: Record) => void; + onRevertOptimistic?: (id: string) => void; + onDragEnd?: () => void; onCommitFields: (id: string, fields: Record) => void; onApproveLayer: (layer: string, approve: boolean) => void; onQuickApprove: (ids: string[], approve: boolean) => void; @@ -186,6 +188,10 @@ export class PlanFloorplannerCanvas { this.root.addEventListener("keydown", (e) => this.onKeyDown(e)); } + public isDragging(): boolean { + return this.drag !== null; + } + public fitAll(): void { this.sharedCam = null; this.layerCams.clear(); @@ -507,20 +513,22 @@ export class PlanFloorplannerCanvas { } }); - const cancelActiveDrag = (restoreOrig: boolean): void => { + const cancelActiveDrag = (): void => { const d = this.drag; if (!d || d.layer !== layer) return; this.drag = null; this.downPos = null; - if (restoreOrig && d.kind === "vertex") { + if (d.kind === "vertex") { const copy = d.origPts.map((p) => [p[0], p[1]] as [number, number]); this.patchLocalItem(d.id, d.isPlane, copy); - this.cb.onOptimisticPatch(d.id, { [d.isPlane ? "outline" : "path"]: copy }); + this.cb.onRevertOptimistic?.(d.id); + } else { + this.cb.onDragEnd?.(); } this.scheduleDraw(); }; - canvas.addEventListener("pointercancel", () => cancelActiveDrag(true)); - canvas.addEventListener("lostpointercapture", () => cancelActiveDrag(false)); + canvas.addEventListener("pointercancel", cancelActiveDrag); + canvas.addEventListener("lostpointercapture", cancelActiveDrag); canvas.addEventListener("pointerup", (e) => { const s = this.state; @@ -535,6 +543,7 @@ export class PlanFloorplannerCanvas { if (d.moved) { this.cb.onCommitFields(d.id, { [d.isPlane ? "outline" : "path"]: d.pts }); } else { + this.cb.onDragEnd?.(); this.scheduleDraw(); } return; @@ -550,10 +559,14 @@ export class PlanFloorplannerCanvas { if (hit && (hit.kind === "band" || hit.kind === "region")) { this.cb.onSelect(hit.id); this.cb.onFocusItem(hit.id); - } else if (!hit) { + return; + } + if (!hit && s.selectedId) { this.cb.onSelect(""); + return; } } + this.cb.onDragEnd?.(); }); canvas.addEventListener( diff --git a/web/test/mgmt.test.ts b/web/test/mgmt.test.ts index f67f919e95..309fb5744d 100644 --- a/web/test/mgmt.test.ts +++ b/web/test/mgmt.test.ts @@ -32,6 +32,7 @@ import { planLayoutLabels, planAllCanvasLayers, unwrapPlanGetPanel, + isPlanHydrationCurrent, } from "../src/mgmt-model"; describe("Management strip pure model", () => { @@ -230,5 +231,11 @@ describe("Management strip pure model", () => { ); expect(mergedAll.map((l) => l.layer)).toEqual(["F.Cu", "In1.Cu"]); expect(mergedAll[1].title).toBe("L2 · GND"); + + expect(isPlanHydrationCurrent(1, 1, 2, 2, "/p/a", "/p/a", 4, undefined)).toBe(true); + expect(isPlanHydrationCurrent(1, 2, 2, 2, "/p/a", "/p/a", 4, undefined)).toBe(false); + expect(isPlanHydrationCurrent(1, 1, 1, 2, "/p/a", "/p/a", 4, undefined)).toBe(false); + expect(isPlanHydrationCurrent(1, 1, 2, 2, "/p/a", "/p/b", 4, undefined)).toBe(false); + expect(isPlanHydrationCurrent(1, 1, 2, 2, "/p/a", "/p/a", 3, 5)).toBe(false); }); }); From 442ab5158b4cd682be2e38d4b2ef623b21b133c5 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 22:39:39 -0500 Subject: [PATCH 5/5] plan: finalize drag isolation, hydration key preservation, hard budget cap, and sequential hole merging --- native/gpui/src/screens/mgmt_plan_canvas.rs | 31 ++++++--- native/host/src/plan/geom.rs | 33 +++++++++- native/host/src/plan/mod.rs | 70 ++++++++++++++++----- native/host/src/plan/panel.rs | 29 ++++++++- web/dist/assets/app.js | 26 ++++---- web/dist/manifest.json | 12 ++-- web/src/mgmt.ts | 11 ---- web/src/plan-canvas.ts | 10 +-- 8 files changed, 154 insertions(+), 68 deletions(-) diff --git a/native/gpui/src/screens/mgmt_plan_canvas.rs b/native/gpui/src/screens/mgmt_plan_canvas.rs index b68b923822..15f337ceb1 100644 --- a/native/gpui/src/screens/mgmt_plan_canvas.rs +++ b/native/gpui/src/screens/mgmt_plan_canvas.rs @@ -741,24 +741,28 @@ pub fn accept_hydration_reply(req_tag: Option, reply_tag: u64, cur_pro: &st Some((rev, panel["board"].clone(), panel["draw"].clone())) } -pub fn board_answered(app: &mut Backplane, tag: u64, reply: &Value, cx: &mut Context) { - let pro = app.screens.mgmt.project.clone(); - let Some((rev, board, draw)) = accept_hydration_reply(app.screens.mgmt.plan_ui.hydrated_req_tag, tag, &pro, reply) else { - return; - }; - let ui = &mut app.screens.mgmt.plan_ui; +pub fn record_hydrated_panel(ui: &mut State, pro: &str, rev: u64, board: Value, draw: Value) -> bool { if !ui.hydrated_req_pro.is_empty() && ui.hydrated_req_pro != pro { - return; + return false; } if ui.hydrated_rev.map_or(false, |prev| rev < prev) { - return; + return false; } ui.hydrated_rev = Some(rev); ui.hydrated_key = format!("{pro}:{rev}"); - ui.hydrated_req_key = ui.hydrated_key.clone(); ui.hydrated_board = Some(board); ui.hydrated_draw = Some(draw); - cx.notify(); + true +} + +pub fn board_answered(app: &mut Backplane, tag: u64, reply: &Value, cx: &mut Context) { + let pro = app.screens.mgmt.project.clone(); + let Some((rev, board, draw)) = accept_hydration_reply(app.screens.mgmt.plan_ui.hydrated_req_tag, tag, &pro, reply) else { + return; + }; + if record_hydrated_panel(&mut app.screens.mgmt.plan_ui, &pro, rev, board, draw) { + cx.notify(); + } } pub fn sync_revision_and_hydrate(app: &mut Backplane, d: &Value) { @@ -2053,6 +2057,13 @@ mod tests { assert!(accept_hydration_reply(Some(BOARD_TAG_BASE + 1), BOARD_TAG_BASE, "/p/a.kicad_pro", &wrapped).is_none(), "stale tag rejected"); assert!(accept_hydration_reply(Some(BOARD_TAG_BASE), BOARD_TAG_BASE, "/p/b.kicad_pro", &wrapped).is_none(), "wrong project rejected"); assert_eq!(accept_hydration_reply(Some(BOARD_TAG_BASE), BOARD_TAG_BASE, "/p/a.kicad_pro", &wrapped).unwrap().0, 4); + + let mut st = State::default(); + st.hydrated_req_pro = "/p/a.kicad_pro".into(); + st.hydrated_req_key = "/p/a.kicad_pro:10".into(); + assert!(record_hydrated_panel(&mut st, "/p/a.kicad_pro", 9, json!({}), json!({}))); + assert_eq!(st.hydrated_req_key, "/p/a.kicad_pro:10", "older reply must not downgrade requested key"); + assert!(!record_hydrated_panel(&mut st, "/p/a.kicad_pro", 8, json!({}), json!({}))); let direct = json!({"panel": {"revision": 9}}); assert_eq!(unwrap_board_panel(&direct).unwrap()["revision"], 9); diff --git a/native/host/src/plan/geom.rs b/native/host/src/plan/geom.rs index a157c12453..59c6d68110 100644 --- a/native/host/src/plan/geom.rs +++ b/native/host/src/plan/geom.rs @@ -775,8 +775,24 @@ pub fn guides_for_plan(board: &CachedBoard, plan: &Value) -> HashMap = to_refs.iter().copied().collect(); f_sorted.sort_unstable(); t_sorted.sort_unstable(); - let f_pts: Vec<[f64; 2]> = f_sorted.into_iter().filter_map(|r| part_center.get(r).copied()).take(MAX_CORRIDOR_GUIDES).collect(); - let t_pts: Vec<[f64; 2]> = t_sorted.into_iter().filter_map(|r| part_center.get(r).copied()).take(MAX_CORRIDOR_GUIDES).collect(); + let mut f_pts: Vec<[f64; 2]> = Vec::new(); + for r in f_sorted { + if let Some(pt) = part_center.get(r).copied() { + if !f_pts.iter().any(|p| (p[0] - pt[0]).hypot(p[1] - pt[1]) <= 0.5) { + f_pts.push(pt); + if f_pts.len() >= MAX_CORRIDOR_GUIDES { break; } + } + } + } + let mut t_pts: Vec<[f64; 2]> = Vec::new(); + for r in t_sorted { + if let Some(pt) = part_center.get(r).copied() { + if !t_pts.iter().any(|p| (p[0] - pt[0]).hypot(p[1] - pt[1]) <= 0.5) { + t_pts.push(pt); + if t_pts.len() >= MAX_CORRIDOR_GUIDES { break; } + } + } + } let mut checks = 0usize; 'fallback: for a in &f_pts { for b in &t_pts { @@ -945,5 +961,18 @@ mod tests { let p_missing = json!({"corridors": [{"id": "cmiss", "from": (0..50).map(|i| format!("M{i}")).collect::>(), "to": (0..50).map(|i| format!("N{i}")).collect::>()}]}); assert!(guides_for_plan(&dummy, &p_missing).is_empty()); + + let mut colo_parts: Vec = (0..25).map(|i| PartBox { r: format!("C{i:02}"), s: "F".into(), b: [20.0, 20.0, 22.0, 22.0], o: false }).collect(); + colo_parts.push(PartBox { r: "Z_DISTINCT".into(), s: "F".into(), b: [50.0, 50.0, 52.0, 52.0], o: false }); + colo_parts.push(PartBox { r: "C_TO".into(), s: "F".into(), b: [20.0, 20.0, 22.0, 22.0], o: false }); + let colo_board = CachedBoard { + geom: BoardGeom { bbox: [0.0, 0.0, 100.0, 100.0], outline: vec![], parts: colo_parts, copper_layers: vec![] }, + pad_nets: HashMap::new(), + }; + let mut from_list: Vec = (0..25).map(|i| format!("C{i:02}")).collect(); + from_list.push("Z_DISTINCT".into()); + let p_colo = json!({"corridors": [{"id": "cc", "from": from_list, "to": ["C_TO"]}]}); + let g_colo = guides_for_plan(&colo_board, &p_colo); + assert_eq!(g_colo["cc"], vec![[51.0, 51.0, 21.0, 21.0]]); } } diff --git a/native/host/src/plan/mod.rs b/native/host/src/plan/mod.rs index 9e364de618..28e3fb7396 100644 --- a/native/host/src/plan/mod.rs +++ b/native/host/src/plan/mod.rs @@ -614,29 +614,57 @@ fn update_saved_plan_sync(pcb: &str, base: Option, ops: &[NormOp]) -> Resul } fn merge_preserved_holes_into_ops(plan: &Value, ops: &[NormOp]) -> Vec { - let planes = plan["planes"].as_array(); - ops.iter().map(|nop| { - if !nop.preserve_holes { - return nop.wire.clone(); + let mut plane_rings: HashMap> = HashMap::new(); + for p in plan["planes"].as_array().into_iter().flatten() { + if let Some(id) = p["id"].as_str() { + if let Ok(Value::Array(rs)) = norm_outline(&p["outline"]) { + plane_rings.insert(id.to_string(), rs); + } } - let mut wire = nop.wire.clone(); - let id = wire["id"].as_str().unwrap_or(""); - let new_len = wire["fields"]["outline"].as_array().map_or(0, Vec::len); - if new_len == 1 { - if let Some(old_raw) = planes.and_then(|ps| ps.iter().find(|p| p["id"] == id)).and_then(|p| p.get("outline")) { - if let Ok(Value::Array(old_rings)) = norm_outline(old_raw) { - if old_rings.len() > 1 { - let mut merged = Vec::with_capacity(old_rings.len()); - merged.push(wire["fields"]["outline"][0].clone()); - merged.extend(old_rings[1..].iter().cloned()); - if let Some(flds) = wire["fields"].as_object_mut() { - flds.insert("outline".into(), Value::Array(merged)); + } + ops.iter().map(|nop| { + let kind = nop.wire["op"].as_str().unwrap_or(""); + match kind { + "add" if nop.wire["kind"] == "plane" => { + if let Some(id) = nop.wire["item"]["id"].as_str() { + if let Ok(Value::Array(rs)) = norm_outline(&nop.wire["item"]["outline"]) { + plane_rings.insert(id.to_string(), rs); + } + } + nop.wire.clone() + } + "delete" => { + if let Some(id) = nop.wire["id"].as_str() { + plane_rings.remove(id); + } + nop.wire.clone() + } + "set" => { + let id = nop.wire["id"].as_str().unwrap_or(""); + if nop.wire["fields"].get("outline").is_none() { + return nop.wire.clone(); + } + let mut wire = nop.wire.clone(); + let new_rings = wire["fields"]["outline"].as_array().cloned().unwrap_or_default(); + if nop.preserve_holes && new_rings.len() == 1 { + if let Some(old_rings) = plane_rings.get(id) { + if old_rings.len() > 1 { + let mut merged = Vec::with_capacity(old_rings.len()); + merged.push(new_rings[0].clone()); + merged.extend(old_rings[1..].iter().cloned()); + plane_rings.insert(id.to_string(), merged.clone()); + if let Some(flds) = wire["fields"].as_object_mut() { + flds.insert("outline".into(), Value::Array(merged)); + } + return wire; } } } + plane_rings.insert(id.to_string(), new_rings); + wire } + _ => nop.wire.clone(), } - wire }).collect() } @@ -996,5 +1024,13 @@ mod tests { let clear = normalize_person_ops_checked(&[json!({"op": "set", "id": "p1", "outline": [[[0.0, 0.0], [12.0, 0.0], [12.0, 10.0]]]})]).unwrap(); let cleared = merge_preserved_holes_into_ops(&live_plan, &clear); assert_eq!(cleared[0]["fields"]["outline"].as_array().unwrap().len(), 1); + + let batch = normalize_person_ops_checked(&[ + json!({"op": "set", "id": "p1", "outline": [[[0.0, 0.0], [12.0, 0.0], [12.0, 10.0]]]}), + json!({"op": "set", "id": "p1", "outline": [[0.0, 0.0], [14.0, 0.0], [14.0, 10.0]]}), + ]).unwrap(); + let batch_out = merge_preserved_holes_into_ops(&live_plan, &batch); + assert_eq!(batch_out[0]["fields"]["outline"].as_array().unwrap().len(), 1); + assert_eq!(batch_out[1]["fields"]["outline"].as_array().unwrap().len(), 1, "subsequent flat move must keep holes cleared"); } } diff --git a/native/host/src/plan/panel.rs b/native/host/src/plan/panel.rs index 2936b69b3b..8c64ddd6d9 100644 --- a/native/host/src/plan/panel.rs +++ b/native/host/src/plan/panel.rs @@ -126,8 +126,9 @@ pub fn data_with_board(plan: &Value, asks: &[Value], live: bool, pcb: Option<&st } else { json!(ls.iter().map(|l| json!({"layer": l["layer"], "index": l["index"], "role": l["role"], "title": l["title"], "subtitle": l["subtitle"]})).collect::>()) }; + let rev = plan["revision"].as_u64().map_or(Value::Null, |n| json!(n)); json!({"draw": draw, "board": board, "copper_layers": copper_layers, "notes": plan["notes"], "constraints": plan["constraints"], - "badge": {"n": awaiting + blocked, "tone": if blocked > 0 { "bad" } else if awaiting > 0 { "warn" } else { "" }}, "revision": plan["revision"], "live": live, + "badge": {"n": awaiting + blocked, "tone": if blocked > 0 { "bad" } else if awaiting > 0 { "warn" } else { "" }}, "revision": rev, "live": live, "total": total, "awaiting": awaiting, "approved": approved, "blocked": blocked, "routing": routing, "done": done, "routed": routed, "verified": verified, "rejected": rejected, "status": status, "stackup_summary": stackup_summary, "impedances": impedances, "asks": asks, "layers": ls, "empty": rows.is_empty()}) } @@ -286,6 +287,27 @@ pub fn fit_info_budget(d: &mut Value) { } } } + if d.to_string().len() > BUDGET { + let badge_n = d["badge"]["n"].as_u64().unwrap_or(0); + let badge_tone = d["badge"]["tone"].as_str().filter(|s| s.len() <= 16).unwrap_or(""); + let rev = d["revision"].as_u64().map_or(Value::Null, |n| json!(n)); + let live = d["live"] == true; + let empty = d["empty"] == true; + let on = d["on"] == true; + let status = d["status"].as_str().filter(|s| s.len() <= 32).unwrap_or("empty"); + *d = json!({ + "badge": {"n": badge_n, "tone": badge_tone}, + "on": on, + "empty": empty, + "live": live, + "revision": rev, + "status": status, + "board_trimmed": true, + "board": {"bbox": [0, 0, 100, 70], "outline": [], "parts": []}, + "draw": {"bands": [], "regions": []}, + "layers": [] + }); + } } /// The board of a project's .kicad_pro. @@ -492,5 +514,10 @@ mod tests { fit_info_budget(&mut huge_d); assert!(huge_d.to_string().len() <= 58 * 1024); assert_eq!(huge_d["board_trimmed"], true); + + let mut crazy_rev = json!({"revision": "x".repeat(100_000), "badge": {"n": 1, "tone": "warn"}, "layers": []}); + fit_info_budget(&mut crazy_rev); + assert!(crazy_rev.to_string().len() <= 58 * 1024); + assert_eq!(crazy_rev["board_trimmed"], true); } } diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index aac07d28b5..129665b5ce 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,14 +1,14 @@ -function Gt(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function Ln(e){return e==="done"||e==="failed"||e==="cancelled"}function An(e,t){if(!e||e.id!==t.id)return!0;let n=Ln(e.state),i=Ln(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Pn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Nn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ht=ns(),Ot=new Set,Ut=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function ns(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Mn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ht}Mn();function At(e){return Ot.add(e),()=>{Ot.delete(e)}}function Tn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ht;if(ht=n,Mn(),i)for(let s of Ot)s(ht);return i}function u(e,t,n){let s=(mt[ht]||mt.en||{})[e]??mt.en?.[e]??t??e;return Nn(s,n)}function xe(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return u(t,e)}function Q(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function $e(e,t="",n){let i=Q("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function is(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ss(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Vt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=Q("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=Q("div","bp-fb-head");this.upBtn=$e("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=u("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",u("web.clone.up","Up")),this.pathInput=Q("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=Q("div","bp-fb-list"),this.errEl=Q("div","bp-ap-err bp-hidden");let a=Q("div","bp-ap-foot");this.actBtn=$e("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(Q("div","bp-fb-empty",u("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(xe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=u("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(Q("div","bp-fb-empty",u("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=$e("","bp-fb-row",()=>{this.go(ss(this.path,n))});i.append(Q("span","bp-fb-icon","▸"),Q("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(is(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(xe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Wt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=Q("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=Q("div","bp-modal bp-ap"),n=Q("div","bp-modal-head"),i=Q("h2","",u("sidebar.add.project","Add project")),s=$e("×","icon",()=>this.close());s.title=u("common.close","Close"),s.setAttribute("aria-label",u("common.close","Close")),n.append(i,s),this.tabsEl=Q("div","bp-ap-tabs"),this.bodyEl=Q("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=u("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=$e(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",u("gpui.e.open.folder","Open folder")),e("clone",u("web.clone.tab","Clone from git")))}renderFolder(){let e=new Vt(this.host.hub,(t)=>u("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=Q("div","bp-ap-form"),n=Q("div","bp-ap-repo"),i=Q("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=u("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",u("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=Q("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=Q("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=Q("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=Q("label","bp-ap-check"),a=Q("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,Q("span","",u("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(Q("div","bp-ap-first bp-dim",u("web.clone.first","First message: {text}",{text:this.firstText})));let o=Q("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=Q("div","bp-ap-foot");this.cloneBtn=$e(u("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=$e("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=Q("div","bp-ap-sug-top");if(o.append(Q("span","bp-ap-sug-name",s.name)),s.private)o.append(Q("span","bp-ap-tag",u("web.clone.private","private")));if(r.append(o),s.description)r.append(Q("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(Q("div","bp-ap-sug-note",u("web.clone.loading","Loading…")));else if(t.hint){let s=Q("div","bp-ap-sug-note");if(s.append(Q("span","",xe(t.hint))),t.state==="signedout"){let a=$e(u("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(xe(t.error)))}else if(t){let r=Q("div","bp-ap-where"),o=Q("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=$e(u("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let m=Q("label","bp-ap-name");m.append(Q("span","bp-ap-lbl",u("web.clone.folder.name","Folder name")));let c=Q("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),m.append(c),n.push(m),!t.ok&&t.error)n.push(this.errLine(xe(t.error)));else if(t.same)n.push(Q("div","bp-ap-note bp-dim",u("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=Q("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=$e(u("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Vt(this.host.hub,(i)=>u("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Gt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=xe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Gt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=xe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Pn(e))this.goTo(e)}renderJobView(){this.jobEl=Q("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=Q("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?u("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?u("web.clone.stopped","Stopped cloning {repo}",{repo:i}):u("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[Q("div","bp-ap-job-title",s)];if(t.state==="running"){let r=Q("div","bp-ap-phase",xe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=Q("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=Q("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(Q("div","bp-ap-detail bp-dim",t.detail));let m=Q("div","bp-ap-foot"),c=$e(u("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),m.append(c),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=Q("div","bp-ap-err",xe(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=Q("div","bp-ap-foot"),o=$e(u("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=$e(u("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let l=$e(u("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=Q("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let h of r)c.appendChild(Q("li","",xe(h)));a.push(c)}let o=Q("div","bp-ap-foot"),l=t.thread?u("web.clone.open.thread","Open the thread"):u("web.clone.open.project","Open the project"),m=$e(l,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=Q("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(Q("div","bp-dim",u("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(Q("div","",u("web.clone.signin.enter","Enter this code on GitHub:")));let i=Q("div","bp-ap-code-row"),s=Q("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=$e(this.copied?u("web.clone.copied","Copied"):u("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=Q("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(Q("div","bp-ok",u("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(Q("div","bp-ap-err",xe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function as(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ut(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=as(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i=(e.ended??0)}function Pn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.move":"Move to layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup":"Stackup & impedances","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.move":"Mover a capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup":"Apilado e impedancias","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.move":"レイヤー移動","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup":"スタックアップとインピーダンス","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Nn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ut=ns(),Ut=new Set,Vt=new Map;for(let[e,t]of Object.entries(mt.en||{}))if(typeof t==="string"&&!Vt.has(t))Vt.set(t,e);function ns(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Mn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ut}Mn();function At(e){return Ut.add(e),()=>{Ut.delete(e)}}function Tn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ut;if(ut=n,Mn(),i)for(let s of Ut)s(ut);return i}function h(e,t,n){let s=(mt[ut]||mt.en||{})[e]??mt.en?.[e]??t??e;return Nn(s,n)}function xe(e){if(!e)return"";let t=Vt.get(e);if(!t)return e;return h(t,e)}function Q(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function $e(e,t="",n){let i=Q("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function is(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ss(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Ot{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=Q("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=Q("div","bp-fb-head");this.upBtn=$e("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=Q("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=Q("div","bp-fb-list"),this.errEl=Q("div","bp-ap-err bp-hidden");let a=Q("div","bp-ap-foot");this.actBtn=$e("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(Q("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(xe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(Q("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=$e("","bp-fb-row",()=>{this.go(ss(this.path,n))});i.append(Q("span","bp-fb-icon","▸"),Q("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(is(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(xe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Wt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=Q("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=Q("div","bp-modal bp-ap"),n=Q("div","bp-modal-head"),i=Q("h2","",h("sidebar.add.project","Add project")),s=$e("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=Q("div","bp-ap-tabs"),this.bodyEl=Q("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=$e(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new Ot(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=Q("div","bp-ap-form"),n=Q("div","bp-ap-repo"),i=Q("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(m)=>this.repoKey(m)),this.repoInput=i,this.suggestEl=Q("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=Q("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=Q("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=Q("label","bp-ap-check"),a=Q("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,Q("span","",h("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(Q("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=Q("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let l=Q("div","bp-ap-foot");this.cloneBtn=$e(h("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),l.append(this.cloneBtn),r.push(o,l),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=$e("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(l)=>l.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=Q("div","bp-ap-sug-top");if(o.append(Q("span","bp-ap-sug-name",s.name)),s.private)o.append(Q("span","bp-ap-tag",h("web.clone.private","private")));if(r.append(o),s.description)r.append(Q("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(Q("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=Q("div","bp-ap-sug-note");if(s.append(Q("span","",xe(t.hint))),t.state==="signedout"){let a=$e(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(xe(t.error)))}else if(t){let r=Q("div","bp-ap-where"),o=Q("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let l=$e(h("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});l.setAttribute("data-testid","clone-change-folder"),r.append(o,l),n.push(r);let m=Q("label","bp-ap-name");m.append(Q("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let c=Q("input","bp-input");if(c.type="text",c.spellcheck=!1,c.value=this.nameText,c.setAttribute("data-testid","clone-name"),c.addEventListener("input",()=>{this.nameText=c.value,this.nameTouched=c.value.trim()!=="",this.startErr="",this.askDest(250)}),c.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),m.append(c),n.push(m),!t.ok&&t.error)n.push(this.errLine(xe(t.error)));else if(t.same)n.push(Q("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=Q("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=$e(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Ot(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Gt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=xe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Gt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=xe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!An(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Pn(e))this.goTo(e)}renderJobView(){this.jobEl=Q("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=Q("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[Q("div","bp-ap-job-title",s)];if(t.state==="running"){let r=Q("div","bp-ap-phase",xe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=Q("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),l=Q("div","bp-ap-bar-fill");if(typeof t.pct==="number")l.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(l),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(Q("div","bp-ap-detail bp-dim",t.detail));let m=Q("div","bp-ap-foot"),c=$e(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});c.setAttribute("data-testid","clone-cancel"),m.append(c),a.push(m)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let m=Q("div","bp-ap-err",xe(t.error));m.setAttribute("data-testid","clone-error"),a.push(m)}let r=Q("div","bp-ap-foot"),o=$e(h("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let m=$e(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});m.setAttribute("data-testid","clone-signin-btn"),r.append(m)}let l=$e(h("web.clone.retry","Try again"),"primary",()=>{this.retry(t,l)});l.setAttribute("data-testid","clone-retry"),r.append(l),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let c=Q("ul","bp-ap-notes");c.setAttribute("data-testid","clone-notes");for(let u of r)c.appendChild(Q("li","",xe(u)));a.push(c)}let o=Q("div","bp-ap-foot"),l=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),m=$e(l,"primary",()=>this.goTo(t));m.setAttribute("data-testid","clone-open"),o.append(m),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=Q("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(Q("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(Q("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=Q("div","bp-ap-code-row"),s=Q("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=$e(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=Q("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(Q("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(Q("div","bp-ap-err",xe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function as(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function ht(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=as(s[3]??"");if(o){let l=document.createElement("a");l.href=o,l.target="_blank",l.rel="noopener noreferrer",l.textContent=r,e.appendChild(l)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(c).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),p.append(d,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=c,f.appendChild(g),h.append(p,f),t.appendChild(h);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",ut(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ut(l,m.join(` -`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));ut(o,r[l])}t.appendChild(o)}return t}var Bn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qt(e){return e<10000000000?e*1000:e}function rs(e){if(!e)return"";return new Date(qt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function os(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function _t(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Kt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=u("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=u("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=u("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=u("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!_t(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!_t(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(_t(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||u("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=u("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=u("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let h=rs(e.at);if(t)c.textContent=h,i.append(s,...m?[o]:[],c);else{let p=n&&e.at?os(qt(e.at)-qt(n)):"",d=h?p?u("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:p}):u("web.chat.finished","Finished {time}",{time:h}):"";c.textContent=e.live?u("web.chat.streaming","Streaming…"):d,i.append(c,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=u("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=u("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let h=document.createElement("span");if(h.className="bp-tool-name",h.textContent=a.tool.name,c.appendChild(h),a.tool.summary){let p=document.createElement("span");p.className="bp-tool-summary",p.textContent=a.tool.summary,c.appendChild(p)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let h=document.createElement("div");h.className="bp-ask-card",h.setAttribute("data-testid",`ask-${c.id}`);let p=document.createElement("div");if(p.className="bp-ask-q",p.textContent=c.question,h.appendChild(p),c.state==="open"){let d=document.createElement("div");if(d.className="bp-ask-opts",c.options&&c.options.length>0)for(let b of c.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,b.id)),d.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=u("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=u("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(c.id,b.value.trim())}),d.append(b,y)}h.appendChild(d)}else{let d=document.createElement("div");d.className="bp-ask-answered",d.textContent=u("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),h.appendChild(d)}r.appendChild(h),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!m&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=u("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let h=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let p=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(h);else this.goTo(h)};c.addEventListener("click",p),c.addEventListener("keydown",(d)=>{if(d.key==="Enter"||d.key===" ")d.preventDefault(),p()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.textContent=a.text;else c.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(m&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let h of a.attachments)if(h.previewUrl){let p=document.createElement("img");p.className="bp-reply-img",p.src=h.previewUrl,p.alt=h.name||"attachment",c.appendChild(p)}else if(h.path||h.name){let p=document.createElement("span");p.className="bp-tool-pill",p.textContent=h.name||h.path||"image",c.appendChild(p)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let h of a.images){let p=document.createElement("img");p.className="bp-reply-img",p.alt=h;let d=`${a.id}|${h}`,b=this.imageCache.get(d);if(b)p.src=b;else this.cb.onLoadImage(a.id,h).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(d,f),p.src=f});c.appendChild(p)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?u("ask.plan","Proposed plan"):xe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=u("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let h=u("common.copy","Copy"),p=document.createElement("span");p.textContent=h,c.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),p),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),p.textContent=u("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),p.textContent=h},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?u("gpui.c.term.collapse","Collapse"):u("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let h=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),p=document.createElement("button");if(p.type="button",p.className="primary",p.setAttribute("data-testid","plan-implement"),p.textContent=h?.label&&h.label!=="Implement"?xe(h.label):u("approval.implement","Implement"),p.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"implement")}),c.appendChild(p),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(u("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(y)}let d=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=d?.label&&d.label!=="Dismiss"?xe(d.label):u("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,d?.id??"dismiss")}),c.appendChild(b),i.appendChild(c),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=u("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=u("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let E=()=>{let A=f.value.trim();if(!A)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${A}`)},x=()=>{this.closePlanRevise()};y.addEventListener("keydown",(A)=>{if(A.key==="Escape")A.preventDefault(),A.stopPropagation(),x()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(A)=>{if(A.key==="Enter"&&!A.shiftKey)A.preventDefault(),E()}),g.addEventListener("click",E);let k=document.createElement("button");k.type="button",k.className="bp-btn-ghost",k.textContent=u("common.cancel","Cancel"),k.addEventListener("click",x),y.append(f,g,k),i.appendChild(y)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=u("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var In="http://www.w3.org/2000/svg",Rn=4,jn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(In,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(In,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function zt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Hn(){return Pt(["M6 4l14 8-14 8z"])}function ls(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Jt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=u("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=u("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=u("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",u("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=u("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",u("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=u("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=u("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let m=l.clipboardData?.items;if(!m)return;let c=[];for(let h=0;h0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=ls(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=u("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${u("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?Hn():zt()),this.planChipLbl.textContent=s?u("gpui.planmode.chip.building","Building"):t==="pending"?u("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?u("gpui.planmode.chip.once","Plan · 1t"):u("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?u("gpui.mgmt.plan.tab","Plan"):u("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?Hn():zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?u("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?u("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?u("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?u("gpui.planmode.bar.pending","Proposed plan awaits review below"):u("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let c=(h,p,d,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(p?" active":""),y.textContent=h,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(d)),y};m.append(c(u("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(u("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(u("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(m)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=u("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=u("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} -${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=u("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=u("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",u("web.composer.attach","Attach image")),this.voiceBtn.title=u("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",u("web.composer.voice","Voice dictation")),this.sendBtn.textContent=u("composer.send","Send"),this.stopBtn.textContent=u("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!jn.has(t.type)){this.showError(u("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Rn){this.showError(u("web.composer.maximages","At most {max} images per message.",{max:Rn}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=u("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Dn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var cs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&cs.has(t.id))}function On(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var ds=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ps=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Un(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(ds.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ps.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function Vn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Wn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function _n(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Yt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function qn(e){return e.state==="routed"||e.state==="verified"}function Kn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function zn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Jn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Yn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Xn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Xt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Zn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Zt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Fn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],$n=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Qn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Fn[Qn(i)%Fn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return $n[Qn(e)%$n.length]}function ei(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function Je(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ti(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ni(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[m,c]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function ii(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function si(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Qt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ms(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+m*r,h=i+m*o;return(e-c)*(e-c)+(t-h)*(t-h)}function Gn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(l-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function en(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,l){if(i){for(let p of e){if(p.layer!==n||p.id!==i||p.locked)continue;let d=p.path??[];for(let b=0;b=3)for(let b=0;b=0;p--){let d=t[p];if(d.layer!==n)continue;let b=d.outline??[];if(!Gn(c,h,b))continue;if(!(d.holes??[]).some((f)=>Gn(c,h,f)))return{kind:"region",id:d.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,l=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function ai(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[c,h]=Je(t,m.b[0],m.b[1],n,i),[p,d]=Je(t,m.b[2],m.b[3],n,i),b=Math.abs(p-c),y=Math.abs(d-h);if(b<13||y<9)continue;let f=(c+p)*0.5,g=(h+d)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,c)=>c.score-m.score);let o=[],l=[];for(let m of r){let c=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((p)=>!(c[2]<=p[0]||c[0]>=p[2]||c[3]<=p[1]||c[1]>=p[3])))o.push(c),l.push({text:m.text,cx:m.cx,cy:m.cy})}return l}function ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Rt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}function oi(e,t,n,i,s,a,r,o){return e===t&&n===i&&s===a&&(o===void 0||r>=o)}var li="#111917",hs="#16201d",us="rgba(212, 224, 219, 0.92)",bs="rgba(61, 80, 73, 0.72)",gs="rgba(82, 107, 97, 0.85)",fs="rgba(143, 163, 155, 0.88)",ci="#f59e0b",vs="#eef5f2",di="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function ys(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function ws(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function Es(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class tn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Rt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??rt(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):rt(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ei(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=u("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=u("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,m);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let h=document.createElement("div");h.className="bp-plan-card-canvas-wrap";let p=document.createElement("canvas");p.className="bp-plan-card-canvas",p.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let d=document.createElement("div");d.className="bp-plan-hover-hud bp-hidden",h.append(p,d);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,h,b);let y=p.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(h),this.attachPointerListeners(p,e.layer);let g={layer:e.layer,el:t,canvas:p,ctx:y,legendEl:b,okBtn:l,noBtn:m,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:d,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=Es(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=u(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let l=document.createElement("button");l.type="button";let m=this.state?.selectedId===o.id;l.className="bp-plan-legend-chip"+(m?" active":"");let c=document.createElement("span");c.className="bp-plan-legend-sw",c.style.background=ft(o.net||o.id,o.color||"");let h=document.createElement("span");h.textContent=o.net||o.id,l.append(c,h),l.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(l)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height),c=this.getCam(t,l,m),h=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o);if(i.button===2){if(h?.kind==="vertex"){let p=this.getItemPts(h.id,h.isPlane),d=Qt(p,h.idx,h.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(h.id,{[h.isPlane?"outline":"path"]:d})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},h?.kind==="vertex"){let p=this.getItemPts(h.id,h.isPlane),d=p.map((b)=>[b[0],b[1]]);this.selectedVertex={id:h.id,idx:h.idx},this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:h.idx,pts:p.map((b)=>[b[0],b[1]]),origPts:d,moved:!1},this.scheduleDraw()}else if(h?.kind==="midpoint"){let p=this.getItemPts(h.id,h.isPlane),d=p.map((f)=>[f[0],f[1]]),b=si(p,h.segIdx,h.pos,h.isPlane),y=h.isPlane&&h.segIdx+1>=p.length?b.length-1:Math.min(h.segIdx+1,b.length-1);this.selectedVertex={id:h.id,idx:y},this.patchLocalItem(h.id,h.isPlane,b),this.cb.onOptimisticPatch(h.id,{[h.isPlane?"outline":"path"]:b}),this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:y,pts:b,origPts:d,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let k=this.getCam(t,l,m);this.setCam(t,ti(k,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let y=this.getCam(t,l,m),[f,g]=Bt(y,r,o,l,m),E=[Math.round(f*1000)/1000,Math.round(g*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let x=this.drag.pts.map((k)=>[k[0],k[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.cb.onOptimisticPatch(this.drag.id,{[this.drag.isPlane?"outline":"path"]:x}),this.scheduleDraw();return}let c=this.getCam(t,l,m),h=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o),p=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=this.hover?.hit.kind??"",b=h?h.id:"";if(this.hover=h?{layer:t,hit:h}:null,e.style.cursor=h?"pointer":"crosshair",p!==b||(h?.kind??"")!==d)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"){let s=i.origPts.map((a)=>[a[0],a[1]]);this.patchLocalItem(i.id,i.isPlane,s),this.cb.onRevertOptimistic?.(i.id)}else this.cb.onDragEnd?.();this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,m=i.clientY-o.top,c=Math.max(1,o.width),h=Math.max(1,o.height),p=this.getCam(t,c,h),d=It(s.bands,s.regions,t,s.selectedId,p,c,h,l,m);if(d&&(d.kind==="band"||d.kind==="region")){this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);return}if(!d&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),m=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ni(m,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=Qt(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(d,b)=>Je(a,d,b,n,i);e.fillStyle=li,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((d)=>d.length>=3);if(e.fillStyle=hs,o.length>0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let d of l){let b=d.outline??[];if(b.length<3)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ws(d.state||"proposed",y,f),E=ft(d.net||d.id,d.color||"");e.beginPath();for(let x=0;x0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),p=[];for(let d of h){for(let b of d.from??[])p.push(b);for(let b of d.to??[])p.push(b)}e.fillStyle=fs,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let d of ai(c,a,n,i,p))e.fillText(d.text,d.cx,d.cy);for(let d of h){let b=d.guides??[];if(b.length===0)continue;let y=s.selectedId===d.id||m?.id===d.id,f=vt(d.name||d.id,d.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[E,x]=r(g[0],g[1]),[k,A]=r(g[2],g[3]);e.moveTo(E,x),e.lineTo(k,A)}e.stroke()}for(let d of h){let b=d.path??[];if(b.length<2)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ys(d.state||"proposed",y,f),E=vt(d.name||d.id,d.color||""),x=en(d.width??1.5,a.scale),k=()=>{e.beginPath();for(let N=0;N0){let N=ii(b);if(N){let[M,D]=r(N[0],N[1]),W=String(A),_=Math.max(16,W.length*6.5+8),H=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(M-_*0.5,D-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":E,e.strokeRect(M-_*0.5,D-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,M,D+0.5)}}}if(s.selectedId){let d=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let m=document.createElement("span");m.textContent=xe(r.label),o.appendChild(m);let c=this.getPanelData(r.id),h=On(c);if(h){let p=document.createElement("span");p.className=`bp-mgmt-badge bp-tone-${h.tone}`,p.textContent=h.text,o.appendChild(p)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=u("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",u("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),a=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,a.appendChild(r)}switch(this.openPanel){case"bom":a.appendChild(this.renderBom());break;case"checks":a.appendChild(this.renderChecks());break;case"life":a.appendChild(this.renderLife());break;case"plan":a.appendChild(this.renderPlan());break;case"fab":a.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(a),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=xe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),m.appendChild(c),e.appendChild(m)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=Wn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),l.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=u("gpui.mgmt.bom.dnp","DNP"),l.appendChild(y)}else{let y=Vn(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,l.appendChild(f)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let p=[`${a.qty??r.length}×`,a.value??"",Un(a.footprint??"")].filter(Boolean).join(" · "),d=document.createElement("span");d.className="bp-dim",d.textContent=p;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=u("gpui.mgmt.bom.nompn","no MPN");if(h.append(d,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),h.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=xe(a.stock.class),h.appendChild(y)}o.append(l,h),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(p,d=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!Xt(b,o()))return;this.bomLastUndo=!d&&(y.changed??0)>0?{project:p.project,editId:b.editId,refs:p.refs.slice(),field:p.field,was:typeof y.was==="string"?y.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=d?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Xt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(c,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn",d.textContent="Undo",d.addEventListener("click",()=>{l(Zn(p),!0)}),m.appendChild(d)}if(t.append(i,r,m),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),a=(p)=>t.sources?.[p]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=u("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let p of i){let d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),d.textContent=s(p)+(a(p)?" · judged":""),d.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),r.appendChild(d)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=u("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let p=this.watchGen,d=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:d}).then(()=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(l,m),e.appendChild(r),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let h=_n(n,this.checksSource);if(h.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let p of h){let d=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${d}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(p.source)} · ${p.rule}`;let g=document.createElement("span");g.className=`bp-tone-${d}`,g.textContent=String(p.n),b.append(y,f,g),c.appendChild(b);for(let E of p.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let k=document.createElement("div");if(k.textContent=xe(E.title??""),x.appendChild(k),E.names||this.checksSelectedId===E.id){let A=document.createElement("div");A.className="bp-mgmt-row-sub";let N=document.createElement("span");if(N.className="bp-dim bp-mgmt-flex1",N.textContent=E.names??"",A.appendChild(N),this.checksSelectedId===E.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=u("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(D)=>{D.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:E.id}).then((_)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(W,H))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(W,H))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),A.appendChild(M)}x.appendChild(A)}x.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),c.appendChild(x)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let m=i[l]??0,c=Yt(l),h=document.createElement("span");h.className=m>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",h.textContent=`${c.label} ${m}`,n.appendChild(h)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(l,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],m=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${at(l[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let m=this.lifeSelectedKey===l.key,c=Yt(l.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(m?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let d=document.createElement("span");d.className="bp-mgmt-strong",d.textContent=Mt(l.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=l.mpn||l.key;let y=document.createElement("span");if(y.className=`bp-tone-${c.tone}`,y.textContent=c.label,p.append(d,b,y),typeof l.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(l.stock),p.appendChild(f)}if(h.appendChild(p),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=u("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=u("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(f)}h.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((f)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(u("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(C,S)=>{let R=this.watchGen,q=this.project;this.planStatus="",this.cb.hub.rpc(C,{pro:q,...S}).catch((T)=>{if(R!==this.watchGen||q!==this.project)return;this.planOptimistic.clear(),this.planStatus=T instanceof Error?T.message:u("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let C=this.watchGen,S=++this.planHydrateGen,R=this.project,q=t.revision??0;this.cb.hub.rpc("plan.get",{pro:R,board:!0}).then((T)=>{let z=ri(T);if(!z)return;let J=typeof z.revision==="number"?z.revision:q;if(!oi(C,this.watchGen,S,this.planHydrateGen,R,this.project,J,this.planHydratedRev))return;this.planHydratedRev=J,this.planHydratedKey=`${R}:${J}`,this.planHydratedBoard=z.board??null,this.planHydratedDraw=z.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=u("gpui.mgmt.plan.before","Plan before routing"),r.title=a?u("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):u("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=u("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),l.setAttribute("data-testid","mgmt-plan-off"),l.setAttribute("aria-pressed",!a?"true":"false"),l.textContent=u("gpui.bots.recall.off","Off"),l.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,l),e.appendChild(s);for(let C of t.elsewhere??[]){let S=document.createElement("div");S.className="bp-plan-elsewhere";let R=document.createElement("span");R.className="bp-tone-warn bp-mgmt-flex1",R.textContent=u("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:C.name||C.rel||""}),S.appendChild(R),e.appendChild(S)}if(t.empty){let C=document.createElement("div");C.className="bp-mgmt-note";let S=document.createElement("div");S.className="bp-dim",S.textContent=u("gpui.mgmt.plan.noboard","No routing plan for this board.");let R=document.createElement("div");return R.className="bp-mgmt-faint",R.textContent=u("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),C.append(S,R),e.appendChild(C),e}let m=t.awaiting??0,c=t.blocked??0,h=t.done??0,p=t.total??0,d=t.revision??0,b=zn(t),y=Jn(t),f=y.reduce((C,S)=>C+S.count,0),g=document.createElement("div");g.className="bp-plan-status";let E=document.createElement("div");E.className="bp-plan-status-top";let x=document.createElement("span");if(x.className=`bp-plan-status-badge tone-${b.tone}`,x.textContent=u(b.key,b.label),E.appendChild(x),d>0){let C=document.createElement("span");C.className="bp-dim",C.textContent=`v${d}`,E.appendChild(C)}let k=document.createElement("span");if(k.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":c>0?"bp-tone-bad":"bp-dim"),k.textContent=p>0?`${h}/${p} ${u("gpui.mgmt.plan.done","done")}`:m>0?u("web.plan.awaiting","{n} awaiting approval",{n:m}):u("gpui.mgmt.plan.nothing","Nothing awaits your approval"),E.appendChild(k),!t.live){let C=document.createElement("span");C.className="bp-mgmt-pill",C.textContent=u("gpui.mgmt.plan.saved","saved plan"),E.appendChild(C)}if(g.appendChild(E),f>0){let C=document.createElement("div");C.className="bp-plan-segbar";for(let S of y){if(S.count<=0)continue;let R=document.createElement("div");R.className=`bp-plan-seg bp-tone-bg-${S.tone}`,R.style.flexGrow=String(S.count),C.appendChild(R)}g.appendChild(C)}e.appendChild(g);let A=document.createElement("div");if(A.className="bp-mgmt-head",m>0){let C=document.createElement("button");C.type="button",C.className="primary bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-approve-all"),C.textContent=u("gpui.mgmt.plan.all","Approve all"),C.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(C)}if(t.routing){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-stop"),C.textContent=u("gpui.mgmt.plan.stop","Stop routing"),C.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(C)}if(t.live&&h>0){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-verify"),C.textContent=u("gpui.mgmt.plan.verify","Verify"),C.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(C)}let N=document.createElement("span");N.className="bp-mgmt-flex1";let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.setAttribute("data-testid","mgmt-plan-hide"),M.textContent=this.planHideDone?u("gpui.mgmt.plan.show","Show done"):u("gpui.mgmt.plan.hide","Hide done"),M.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.append(N,M),e.appendChild(A);let D=Array.isArray(t.asks)?t.asks:[];if(D.length>0){let C=D.map((z)=>z.what||"").filter(Boolean).join(", "),S=D[0]?.note||"",R=document.createElement("div");R.className="bp-plan-elsewhere";let q=document.createElement("div");q.className="bp-plan-ask-col";let T=document.createElement("div");if(T.className="bp-tone-warn",T.textContent=C?u("gpui.mgmt.plan.requested","Approval requested: {what}",{what:C}):u("gpui.mgmt.plan.reqplain","Approval requested"),q.appendChild(T),S){let z=document.createElement("div");z.className="bp-dim",z.textContent=S,q.appendChild(z)}R.appendChild(q),e.appendChild(R)}if(this.planStatus){let C=document.createElement("div");C.className="bp-mgmt-note bp-plan-err bp-tone-bad";let S=document.createElement("span");S.className="bp-mgmt-flex1",S.textContent=this.planStatus==="KiCad refused"?u("gpui.mgmt.plan.refused","KiCad refused"):xe(this.planStatus);let R=document.createElement("button");R.type="button",R.className="icon",R.textContent="×",R.title=u("common.close","Close"),R.addEventListener("click",()=>{this.planStatus="",this.render()}),C.append(S,R),e.appendChild(C)}if(t.keys_note){let C=document.createElement("div");C.className="bp-mgmt-note bp-dim";let S="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";C.textContent=t.keys_note===S?u("gpui.mgmt.plan.keysnote",S):xe(t.keys_note),e.appendChild(C)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let C=document.createElement("div");C.className="bp-plan-stackup";let S=document.createElement("button");S.type="button",S.className="bp-plan-stackup-head",S.setAttribute("data-testid","mgmt-plan-stackup-toggle"),S.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let R=document.createElement("span");R.className="bp-plan-chev",R.textContent=this.planStackupOpen?"▾":"▸";let q=document.createElement("span");if(q.textContent=u("gpui.mgmt.plan.stackup","Stackup & impedances"),S.append(R,q),S.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),C.appendChild(S),this.planStackupOpen){let T=document.createElement("div");if(T.className="bp-plan-stackup-body",T.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let z=document.createElement("div");z.className="bp-dim",z.textContent=W,T.appendChild(z)}for(let z of _){let J=document.createElement("div");J.className="bp-mgmt-faint",J.textContent=`· ${z}`,T.appendChild(J)}C.appendChild(T)}e.appendChild(C)}let H=(C,S,R,q)=>{let T=document.createElement("button");return T.type="button",T.className="bp-mgmt-btn bp-plan-chip-btn"+(S?" active":""),T.setAttribute("data-testid",R),T.setAttribute("aria-pressed",S?"true":"false"),T.textContent=C,T.addEventListener("click",q),T},ue=document.createElement("div");if(ue.className="bp-plan-viewbar",ue.append(H(u("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),H(u("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),H(u("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let C=document.createElement("span");C.className="bp-plan-sep";let S=document.createElement("span");S.className="bp-plan-sep";let R=document.createElement("button");R.type="button",R.className="bp-mgmt-btn bp-plan-mini-btn",R.setAttribute("data-testid","mgmt-plan-fit"),R.textContent=u("gpui.mgmt.plan.fit","Fit"),R.addEventListener("click",()=>this.planCanvas?.fitAll()),ue.append(C,H(u("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),H(u("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),H(u("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),S,H(u("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),R)}let me=document.createElement("span");me.className="bp-mgmt-flex1";let se=document.createElement("button");se.type="button",se.className="bp-mgmt-btn bp-plan-mini-btn",se.setAttribute("data-testid","mgmt-plan-expand"),se.textContent=this.planExpanded?u("gpui.mgmt.plan.compact","Compact"):u("gpui.mgmt.plan.expand","Expand"),se.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),ue.append(me,se),e.appendChild(ue);let ye=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),Le=ye&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},Ae=ye&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(Ae.bands??[]).map((C)=>{let S=this.planOptimistic.get(C.id);if(!S)return{...C};return{...C,...S,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Be=(Ae.regions??[]).map((C)=>{let S=this.planOptimistic.get(C.id);if(!S)return{...C};return{...C,...S,edited:!0,state:C.state==="proposed"?"edited":C.state}}),B=[],pe=(t.layers??[]).map((C)=>{let S=[];for(let R of C.items??[]){let q=this.planOptimistic.get(R.id);if(!q){S.push(R);continue}let T={...R,width:typeof q.width==="number"?q.width:R.width,locked:typeof q.locked==="boolean"?q.locked:R.locked,edited:!0,state:R.state==="proposed"?"edited":R.state};if(typeof q.layer==="string"&&q.layer!==C.layer)B.push({target:q.layer,item:T});else S.push(T)}return{...C,items:S}});for(let C of B){let S=pe.find((R)=>R.layer===C.target);if(S)S.items=[...S.items??[],C.item]}let ne=Rt(pe,t.copper_layers),Z=this.planGridMode==="all"?ne.map((C)=>C.layer):this.planGridMode==="single"?[this.planShownLayers.find((C)=>ne.some((S)=>S.layer===C))??rt(ne)[0]??ne[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((C)=>ne.some((S)=>S.layer===C))?this.planShownLayers.slice(0,2):rt(ne);if(this.planViewMode!=="list"&&ne.length>1){let C=document.createElement("div");C.className="bp-plan-layerbar";for(let S of ne){let R=Z.includes(S.layer);C.appendChild(H(S.title||S.layer,R,`mgmt-plan-layerpill-${S.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"){if(!Z.includes(S.layer))this.planShownLayers=Z.length>=2?[Z[0],S.layer]:[...Z,S.layer]}else this.planGridMode="single",this.planShownLayers=[S.layer];this.render()}))}e.appendChild(C)}let le=(C,S)=>{let R=this.planOptimistic.get(C)??{};if(this.planOptimistic.set(C,{...R,...S}),typeof S.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"&&!Z.includes(S.layer))this.planShownLayers=Z.length>=2?[Z[0],S.layer]:[...Z,S.layer]}let q=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:C,fields:S}],...q!==void 0?{base:q}:{}})};if(this.planCommitFields=le,this.planSelectedId){let C="",S=null;for(let R of pe){let q=(R.items??[]).find((T)=>T.id===this.planSelectedId);if(q){C=R.layer,S=q;break}}if(S){let R=document.createElement("div");R.className="bp-plan-inspector",R.setAttribute("data-testid","mgmt-plan-inspector");let q=document.createElement("div");q.className="bp-plan-ins-row";let T=document.createElement("span");T.className="bp-plan-ins-sw",T.style.background=S.kind==="corridor"?vt(S.name||S.id,S.color||""):ft(S.name||S.id,S.color||"");let z=document.createElement("span");z.className="bp-mgmt-strong",z.textContent=S.name||S.id;let J=document.createElement("span");if(J.className="bp-dim",J.textContent=C,q.append(T,z,J),S.edited||S.state==="edited"){let be=document.createElement("span");be.className="bp-plan-ins-pill warn",be.textContent=u("gpui.mgmt.plan.edited","Edited"),q.appendChild(be)}if(S.locked){let be=document.createElement("span");be.className="bp-plan-ins-pill",be.textContent=u("gpui.mgmt.plan.locked","Locked"),q.appendChild(be)}let Me=document.createElement("span");Me.className="bp-mgmt-flex1",q.appendChild(Me);let re=document.createElement("button");if(re.type="button",re.className="bp-mgmt-btn bp-plan-mini-btn",re.setAttribute("data-testid","mgmt-plan-lock"),re.textContent=S.locked?u("gpui.mgmt.plan.unlock","Unlock"):u("gpui.mgmt.plan.lock","Lock"),re.addEventListener("click",()=>le(S.id,{locked:!S.locked})),q.appendChild(re),S.state==="proposed"||S.state==="edited"){let be=document.createElement("button");be.type="button",be.className="primary bp-mgmt-btn bp-plan-mini-btn",be.textContent=u("android.hub.machines.approve","Approve"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!0}));let de=document.createElement("button");de.type="button",de.className="bp-mgmt-btn bp-plan-mini-btn",de.textContent=u("gpui.mgmt.plan.reject","Reject"),de.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!1})),q.append(be,de)}let ke=document.createElement("button");ke.type="button",ke.className="bp-mgmt-btn bp-plan-mini-btn",ke.setAttribute("data-testid","mgmt-plan-note-toggle"),ke.textContent=u("gpui.mgmt.plan.addnote","Add note"),ke.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let He=document.createElement("button");if(He.type="button",He.className="icon",He.textContent="×",He.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),q.append(ke,He),R.appendChild(q),!S.locked){let be=document.createElement("div");if(be.className="bp-plan-ins-row",S.kind==="corridor"){let he=typeof S.width==="number"?S.width:1.5,Re=document.createElement("span");Re.className="bp-dim",Re.textContent=u("gpui.mgmt.plan.width","Width");let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn bp-plan-mini-btn",X.setAttribute("data-testid","mgmt-plan-w-down"),X.textContent="-",X.addEventListener("click",()=>{let Ke=Math.round(Math.max(0.15,he-0.25)*100)/100;le(S.id,{width:Ke})});let oe=document.createElement("span");oe.className="bp-plan-ins-val",oe.textContent=`${he.toFixed(2)}mm`;let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn bp-plan-mini-btn",je.setAttribute("data-testid","mgmt-plan-w-up"),je.textContent="+",je.addEventListener("click",()=>{let Ke=Math.round(Math.min(25,he+0.25)*100)/100;le(S.id,{width:Ke})});let We=document.createElement("span");We.className="bp-plan-sep",be.append(Re,X,oe,je,We)}let de=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((he)=>he.layer):pe.map((he)=>he.layer);if(de.length>0){let he=document.createElement("span");he.className="bp-dim",he.textContent=u("gpui.mgmt.plan.layer.move","Move to layer"),be.appendChild(he);for(let Re of de)be.appendChild(H(Re,Re===C,`mgmt-plan-move-${Re}`,()=>{if(Re!==C)le(S.id,{layer:Re})}))}R.appendChild(be)}if(this.planNoteOpen){let be=document.createElement("form");be.className="bp-plan-note-form";let de=document.createElement("input");de.type="text",de.className="bp-plan-note-input",de.setAttribute("data-testid","mgmt-plan-note-input"),de.placeholder=u("gpui.mgmt.plan.note.placeholder","Steering note for router…");let he=document.createElement("button");he.type="submit",he.className="primary bp-mgmt-btn bp-plan-mini-btn",he.setAttribute("data-testid","mgmt-plan-note-submit"),he.textContent=u("gpui.mgmt.plan.addnote","Add note"),be.append(de,he),be.addEventListener("submit",(Re)=>{Re.preventDefault();let X=de.value.trim();if(!X)return;de.value="",this.planNoteOpen=!1;let oe=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:S.id,text:X}],...oe!==void 0?{base:oe}:{}})}),R.appendChild(be)}if(this.planViewMode!=="list"&&!S.locked){let be=document.createElement("div");be.className="bp-plan-hint",be.textContent=u("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),R.appendChild(be)}e.appendChild(R)}}let j=document.createElement("div");j.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),j.setAttribute("data-testid","mgmt-plan-rows");let Y=u("gpui.mgmt.plan.done","done");for(let C of pe){let S=C.items??[],R=document.createElement("div");R.className="bp-mgmt-group-head bp-plan-layer-head";let q=document.createElement("div");q.className="bp-mgmt-row-line";let T=document.createElement("span");T.className="bp-mgmt-strong",T.textContent=C.layer;let z=document.createElement("span");if(z.className="bp-dim bp-mgmt-flex1",z.textContent=`${C.role?`${C.role} · `:""}${C.done??0}/${S.length} ${Y}`,q.append(T,z),C.status!=="approved"&&S.length>0){let J=document.createElement("button");J.type="button",J.className="bp-mgmt-btn",J.textContent=u("gpui.mgmt.plan.layer","Approve layer"),J.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!0}));let Me=document.createElement("button");Me.type="button",Me.className="bp-mgmt-btn",Me.textContent=u("gpui.mgmt.plan.reject","Reject"),Me.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!1})),q.append(J,Me)}if(R.appendChild(q),C.stackup){let J=document.createElement("div");J.className="bp-plan-layer-stackup",J.textContent=C.stackup,R.appendChild(J)}j.appendChild(R);for(let J of S){if(this.planHideDone&&qn(J))continue;let Me=this.planSelectedId===J.id,re=document.createElement("div");re.className="bp-mgmt-row bp-plan-row"+(Me?" active":""),re.setAttribute("data-testid",`mgmt-plan-row-${J.id}`);let ke=document.createElement("div");ke.className="bp-mgmt-row-line";let He=document.createElement("span");He.className=`bp-plan-swatch bp-plan-st-${J.state||"proposed"}`,He.style.setProperty("--swatch-color",J.color||"#8a8a8a");let be=document.createElement("span");be.className="bp-mgmt-flex1"+(J.state==="blocked"||J.state==="failed"?" bp-tone-bad":J.state==="edited"?" bp-tone-warn":J.state==="rejected"||J.state==="routed"||J.state==="verified"?" bp-dim":""),be.textContent=`${J.name||J.id}${J.locked?" \uD83D\uDD12":""}`;let de=[];if(J.kind==="plane"){if(J.reference)de.push(u("gpui.mgmt.plan.reference","over {layer}",{layer:J.reference}))}else{let X=J.nets??0;de.push(X===1?u("web.plan.net.one","1 net"):u("web.plan.nets","{n} nets",{n:X}))}if(typeof J.width==="number"&&Number.isFinite(J.width))de.push(`${J.width.toFixed(2)}mm`);if(J.impedance)de.push(J.impedance);let he=de.join(" · "),Re=document.createElement("span");if(Re.className="bp-plan-mark "+(J.state==="blocked"||J.state==="failed"?"bp-tone-bad":J.state==="verified"||J.state==="routed"?"bp-tone-ok":J.state==="approved"?"bp-tone-accent":"bp-dim"),Re.textContent=Kn(J),ke.append(He,be,Re),J.state==="proposed"||J.state==="edited"){let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn",X.textContent="✓",X.title=u("gpui.mgmt.plan.layer","Approve layer"),X.addEventListener("click",(je)=>{je.stopPropagation(),n("plan.approve",{layer:"",ids:[J.id],approve:!0})});let oe=document.createElement("button");oe.type="button",oe.className="bp-mgmt-btn",oe.textContent="✗",oe.title=u("gpui.mgmt.plan.reject","Reject"),oe.addEventListener("click",(je)=>{je.stopPropagation(),n("plan.approve",{layer:"",ids:[J.id],approve:!1})}),ke.append(X,oe)}if(re.appendChild(ke),he){let X=document.createElement("div");X.className="bp-mgmt-row-sub bp-plan-detail bp-dim",X.textContent=he,re.appendChild(X)}if(J.state==="routing"&&typeof J.total==="number"&&J.total>0){let X=document.createElement("div");X.className="bp-plan-microbar";let oe=document.createElement("div");oe.className="bp-plan-microbar-fill";let je=Math.max(0,Math.min(100,Math.round((J.routed??0)/J.total*100)));oe.style.width=`${je}%`,X.appendChild(oe),re.appendChild(X)}if(J.problem_text){let X=document.createElement("div");X.className="bp-plan-problem",X.textContent=J.problem_text,re.appendChild(X)}re.addEventListener("click",()=>{this.planSelectedId=J.id,n("plan.focus",{id:J.id}),this.render()}),j.appendChild(re)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new tn({onSelect:(q)=>{if(this.planSelectedId=q,!q)this.planNoteOpen=!1;this.render()},onFocusItem:(q)=>{n("plan.focus",{id:q})},onOptimisticPatch:(q,T)=>{let z=this.planOptimistic.get(q)??{};this.planOptimistic.set(q,{...z,...T})},onRevertOptimistic:(q)=>{if(this.planOptimistic.delete(q)||this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(q,T)=>{(this.planCommitFields??le)(q,T)},onApproveLayer:(q,T)=>{n("plan.approve",{layer:q,ids:[],approve:T})},onQuickApprove:(q,T)=>{n("plan.approve",{layer:"",ids:q,approve:T})}});let C=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,S=this.planExpanded||this.panelEl.clientWidth>=540||C;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:Z,selectedId:this.planSelectedId,board:Le,bands:we,regions:Be,layers:ne,copperLayers:t.copper_layers},S);let R=document.createElement("div");R.className="bp-plan-canvas-scroll",R.appendChild(this.planCanvas.root),e.appendChild(R)}if(this.planViewMode!=="canvas")e.appendChild(j);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let C=document.createElement("div");C.className="bp-plan-footer",C.textContent=u("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(C)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,x={})=>{let k=this.watchGen,A=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:A,action:E,...x}).catch((N)=>{if(k!==this.watchGen||A!==this.project)return;this.fabStatus=N instanceof Error?N.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=u("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Xn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=u("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let h=document.createElement("span"),p=(l?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),h.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(h),l?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(E)}if(!l?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),c.appendChild(E)}if(l?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(E)}m.appendChild(c),o.appendChild(m);let d=Yn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(d.button?"bp-tone-warn":"bp-dim"),f.textContent=d.text,y.appendChild(f),d.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=d.button,E.addEventListener("click",()=>n("drc")),y.appendChild(E)}b.appendChild(y),o.appendChild(b);for(let E of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=E,o.appendChild(x)}for(let E of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=u("gpui.mgmt.fab.apply","Apply"),N.addEventListener("click",()=>n("apply",{key:E.key})),k.append(A,N),x.appendChild(k),o.appendChild(x)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let k=t.stackup.by==="proposed",A=document.createElement("span");if(A.className="bp-mgmt-flex1 "+(k?"bp-tone-warn":"bp-dim"),A.textContent=`${k?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(A),k){let N=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=u("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:N})),x.appendChild(M)}E.appendChild(x),o.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let k=document.createElement("span");k.className="bp-mgmt-flex1 bp-tone-warn",k.textContent=u("gpui.mgmt.fab.changed","Changed since you last looked");let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=u("gpui.mgmt.fab.seen","Seen"),A.addEventListener("click",()=>n("seen")),x.append(k,A),E.appendChild(x);for(let N of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=N,E.appendChild(M)}o.appendChild(E)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=u("gpui.mgmt.fab.limit","Limit");let k=document.createElement("span");k.className="bp-mgmt-col",k.textContent=u("gpui.mgmt.fab.free","Base price");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=u("gpui.mgmt.fab.extra","Costs more");let N=document.createElement("span");N.className="bp-mgmt-col bp-mgmt-col-read",N.textContent=u("gpui.mgmt.fab.readcol","Read"),E.append(x,k,A,N),o.appendChild(E);for(let D of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(D.changed?" bp-tone-warn":D.inherited?" bp-dim":""),H.textContent=`${D.changed?"• ":""}${D.label??""}`;let ue=document.createElement("span");ue.className="bp-mgmt-col",ue.textContent=D.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=D.extra?.text||"—";let se=D.free&&typeof D.free==="object"?D.free:D.extra,ye=se?.fetched??"",Le=Boolean(ye)&&se?.confidence!=="published",Ae=ye?Le?`${ye}*`:ye:"—",we=se?.source??"",Be;if(we.startsWith("https://")&&ye){let B=document.createElement("a");B.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",B.href=we,B.target="_blank",B.rel="noopener noreferrer",B.textContent=Ae,Be=B}else{let B=document.createElement("span");B.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",B.textContent=Ae,Be=B}_.append(H,ue,me,Be),W.appendChild(_),o.appendChild(W)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=u("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var xs={trs:(e)=>e,t:(e,t)=>t},Cs=new Set(["/settle"]);function pi(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function hi(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ui(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function bi(e,t=xs){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=Cs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:m}=mi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:m,dotClass:hi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function gi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let b of i)p.set(b.id,b.title||b.id);let d=new Set;for(let b of l)if(b.action.type==="thread")d.add(b.action.id);for(let b of n.threads){if(!b.id||d.has(b.id))continue;d.add(b.id);let{urgency:y,want:f}=mi(b);l.push({label:b.title||"Untitled thread",place:b.project?p.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:hi(b),action:{type:"thread",id:b.id}})}}let m=[];for(let p=0;p0)m.push({score:f,index:p,item:d})}m.sort((p,d)=>{if(o){let f=(d.item.urgency??0)-(p.item.urgency??0);if(f!==0)return f}if(d.score!==p.score)return d.score-p.score;let b=p.item.kind==="thread"?0:1,y=d.item.kind==="thread"?0:1;if(b!==y)return b-y;return p.index-d.index});let c=new Set,h=[];for(let p of m){let d=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(c.has(d))continue;if(c.add(d),h.push(p.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=bi(t,{t:u,trs:xe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=gi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=u("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,p)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(p,d),m.appendChild(b),d{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var Ss=new Set(["resume","raise","retry","move","signin"]);function yi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function jt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Ss.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function wi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class rn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${u("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",u("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${u("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",u("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let c=document.createElement("div");c.className="bp-set-head",c.textContent=u("home.machine","Home machine");let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";d.textContent=b,p.appendChild(d);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?u("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):u("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?u("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):u("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?u("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):u("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(p.appendChild(y),h.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=u("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),h.appendChild(f)}m.append(c,h),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=u("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=u("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let l=document.createElement("div");l.className="bp-set-head",l.textContent="Paired devices",o.appendChild(l);try{let m=await this.cb.onLoadDevices();if(m.length===0){let c=document.createElement("div");c.className="bp-dim",c.textContent="No devices listed.",o.appendChild(c)}else for(let c of m){let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div");if(d.textContent=c.title||c.head||"",p.appendChild(d),c.text||c.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=c.text||c.detail||"",p.appendChild(b)}if(h.appendChild(p),c.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of c.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||u("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}h.appendChild(b)}o.appendChild(h)}}catch(m){let c=document.createElement("div");c.className="bp-dim";let h=m instanceof Error&&m.message?m.message:"Not available from a browser";c.textContent=`${h} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(c)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function Ce(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=Ce("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function on(e){return Ce("pre","bp-context-code",e)}function Ls(e){return Ce("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,xe(e))}function Ht(e,t){let n=Ce("div","bp-context-row");return n.append(Ce("strong",void 0,e),Ls(t)),n}class ln{fetchContext;dialog=Ce("dialog","bp-context");title=Ce("h2");cwd=Ce("div","bp-context-path");tabs=Ce("div","bp-context-tabs");body=Ce("div","bp-context-body");notice=Ce("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ce("div","bp-context-head"),i=Ce("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(u("common.refresh","Refresh"),()=>{this.load()}),yt(u("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=u("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=u("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[u("thread.context.instructions","Instructions"),u("thread.context.system","System Prompt"),u("thread.context.skills","Skills"),u("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ce("p","bp-dim",u("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ce("details","bp-context-card"),i=Ce("summary");if(i.append(Ht(t.path,t.status),Ce("small","bp-dim",u("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,on(t.preview)),t.note)n.append(Ce("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ce("div","bp-context-row"),n=yt(u("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=u("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ce("p","bp-dim",u("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[u("thread.context.base","Backplane"),e.sections.base],[u("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[u("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ce("h3",void 0,i),on(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ce("h3",void 0,xe(t)));for(let i of n){let s=Ce("article","bp-context-card");s.append(Ht(i.name,i.status),Ce("p",void 0,i.description),Ce("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ce("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ce("p","bp-dim",u("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ce("article","bp-context-card");n.append(Ht(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Ht(s.name,s.status),on(a)),s.cwd)n.append(Ce("small","bp-context-path",s.cwd))}if(t.error)n.append(Ce("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?u("thread.context.trust","Trust and enable"):i==="disable"?u("thread.context.disable","Disable"):u("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ce("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var Ei="http://www.w3.org/2000/svg";function xi(){let e=document.createElementNS(Ei,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ei,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function As(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ci(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class cn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=u("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=u("thread.new","New thread"),l.setAttribute("aria-label",u("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?u("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):u("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?u("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):u("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=u("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=u("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=u("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=u("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=u("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=u("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),n.appendChild(h)}let i=document.createElement("span");i.className=`bp-dot ${As(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let h=document.createElement("span");if(h.className="bp-badge-need",h.textContent=e.want==="approval"?"!":"•",e.say)h.title=e.say;n.appendChild(h)}else if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=u("tools.pinned","Pinned");n.appendChild(h)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?yi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,l.appendChild(m);for(let h of r.actions){if(!jt(h,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=h.label,p.setAttribute("data-testid",`need-${h.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(d)=>{d.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(h).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(p)}o.append(n,l);let c=this.needErr.get(e.id);if(c){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=c,o.appendChild(h)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let l=document.createElement("section");l.className="bp-side-section",l.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),l.appendChild(m);for(let c of o)l.appendChild(this.renderSectionThreadRow(c,!1));e.appendChild(l);continue}if(r.kind==="projects"){let o=r.rows.filter((c)=>{if(!t)return!0;if((c.title||c.id).toLowerCase().includes(t))return!0;if((c.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((c.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),l=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!l&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),l){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let h=r.count??o.length,p=r.open?"▾":"▸";if(c.textContent=`${r.title.toUpperCase()} (${h}) ${p}`,r.hint)c.title=r.hint;c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(c)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!l||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let c=document.createElement("div");c.className="bp-side-empty",c.textContent="No projects yet.",m.appendChild(c)}for(let c of o){let h=document.createElement("div");if(h.className="bp-proj-group"+(c.off?" bp-dim":""),h.setAttribute("data-project-id",c.id),c.nav||c.key)h.setAttribute("data-project-key",c.nav||c.key||"");let p=document.createElement("div");p.className="bp-proj-head";let d=document.createElement("button");d.type="button",d.className="bp-proj-toggle";let b=xi();if(c.css)b.style.color=c.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=c.title||c.id,d.append(b,y),c.fold==="project-fold"&&c.nav)d.addEventListener("click",()=>this.cb.onToggleProjectFold?.(c.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=u("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${c.id}`),c.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(c.id)}),p.append(d,f),h.appendChild(p),!c.folded||Boolean(t)){let g=Boolean(t)&&(c.title||c.id).toLowerCase().includes(t);for(let E of c.swarms??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(E,!0))}for(let E of c.threads??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(E,!0))}if(s&&s.project===c.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Ci(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(h)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!t,m=xi();if(i.css)m.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(m,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=u("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${i.id}`),h.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,h),a.appendChild(r),!l)for(let p of s)a.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:Ci(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=u("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let c of this.bots){let h=document.createElement("div");h.className="bp-thread-row"+(c.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",c.color)p.style.backgroundColor=c.color;let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`@${c.name}`,h.append(p,d),h.addEventListener("click",()=>this.cb.onSelectBot(c)),n.appendChild(h)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let l=document.createElement("span");l.textContent=u("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(l,m),r.appendChild(o);for(let c of this.rooms){let h=document.createElement("div");h.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${c.name}`,h.appendChild(p),r.appendChild(h)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ps(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ns(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/m:0));s[a]=c<0?c*32768:c*32767}return s}class dn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ps(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Ns(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var ki=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Si=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Li=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Ai=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ms=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ts=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Bs=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class pn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,p},r=(h)=>{let p=0,d=0,b=0;for(let y=1;y<=h.maxBits;y++){p|=a(1);let f=h.counts[y];if(p-f{let p=l+h;if(p>t)throw Error("inflated frame exceeds limit");if(p<=o.length)return;let d=o.length;while(d{m(1),o[l++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=a(1),p=a(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let d=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(d^65535)!==b)throw Error("invalid stored block length");if(n+d>e.length)throw Error("truncated stored payload");m(d);for(let y=0;y=e.length)break}else if(p===1||p===2){let d=Ts,b=Bs;if(p===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,E=new Uint8Array(19);for(let M=0;Mk)throw Error("code length overflow");for(let _=0;_k)throw Error("code length overflow");N+=D}else if(M===18){let D=a(7)+11;if(N+D>k)throw Error("code length overflow");N+=D}else throw Error("invalid code length symbol")}d=Et(A,y),b=Et(A.subarray(y),f)}while(!0){let y=r(d);if(y<256)c(y);else if(y===256)break;else{let f=y-257;if(f>=ki.length)throw Error("invalid length symbol");let g=ki[f]+(Si[f]?a(Si[f]):0),E=r(b);if(E>=Li.length)throw Error("invalid distance symbol");let x=Li[E]+(Ai[E]?a(Ai[E]):0);m(g);let k=this.winPos-x&32767;for(let A=0;A{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new pn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(l))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Is=new TextDecoder;function Pi(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ni(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,m=i(o&31);if(m===null)return null;switch(l){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let c=e.subarray(t,t+m);return t+=m,c}case 3:{if(t+m>e.length)return null;let c=Is.decode(e.subarray(t,t+m));return t+=m,c}case 4:{if(m>e.length)return null;let c=Array(m);for(let h=0;h=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Ti(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new Mi(m),h=[],p=[],d=0,b=0;while(c.more()){let y=c.nextU32(),f=h.length,g=1/0,E=1/0,x=-1/0,k=-1/0;if(a===2)d=d+c.nextI32()|0,b=b+c.nextI32()|0,h.push(d,b),g=x=d,E=k=b;else{let N=Math.min(c.nextU32(),1048576);for(let M=0;Mx)x=d;if(bk)k=b}}let A=(h.length-f)/2;if(A>0){let N=a===2||A===1?2:a===0?0:1,M=a===0?0:o;p.push({info:y,x0:g-M,y0:E-M,x1:x+M,y1:k+M,at:f,n:A,kind:N})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(h),pieces:p}}function Bi(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Ii(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,c=(t-l)/r;if(m<0||m>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var Ri=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ji(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class hn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Hi(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,m=-1,c=null,h=new hn,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let d=document.createElement("div");d.className="bp-pane-bar bp-browser-nav";function b(Z,le,j){let Y=document.createElement("button");if(Y.type="button",Y.className="bp-v-btn",Y.textContent=Z,Y.setAttribute("data-testid",le),j)Y.title=j;return Y}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let k=b("Go","browser-go","Navigate");k.type="submit",E.append(x,k);let A=b("Take over","browser-takeover");A.classList.add("is-primary"),d.append(y,f,g,E,A);let N=document.createElement("div");N.className="bp-browser-drive-bar",N.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let D=document.createElement("input");D.type="text",D.className="bp-browser-input",D.placeholder="Type text or press Enter/Tab/Arrows…",D.autocomplete="off",D.spellcheck=!1,D.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");M.append(D,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[Z,le]of Ri){let j=b(Z,`browser-key-${le}`);j.addEventListener("click",()=>we("press",{key:le})),_.append(j)}N.append(M,_);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ue=document.createElement("div");ue.className="bp-browser-stage",ue.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let se=document.createElement("div");se.className="bp-pane-empty",se.setAttribute("data-testid","browser-empty"),se.textContent="Loading browser screen…",ue.append(me,se);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,p.append(d,N,H,ue,ye),e.replaceChildren(p);function Le(Z){H.textContent=Z,H.hidden=!Z}function Ae(){N.hidden=!s,ye.hidden=!s,A.textContent=s?"Hand back":"Take over",A.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),A.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function we(Z,le={},j){h.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:Z,...le}),!i)return;j?.(),pe()}catch(Y){if(!i)return;Le(Y instanceof Error?Y.message:String(Y))}})}function Be(Z){we("toolbar",{command:Z},()=>{s=!0,Ae()})}y.addEventListener("click",()=>Be("back")),f.addEventListener("click",()=>Be("forward")),g.addEventListener("click",()=>Be("reload")),E.addEventListener("submit",(Z)=>{Z.preventDefault();let le=ji(x.value);if(!le)return;if(x.value=le,!s)we("takeover",{},()=>{s=!0,Ae()});we("navigate",{url:le},()=>{s=!0,Ae()})}),A.addEventListener("click",()=>{if(s)we("handback",{},()=>{s=!1,Ae()});else we("takeover",{},()=>{s=!0,Ae(),D.focus()})});function B(){let Z=D.value;if(!Z)return;D.value="",we("type",{text:Z})}W.addEventListener("click",B),D.addEventListener("keydown",(Z)=>{if(!s)return;if(Z.key==="Enter"){if(Z.preventDefault(),D.value)B();we("press",{key:"Enter"});return}if(Z.key==="Tab"||Z.key==="Escape"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="ArrowLeft"||Z.key==="ArrowRight"||Z.key==="Backspace"&&D.value==="")Z.preventDefault(),we("press",{key:Z.key})}),me.addEventListener("click",(Z)=>{if(!s||!a)return;let le=me.getBoundingClientRect(),j=Ii(Z.clientX,Z.clientY,{left:le.left,top:le.top,width:le.width,height:le.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!j)return;we("click",j)}),me.addEventListener("wheel",(Z)=>{if(!s||!a)return;Z.preventDefault();let le=Math.round(Z.deltaX),j=Math.round(Z.deltaY);if(le===0&&j===0)return;we("scroll",{dx:le,dy:j})},{passive:!1});async function pe(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let Z=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(Z.ok){let le=await Z.blob();if(!i)return;let j=URL.createObjectURL(le),Y=r;if(r=j,me.src=j,me.hidden=!1,se.hidden=!0,a=!0,Y)URL.revokeObjectURL(Y)}else if(!a)me.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)me.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ne=t.hub.onFrame((Z)=>{if(!i)return;if(Z.t==="shot"&&Z.bot===n){if(typeof Z.n==="number"){if(Z.n===m)return;m=Z.n}pe()}});return pe(),{destroy(){if(i=!1,ne(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function U(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Dt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Fi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function js(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Di(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Hs(e){let t=Fi(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function $i(e,t,n,i){let s=!0,a="",r="",o=U("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=U("div","bp-pane-bar"),m=U("div","bp-files-crumbs"),c=U("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void f(a)),l.append(m,c);let h=U("div","bp-files-split"),p=U("div","bp-files-list");p.setAttribute("data-testid","files-list");let d=U("div","bp-files-preview");d.setAttribute("data-testid","files-preview"),d.append(U("div","bp-pane-empty","Select a file to preview")),h.append(p,d),o.append(l,h),e.replaceChildren(o);function b(){m.replaceChildren();let g=U("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let E=a.split("/").filter(Boolean),x="";for(let k of E){x=x?`${x}/${k}`:k;let A=x;m.append(U("span","bp-vh-sep","/"));let N=U("button","bp-crumb-btn",k);N.type="button",N.addEventListener("click",()=>void f(A)),m.append(N)}}async function y(g,E,x){r=g,d.replaceChildren();let k=U("div","bp-files-prev-head");k.append(U("span","bp-files-prev-name",g));let A=U("div","bp-files-prev-acts"),N=Hs(E);if(N){let _=U("button","bp-v-btn is-primary",`Open in ${N}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(N,g)),A.append(_)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,D=U("a","bp-v-btn","Download");D.href=M,D.download=E,A.append(D),k.append(A),d.append(k);let W=Fi(E);if(js(W)){let _=U("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=E,H.src=M,_.append(H),d.append(_);return}if(x>524288&&!Di(W)){d.append(U("div","bp-pane-empty",`Binary file (${Dt(x)}). Use Download to save.`));return}if(Di(W)||x<=65536){let _=U("div","bp-pane-empty","Loading…");d.append(_);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||r!==g)return;if(!H.ok){_.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){_.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=E,ne.src=M,d.append(ne);return}let me=262144,se=[],ye=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:Z,value:le}=await ne.read();if(Z||!le)break;if(ye+le.byteLength>me){let j=me-ye;if(j>0)se.push(le.subarray(0,j)),ye+=j;Le=!0,await ne.cancel();break}se.push(le),ye+=le.byteLength}}finally{ne.releaseLock()}}if(!s||r!==g)return;let Ae=new Uint8Array(ye),we=0;for(let ne of se)Ae.set(ne,we),we+=ne.byteLength;let Be=!1;for(let ne=0;nek.dir===A.dir?k.name.localeCompare(A.name):k.dir?-1:1),p.replaceChildren(),g){let k=U("button","bp-file-row is-dir");k.type="button",k.append(U("span","bp-file-icon","↰"),U("span","bp-file-name",".."));let A=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";k.addEventListener("click",()=>void f(A)),p.append(k)}if(x.length===0){p.append(U("div","bp-pane-empty","Empty folder"));return}for(let k of x){let A=g?`${g}/${k.name}`:k.name,N=U("button","bp-file-row"+(k.dir?" is-dir":"")+(A===r?" is-sel":""));N.type="button",N.setAttribute("data-testid",`file-row-${k.name}`),N.append(U("span","bp-file-icon",k.dir?"▸":"·"),U("span","bp-file-name",k.name),U("span","bp-file-size",k.dir?"":Dt(k.size))),N.addEventListener("click",()=>{if(k.dir)f(A);else p.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),N.classList.add("is-sel"),y(A,k.name,k.size)}),p.append(N)}}catch(E){if(!s)return;p.replaceChildren(U("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return f(""),{destroy(){s=!1}}}function Gi(e,t,n){let i=!0,s=U("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=U("div","bp-pane-bar"),r=U("span","bp-diff-summary","Loading diff…"),o=U("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let l=U("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(U("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof c?.diff==="string"?c.diff:"";if(!h.trim()){r.textContent="Clean working tree",l.append(U("div","bp-pane-empty","No uncommitted changes."));return}let p=h.split(` -`),d=0,b=0,y=0,f=document.createDocumentFragment(),g=U("div","bp-diff-file");for(let E of p){if(E.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=U("div","bp-diff-file"),d++;let x=E.match(/ b\/(.+)$/);g.append(U("div","bp-diff-file-head",x?x[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))g.append(U("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))g.append(U("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))b++,g.append(U("div","bp-diff-line is-add",E));else if(E.startsWith("-"))y++,g.append(U("div","bp-diff-line is-del",E));else g.append(U("div","bp-diff-line",E))}if(g.childNodes.length>0)f.append(g);r.textContent=`${d||1} file${d===1?"":"s"} · +${b} -${y}`,l.append(f)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(U("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return m(),{destroy(){i=!1}}}function Oi(e,t,n){let i=!0,s="checks",a=U("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=U("div","bp-pane-bar"),o=U("div","bp-review-tabs"),l=U("button","bp-v-btn is-on","Checks"),m=U("button","bp-v-btn","BOM"),c=U("button","bp-v-btn","Comments");l.type=m.type=c.type="button",o.append(l,m,c);let h=U("button","bp-v-btn","Refresh");h.type="button",h.addEventListener("click",()=>void y()),r.append(o,h);let p=U("div","bp-review-body");p.setAttribute("data-testid","review-body"),a.append(r,p),e.replaceChildren(a);function d(f){s=f,l.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),y()}l.addEventListener("click",()=>d("checks")),m.addEventListener("click",()=>d("bom")),c.addEventListener("click",()=>d("comments"));function b(f){let g=U("div","bp-review-md"),E=f.split(` -`),x=0;while(x{M.preventDefault();let D=A.value.trim();if(!D)return;N.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:D}).then(()=>{A.value="",N.disabled=!1,y()},()=>{N.disabled=!1})}),p.append(k),x.length===0){p.append(U("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let D=U("div","bp-review-comment"+(M.resolved?" is-resolved":"")),W=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");D.append(U("div","bp-review-comment-meta",W),U("div","bp-review-comment-text",M.text)),p.append(D)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(p.replaceChildren(),g.line||g.gate){let E=U("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));p.append(E)}if(g.err)p.append(U("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let E=U("div","bp-review-tasks");g.tasks.forEach((x,k)=>{let A=U("label","bp-review-task"),N=document.createElement("input");N.type="checkbox",N.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:k;N.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void y(),()=>{})}),A.append(N,U("span",void 0,x.text||x.label||`Item ${k+1}`)),E.append(A)}),p.append(E)}if(g.md&&g.md.trim())p.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))p.append(U("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;p.replaceChildren(U("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function Ui(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class un{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,m=n*0.5,c=this.scale,h=this.cx,p=this.cy,d=h-l/c,b=h+l/c,y=p-m/c,f=p+m/c,{off:g,dim:E,lift:x}=this.masks,k=[],A=[];for(let M=0;M>>D&1)===1)continue;if(D===x)A.push(M);else k.push(M)}let N=k.concat(A);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>W.layer&1)===1,H=W.alpha*(_?0.25:1);if(H<=0.01)continue;this.drawChunk(r,W,H,d,y,b,f,h,p,c,l,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let D=0;Da||f.y1r)continue;if(f.n<3)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+h;e.moveTo(g,E);for(let x=1;x0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=d,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let E=(p[g.at]-o)*m+c,x=(p[g.at+1]-l)*m+h;e.moveTo(E+b,x),e.arc(E,x,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=d,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+h;if(f.n===1)e.moveTo(g,E),e.lineTo(g+0.01,E);else{e.moveTo(g,E);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,m,c,h,p){let d=t.pts,b=Ui(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(d[f.at]-l)*c+h,E=(d[f.at+1]-m)*c+p;if(f.kind===2){let x=Math.max(1.5,t.r*c);e.fillStyle=b,e.beginPath(),e.arc(g,E,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,E);for(let x=1;x=0;c--){let h=n.chunks[c];if(h.layer<32&&(m>>>h.layer&1)===1)continue;for(let p=0;pd.x1+r||ad.y1+r)continue;let b=(d.x1-d.x0+1)*(d.y1-d.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,h=s-l.left-l.width*0.5,p=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-h/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-p/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Vi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Wi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function bn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),u=document.createElement("div");u.className="bp-code-block";let p=document.createElement("div");p.className="bp-code-head";let d=document.createElement("span");d.className="bp-code-lang",d.textContent=l||"code";let b=document.createElement("button");b.type="button",b.className="bp-btn-ghost bp-code-copy";let y=h("common.copy","Copy");b.textContent=y,b.addEventListener("click",()=>{navigator.clipboard?.writeText(c).then(()=>{b.textContent="✓",window.setTimeout(()=>{b.textContent=y},1200)}).catch(()=>{})}),p.append(d,b);let f=document.createElement("pre"),g=document.createElement("code");g.textContent=c,f.appendChild(g),u.append(p,f),t.appendChild(u);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let l=document.createElement(`h${Math.min(4,a[1].length+1)}`);l.className="bp-md-h",ht(l,a[2]),t.appendChild(l),i++;continue}if(s.startsWith("> ")){let l=document.createElement("blockquote");l.className="bp-md-quote";let m=[];while(i "))m.push(n[i].slice(2)),i++;ht(l,m.join(` +`)),t.appendChild(l);continue}if(/^\s*[-*]\s+/.test(s)){let l=document.createElement("ul");l.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let l=0;l0)o.appendChild(document.createElement("br"));ht(o,r[l])}t.appendChild(o)}return t}var Bn="http://www.w3.org/2000/svg";function gt(e){let t=document.createElementNS(Bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function qt(e){return e<10000000000?e*1000:e}function rs(e){if(!e)return"";return new Date(qt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function os(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function _t(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Kt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=h("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!_t(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!_t(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(_t(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(bt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(bt(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=h("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let l=document.createElement("span");l.textContent=h("reply.action","Reply"),o.append(gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),l),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let m=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),c=document.createElement("span");c.className="bp-entry-time";let u=rs(e.at);if(t)c.textContent=u,i.append(s,...m?[o]:[],c);else{let p=n&&e.at?os(qt(e.at)-qt(n)):"",d=u?p?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:p}):h("web.chat.finished","Finished {time}",{time:u}):"";c.textContent=e.live?h("web.chat.streaming","Streaming…"):d,i.append(c,s,...m?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=h("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let c=document.createElement("div");c.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=a.tool.name,c.appendChild(u),a.tool.summary){let p=document.createElement("span");p.className="bp-tool-summary",p.textContent=a.tool.summary,c.appendChild(p)}r.appendChild(c),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let c=a.ask;if(c.kind==="plan"){r.appendChild(this.renderPlanAsk(c)),i.appendChild(r);continue}let u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${c.id}`);let p=document.createElement("div");if(p.className="bp-ask-q",p.textContent=c.question,u.appendChild(p),c.state==="open"){let d=document.createElement("div");if(d.className="bp-ask-opts",c.options&&c.options.length>0)for(let b of c.options){let y=document.createElement("button");y.type="button",y.textContent=b.label,y.addEventListener("click",()=>this.cb.onAnswerAsk(c.id,b.id)),d.appendChild(y)}else{let b=document.createElement("input");b.type="text",b.className="bp-input",b.placeholder=h("web.chat.answer.placeholder","Type answer…");let y=document.createElement("button");y.type="button",y.className="primary",y.textContent=h("web.chat.answer.btn","Answer"),y.addEventListener("click",()=>{if(b.value.trim())this.cb.onAnswerAsk(c.id,b.value.trim())}),d.append(b,y)}u.appendChild(d)}else{let d=document.createElement("div");d.className="bp-ask-answered",d.textContent=h("web.chat.answered","Answered: {answer}",{answer:c.answered??""}),u.appendChild(d)}r.appendChild(u),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),l=Boolean(a.images&&a.images.length>0),m=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!l&&!m&&!a.live)continue;if(a.replyTo?.quote){let c=document.createElement("div");c.className="bp-reply-quote",c.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let u=a.replyTo.id;c.setAttribute("role","button"),c.tabIndex=0,c.setAttribute("data-testid","entry-reply-quote");let p=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(u);else this.goTo(u)};c.addEventListener("click",p),c.addEventListener("keydown",(d)=>{if(d.key==="Enter"||d.key===" ")d.preventDefault(),p()}),r.appendChild(c)}if(o||a.live){let c=document.createElement("div");if(c.className="bp-entry-body",a.kind==="user")c.textContent=a.text;else c.appendChild(bt(a.text||""));if(a.live)this.liveNodes.set(a.id,c);r.appendChild(c)}if(m&&a.attachments){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.attachments)if(u.previewUrl){let p=document.createElement("img");p.className="bp-reply-img",p.src=u.previewUrl,p.alt=u.name||"attachment",c.appendChild(p)}else if(u.path||u.name){let p=document.createElement("span");p.className="bp-tool-pill",p.textContent=u.name||u.path||"image",c.appendChild(p)}if(c.childElementCount>0)r.appendChild(c)}if(a.images&&a.images.length>0){let c=document.createElement("div");c.className="bp-entry-images";for(let u of a.images){let p=document.createElement("img");p.className="bp-reply-img",p.alt=u;let d=`${a.id}|${u}`,b=this.imageCache.get(d);if(b)p.src=b;else this.cb.onLoadImage(a.id,u).then((y)=>{if(!y)return;let f=y.url??(y.mime&&y.data?`data:${y.mime};base64,${y.data}`:"");if(!f)return;this.imageCache.set(d,f),p.src=f});c.appendChild(p)}r.appendChild(c)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=gt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?h("ask.plan","Proposed plan"):xe(e.head),s.append(a,r),e.state==="open"){let c=document.createElement("span");c.className="bp-plan-badge",c.textContent=h("gpui.ask.plan.ready","Ready for review"),s.appendChild(c)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn";let u=h("common.copy","Copy"),p=document.createElement("span");p.textContent=u,c.append(gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),p),c.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{c.classList.add("copied"),p.textContent=h("web.clone.copied","Copied"),window.setTimeout(()=>{c.classList.remove("copied"),p.textContent=u},1200)}).catch(()=>{})}),s.appendChild(c)}let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn",l.setAttribute("data-testid","plan-expand"),l.textContent=t?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),l.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let c=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=c}),s.appendChild(l),i.appendChild(s);let m=document.createElement("div");if(m.className="bp-plan-body"+(t?" is-expanded":""),m.setAttribute("data-testid","plan-body"),m.appendChild(bt(e.question||"")),i.appendChild(m),e.state==="open"){let c=document.createElement("div");c.className="bp-plan-actions";let u=e.options?.find((y)=>y.id==="implement"||y.id.endsWith("|implement")),p=document.createElement("button");if(p.type="button",p.className="primary",p.setAttribute("data-testid","plan-implement"),p.textContent=u?.label&&u.label!=="Implement"?xe(u.label):h("approval.implement","Implement"),p.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),c.appendChild(p),e.revise!==!1){let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-btn"+(n?" active":""),y.setAttribute("data-testid","plan-revise"),y.append(gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),y.addEventListener("click",()=>{let f=this.planRevisingId!==e.id;this.planRevisingId=f?e.id:"";let g=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=g,f)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),c.appendChild(y)}let d=e.options?.find((y)=>y.id==="dismiss"||y.id.endsWith("|dismiss")),b=document.createElement("button");if(b.type="button",b.className="bp-plan-dismiss-btn",b.setAttribute("data-testid","plan-dismiss"),b.textContent=d?.label&&d.label!=="Dismiss"?xe(d.label):h("approval.dismiss","Dismiss"),b.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,d?.id??"dismiss")}),c.appendChild(b),i.appendChild(c),n){let y=document.createElement("div");y.className="bp-plan-revise",y.setAttribute("data-testid","plan-revise-drawer");let f=document.createElement("textarea");f.rows=2,f.className="bp-input bp-plan-revise-input",f.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),f.value=this.planReviseDrafts.get(e.id)??"";let g=document.createElement("button");g.type="button",g.className="bp-plan-revise-send",g.setAttribute("data-testid","plan-revise-send"),g.textContent=h("gpui.ask.plan.sendrev","Send revision"),g.disabled=f.value.trim().length===0;let E=()=>{let A=f.value.trim();if(!A)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${A}`)},x=()=>{this.closePlanRevise()};y.addEventListener("keydown",(A)=>{if(A.key==="Escape")A.preventDefault(),A.stopPropagation(),x()}),f.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,f.value),g.disabled=f.value.trim().length===0}),f.addEventListener("keydown",(A)=>{if(A.key==="Enter"&&!A.shiftKey)A.preventDefault(),E()}),g.addEventListener("click",E);let k=document.createElement("button");k.type="button",k.className="bp-btn-ghost",k.textContent=h("common.cancel","Cancel"),k.addEventListener("click",x),y.append(f,g,k),i.appendChild(y)}}else{let c=document.createElement("div");c.className="bp-ask-answered",c.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(c)}return i}}var In="http://www.w3.org/2000/svg",Rn=4,jn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Pt(e){let t=document.createElementNS(In,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(In,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function zt(){return Pt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Hn(){return Pt(["M6 4l14 8-14 8z"])}function ls(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Jt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=h("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Pt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Pt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(l)=>{let m=l.clipboardData?.items;if(!m)return;let c=[];for(let u=0;u0)l.preventDefault(),this.addFiles(c)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let m=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,m),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,m))%Math.max(1,m),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=ls(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?Hn():zt()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?Hn():zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let l=[r,o];if(t==="armed"||t==="planning"){let m=document.createElement("div");m.className="bp-plan-scopes";let c=(u,p,d,b)=>{let y=document.createElement("button");return y.type="button",y.className="bp-plan-scope-btn"+(p?" active":""),y.textContent=u,y.disabled=!this.enabled,y.setAttribute("data-testid",b),y.addEventListener("click",()=>this.cb.onSetPlanMode?.(d)),y};m.append(c(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),c(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),c(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),l.push(m)}this.planBarEl.replaceChildren(...l)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=h("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=h("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!jn.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Rn){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:Rn}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=h("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Dn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var cs=new Set(["bom","checks","life","plan","fab"]);function Nt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&cs.has(t.id))}function Un(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function Mt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function st(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function at(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var ds=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ps=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Vn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(ds.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ps.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function On(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${st(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${st(n)}`,tone:"warn"};return{text:st(n),tone:"ok"}}function Wn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function _n(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Yt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Tt(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function qn(e){return e.state==="routed"||e.state==="verified"}function Kn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function zn(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function Jn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function Yn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Xn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Xt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Zn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Zt(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Fn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],$n=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Qn(e){let t=2166136261;for(let n=0;n>>0;return t}function ft(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return Fn[Qn(i)%Fn.length]}function vt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return $n[Qn(e)%$n.length]}function ei(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),l=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:l,fitted:l,touched:!1}}function Je(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Bt(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ti(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function ni(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),l=Math.max(r,Math.min(o,e.scale*t)),[m,c]=Bt(e,n,i,s,a);return{...e,cx:m-(n-s*0.5)/l,cy:c-(i-a*0.5)/l,scale:l,touched:!0}}function ii(e){if(e.length===0)return null;if(e.length===1)return e[0];let t=0;for(let s=0;s+1=n&&a>0.000000001){let r=(n-i)/a;return[e[s][0]+(e[s+1][0]-e[s][0])*r,e[s][1]+(e[s+1][1]-e[s][1])*r]}i+=a}return e[e.length-1]}function si(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function Qt(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function ms(e,t,n,i,s,a){let r=s-n,o=a-i,l=r*r+o*o;if(l<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let m=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/l)),c=n+m*r,u=i+m*o;return(e-c)*(e-c)+(t-u)*(t-u)}function Gn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==m>t&&e<(l-r)*(t-o)/(m-o+0.000000000001)+r)i=!i}return i}function en(e,t){return Math.max(5,Math.min(32,e*t))}function It(e,t,n,i,s,a,r,o,l){if(i){for(let p of e){if(p.layer!==n||p.id!==i||p.locked)continue;let d=p.path??[];for(let b=0;b=3)for(let b=0;b=0;p--){let d=t[p];if(d.layer!==n)continue;let b=d.outline??[];if(!Gn(c,u,b))continue;if(!(d.holes??[]).some((f)=>Gn(c,u,f)))return{kind:"region",id:d.id}}return null}function rt(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((m)=>m.kind==="corridor").length,l=r.filter((m)=>m.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((l>0||a.role==="power"||a.role==="plane")&&(!n||l>n.count))n={count:l,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function ai(e,t,n,i,s){let a=new Set(s),r=[];for(let m of e){if(!m.r||!m.b||m.b.length!==4)continue;let[c,u]=Je(t,m.b[0],m.b[1],n,i),[p,d]=Je(t,m.b[2],m.b[3],n,i),b=Math.abs(p-c),y=Math.abs(d-u);if(b<13||y<9)continue;let f=(c+p)*0.5,g=(u+d)*0.5;if(f<8||f>n-8||g<8||g>i-8)continue;r.push({text:m.r,cx:f,cy:g,bw:m.r.length*5.8+4,bh:11,score:b*y+(a.has(m.r)?1e4:0)})}r.sort((m,c)=>c.score-m.score);let o=[],l=[];for(let m of r){let c=[m.cx-m.bw*0.5,m.cy-m.bh*0.5,m.cx+m.bw*0.5,m.cy+m.bh*0.5];if(!o.some((p)=>!(c[2]<=p[0]||c[0]>=p[2]||c[3]<=p[1]||c[1]>=p[3])))o.push(c),l.push({text:m.text,cx:m.cx,cy:m.cy})}return l}function ri(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function Rt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}function oi(e,t,n,i,s,a,r,o){return e===t&&n===i&&s===a&&(o===void 0||r>=o)}var li="#111917",us="#16201d",hs="rgba(212, 224, 219, 0.92)",bs="rgba(61, 80, 73, 0.72)",gs="rgba(82, 107, 97, 0.85)",fs="rgba(143, 163, 155, 0.88)",ci="#f59e0b",vs="#eef5f2",di="#ef4444";function ot(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function ys(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function ws(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function Es(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class tn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=Rt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??rt(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):rt(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ei(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-mini-btn",l.textContent="✓",l.title=h("gpui.mgmt.plan.layer","Approve layer"),l.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-mini-btn",m.textContent="✗",m.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),m.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,l,m);let c=document.createElement("div");c.className="bp-plan-card-sub",n.append(i,c);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let p=document.createElement("canvas");p.className="bp-plan-card-canvas",p.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let d=document.createElement("div");d.className="bp-plan-hover-hud bp-hidden",u.append(p,d);let b=document.createElement("div");b.className="bp-plan-legend bp-hidden",t.append(n,u,b);let y=p.getContext("2d"),f=new ResizeObserver(()=>this.scheduleDraw());f.observe(u),this.attachPointerListeners(p,e.layer);let g={layer:e.layer,el:t,canvas:p,ctx:y,legendEl:b,okBtn:l,noBtn:m,statusEl:o,titleEl:r,subtitleEl:c,hoverHudEl:d,ro:f};return this.syncCardHeaderAndLegend(g,e),g}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=Es(t);e.statusEl.className=`bp-plan-status-badge tone-${i.tone}`,e.statusEl.textContent=h(i.key,i.label);let s=(t.items??[]).some((r)=>r.state==="proposed"||r.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!s);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!s);let a=(this.state?.regions??[]).filter((r)=>r.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let r=document.createDocumentFragment();for(let o of a){let l=document.createElement("button");l.type="button";let m=this.state?.selectedId===o.id;l.className="bp-plan-legend-chip"+(m?" active":"");let c=document.createElement("span");c.className="bp-plan-legend-sw",c.style.background=ft(o.net||o.id,o.color||"");let u=document.createElement("span");u.textContent=o.net||o.id,l.append(c,u),l.addEventListener("click",()=>{this.cb.onSelect(o.id),this.cb.onFocusItem(o.id)}),r.appendChild(l)}e.legendEl.replaceChildren(r)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height),c=this.getCam(t,l,m),u=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o);if(i.button===2){if(u?.kind==="vertex"){let p=this.getItemPts(u.id,u.isPlane),d=Qt(p,u.idx,u.isPlane);if(d)this.selectedVertex=null,this.cb.onCommitFields(u.id,{[u.isPlane?"outline":"path"]:d})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},u?.kind==="vertex"){let p=this.getItemPts(u.id,u.isPlane),d=p.map((b)=>[b[0],b[1]]);this.selectedVertex={id:u.id,idx:u.idx},this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:u.idx,pts:p.map((b)=>[b[0],b[1]]),origPts:d,moved:!1},this.scheduleDraw()}else if(u?.kind==="midpoint"){let p=this.getItemPts(u.id,u.isPlane),d=p.map((f)=>[f[0],f[1]]),b=si(p,u.segIdx,u.pos,u.isPlane),y=u.isPlane&&u.segIdx+1>=p.length?b.length-1:Math.min(u.segIdx+1,b.length-1);this.selectedVertex={id:u.id,idx:y},this.patchLocalItem(u.id,u.isPlane,b),this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:y,pts:b,origPts:d,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,l=Math.max(1,a.width),m=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let k=this.getCam(t,l,m);this.setCam(t,ti(k,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let y=this.getCam(t,l,m),[f,g]=Bt(y,r,o,l,m),E=[Math.round(f*1000)/1000,Math.round(g*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let x=this.drag.pts.map((k)=>[k[0],k[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.scheduleDraw();return}let c=this.getCam(t,l,m),u=It(s.bands,s.regions,t,s.selectedId,c,l,m,r,o),p=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",d=this.hover?.hit.kind??"",b=u?u.id:"";if(this.hover=u?{layer:t,hit:u}:null,e.style.cursor=u?"pointer":"crosshair",p!==b||(u?.kind??"")!==d)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((a)=>[a[0],a[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),l=i.clientX-o.left,m=i.clientY-o.top,c=Math.max(1,o.width),u=Math.max(1,o.height),p=this.getCam(t,c,u),d=It(s.bands,s.regions,t,s.selectedId,p,c,u,l,m);if(d&&(d.kind==="band"||d.kind==="region")){this.cb.onSelect(d.id),this.cb.onFocusItem(d.id);return}if(!d&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),l=Math.max(1,s.height),m=this.getCam(t,o,l),c=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ni(m,c,a,r,o,l)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),l=Qt(o,this.selectedVertex.idx,r);if(l)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"outline":"path"]:l})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),l=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==l)n.canvas.width=o,n.canvas.height=l;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(d,b)=>Je(a,d,b,n,i);e.fillStyle=li,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((d)=>d.length>=3);if(e.fillStyle=us,o.length>0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),m=this.hover?.layer===t?this.hover.hit:null;for(let d of l){let b=d.outline??[];if(b.length<3)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ws(d.state||"proposed",y,f),E=ft(d.net||d.id,d.color||"");e.beginPath();for(let x=0;x0){e.beginPath();for(let d of o){for(let b=0;bd.layer===t),p=[];for(let d of u){for(let b of d.from??[])p.push(b);for(let b of d.to??[])p.push(b)}e.fillStyle=fs,e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let d of ai(c,a,n,i,p))e.fillText(d.text,d.cx,d.cy);for(let d of u){let b=d.guides??[];if(b.length===0)continue;let y=s.selectedId===d.id||m?.id===d.id,f=vt(d.name||d.id,d.color||"");e.strokeStyle=ot(f,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let g of b){let[E,x]=r(g[0],g[1]),[k,A]=r(g[2],g[3]);e.moveTo(E,x),e.lineTo(k,A)}e.stroke()}for(let d of u){let b=d.path??[];if(b.length<2)continue;let y=s.selectedId===d.id,f=m?.id===d.id,g=ys(d.state||"proposed",y,f),E=vt(d.name||d.id,d.color||""),x=en(d.width??1.5,a.scale),k=()=>{e.beginPath();for(let N=0;N0){let N=ii(b);if(N){let[M,D]=r(N[0],N[1]),W=String(A),_=Math.max(16,W.length*6.5+8),H=15;e.fillStyle="rgba(17, 25, 23, 0.94)",e.fillRect(M-_*0.5,D-7.5,_,15),e.lineWidth=1.2,e.strokeStyle=y?"#ffffff":E,e.strokeRect(M-_*0.5,D-7.5,_,15),e.fillStyle="#eef5f2",e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(W,M,D+0.5)}}}if(s.selectedId){let d=(b,y)=>{let f=y?b.length:Math.max(0,b.length-1);for(let g=0;gn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Nt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Nt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let l=this.openPanel===r.id;o.className="bp-mgmt-tab"+(l?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",l?"true":"false");let m=document.createElement("span");m.textContent=xe(r.label),o.appendChild(m);let c=this.getPanelData(r.id),u=Un(c);if(u){let p=document.createElement("span");p.className=`bp-mgmt-badge bp-tone-${u.tone}`,p.textContent=u.text,o.appendChild(p)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=h("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",h("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),a=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,a.appendChild(r)}switch(this.openPanel){case"bom":a.appendChild(this.renderBom());break;case"checks":a.appendChild(this.renderChecks());break;case"life":a.appendChild(this.renderLife());break;case"plan":a.appendChild(this.renderPlan());break;case"fab":a.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(a),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${at(t.cost)}/board`:`${at(t.cost)}/board`,i.appendChild(m)}if(t.paused){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent="Stock check paused",i.appendChild(m)}if(e.appendChild(i),t.stock_note){let m=document.createElement("div");m.className="bp-mgmt-note bp-mgmt-faint",m.textContent=xe(t.stock_note),e.appendChild(m)}let o=this.bomEditingId?n.find((m)=>m.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let m=document.createElement("div");m.className="bp-mgmt-filter-row";let c=document.createElement("input");c.type="text",c.className="bp-mgmt-filter",c.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",c.value=this.bomFilter,c.setAttribute("data-testid","mgmt-bom-filter"),c.addEventListener("input",()=>{this.bomFilter=c.value,this.renderBomRows(l,n)}),m.appendChild(c),e.appendChild(m)}let l=document.createElement("div");return l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(l,n),e.appendChild(l),e}renderBomRows(e,t){let n=Wn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let l=document.createElement("div");l.className="bp-mgmt-row-line";let m=document.createElement("span");if(m.className="bp-mgmt-strong bp-mgmt-flex1",m.textContent=Mt(r,24),l.appendChild(m),a.dnp){let y=document.createElement("span");y.className="bp-mgmt-pill",y.textContent=h("gpui.mgmt.bom.dnp","DNP"),l.appendChild(y)}else{let y=On(a.stock);if(y){let f=document.createElement("span");f.className=`bp-tone-${y.tone}`,f.textContent=y.text,l.appendChild(f)}}let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn",c.textContent="Edit",c.addEventListener("click",(y)=>{y.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),l.appendChild(c);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let p=[`${a.qty??r.length}×`,a.value??"",Vn(a.footprint??"")].filter(Boolean).join(" · "),d=document.createElement("span");d.className="bp-dim",d.textContent=p;let b=document.createElement("span");if(b.className="bp-mgmt-flex1",a.mpn)b.textContent=a.mpn;else if(i&&!a.dnp)b.className+=" bp-tone-warn",b.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(d,b),!a.dnp&&typeof a.stock?.price==="number"){let y=document.createElement("span");y.className="bp-dim",y.textContent=at(a.stock.price),u.appendChild(y)}if(!a.dnp&&a.stock?.class){let y=document.createElement("span");y.className="bp-mgmt-faint",y.textContent=xe(a.stock.class),u.appendChild(y)}o.append(l,u),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Mt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),l=async(p,d=!1)=>{let b=o();this.bomEditStatus="Writing…",this.render();try{let y=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!Xt(b,o()))return;this.bomLastUndo=!d&&(y.changed??0)>0?{project:p.project,editId:b.editId,refs:p.refs.slice(),field:p.field,was:typeof y.was==="string"?y.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=d?"Restored":(y.changed??0)===0?"No change":y.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(y){if(!Xt(b,o()))return;this.bomEditStatus=y instanceof Error?y.message:"Could not save edit"}this.render()},m=document.createElement("div");m.className="bp-mgmt-btn-row";let c=document.createElement("button");c.type="button",c.className="primary bp-mgmt-btn",c.textContent="Save MPN",c.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{l({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),m.append(c,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn",d.textContent="Undo",d.addEventListener("click",()=>{l(Zn(p),!0)}),m.appendChild(d)}if(t.append(i,r,m),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),a=(p)=>t.sources?.[p]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let p of i){let d=document.createElement("button");d.type="button",d.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),d.textContent=s(p)+(a(p)?" · judged":""),d.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),r.appendChild(d)}let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("button");if(m.type="button",m.className="bp-mgmt-btn",m.textContent=h("gpui.mgmt.checks.run","Run"),m.addEventListener("click",()=>{let p=this.watchGen,d=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:d}).then(()=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus="",this.render()}).catch((b)=>{if(p!==this.watchGen||d!==this.project)return;this.checksStatus=b instanceof Error?b.message:"Could not run checks",this.render()})}),r.append(l,m),e.appendChild(r),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-checks-rows");let u=_n(n,this.checksSource);if(u.length===0)c.appendChild(this.makeEmpty("No check findings."));else for(let p of u){let d=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",b=document.createElement("div");b.className="bp-mgmt-group-head";let y=document.createElement("span");y.className=`bp-mgmt-dot bp-tone-bg-${d}`;let f=document.createElement("span");f.className="bp-mgmt-flex1",f.textContent=`${s(p.source)} · ${p.rule}`;let g=document.createElement("span");g.className=`bp-tone-${d}`,g.textContent=String(p.n),b.append(y,f,g),c.appendChild(b);for(let E of p.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let k=document.createElement("div");if(k.textContent=xe(E.title??""),x.appendChild(k),E.names||this.checksSelectedId===E.id){let A=document.createElement("div");A.className="bp-mgmt-row-sub";let N=document.createElement("span");if(N.className="bp-dim bp-mgmt-flex1",N.textContent=E.names??"",A.appendChild(N),this.checksSelectedId===E.id){let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn accent",M.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),M.addEventListener("click",(D)=>{D.stopPropagation();let W={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:W.project,id:E.id}).then((_)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(W,H))return;if(_.text)this.cb.onSendText(_.text),this.checksStatus="Sent to agent",this.render()}).catch((_)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Zt(W,H))return;this.checksStatus=_ instanceof Error?_.message:"Could not send finding",this.render()})}),A.appendChild(M)}x.appendChild(A)}x.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),c.appendChild(x)}}return e.appendChild(c),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let l of["active","nrnd","eol"]){let m=i[l]??0,c=Yt(l),u=document.createElement("span");u.className=m>0?`bp-tone-${c.tone}`:"bp-mgmt-faint",u.textContent=`${c.label} ${m}`,n.appendChild(u)}if((i.unknown??0)>0){let l=document.createElement("span");l.className="bp-mgmt-faint",l.textContent=`${i.unknown} unknown`,n.appendChild(l)}if(t.since){let l=document.createElement("span");l.className="bp-mgmt-flex1";let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=`since ${Tt(t.since)} (${t.samples??0})`,n.append(l,m)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let l=a[a.length-1],m=r[r.length-1],c=document.createElement("div");c.className="bp-mgmt-note bp-dim",c.textContent=`Parts/board: ${at(l[1])} · ${Math.round(m?.[1]??0)}/${o} lines in stock (${Tt(l[0])})`,s.appendChild(c)}for(let l of t.parts??[]){let m=this.lifeSelectedKey===l.key,c=Yt(l.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(m?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let d=document.createElement("span");d.className="bp-mgmt-strong",d.textContent=Mt(l.refs??[],14);let b=document.createElement("span");b.className="bp-mgmt-flex1 bp-dim",b.textContent=l.mpn||l.key;let y=document.createElement("span");if(y.className=`bp-tone-${c.tone}`,y.textContent=c.label,p.append(d,b,y),typeof l.stock==="number"){let f=document.createElement("span");f.className="bp-dim",f.textContent=st(l.stock),p.appendChild(f)}if(u.appendChild(p),m){let f=document.createElement("div");if(f.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)f.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];f.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Tt(g.at):""}`+(typeof g.stock==="number"?` · stock ${st(g.stock)}`:"")+(typeof g.price==="number"?` · ${at(g.price)}`:"")}else f.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(f)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===l.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=l.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:l.key}).then((f)=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(f.samples)?f.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==l.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(C,S)=>{let R=this.watchGen,Y=this.project;this.planStatus="",this.cb.hub.rpc(C,{pro:Y,...S}).catch((T)=>{if(R!==this.watchGen||Y!==this.project)return;this.planOptimistic.clear(),this.planStatus=T instanceof Error?T.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let C=this.watchGen,S=++this.planHydrateGen,R=this.project,Y=t.revision??0;this.cb.hub.rpc("plan.get",{pro:R,board:!0}).then((T)=>{let J=ri(T);if(!J)return;let K=typeof J.revision==="number"?J.revision:Y;if(!oi(C,this.watchGen,S,this.planHydrateGen,R,this.project,K,this.planHydratedRev))return;this.planHydratedRev=K,this.planHydratedKey=`${R}:${K}`,this.planHydratedBoard=J.board??null,this.planHydratedDraw=J.draw??null,this.render()}).catch(()=>{})}let s=document.createElement("div");s.className="bp-plan-toggle";let a=t.on===!0,r=document.createElement("span");r.className="bp-mgmt-flex1 bp-mgmt-strong",r.textContent=h("gpui.mgmt.plan.before","Plan before routing"),r.title=a?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.");let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn bp-plan-chip-btn"+(a?" active":""),o.setAttribute("data-testid","mgmt-plan-on"),o.setAttribute("aria-pressed",a?"true":"false"),o.textContent=h("gpui.bots.recall.on","On"),o.addEventListener("click",()=>n("plan.enable",{on:!0}));let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn bp-plan-chip-btn"+(!a?" active":""),l.setAttribute("data-testid","mgmt-plan-off"),l.setAttribute("aria-pressed",!a?"true":"false"),l.textContent=h("gpui.bots.recall.off","Off"),l.addEventListener("click",()=>n("plan.enable",{on:!1})),s.append(r,o,l),e.appendChild(s);for(let C of t.elsewhere??[]){let S=document.createElement("div");S.className="bp-plan-elsewhere";let R=document.createElement("span");R.className="bp-tone-warn bp-mgmt-flex1",R.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:C.name||C.rel||""}),S.appendChild(R),e.appendChild(S)}if(t.empty){let C=document.createElement("div");C.className="bp-mgmt-note";let S=document.createElement("div");S.className="bp-dim",S.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let R=document.createElement("div");return R.className="bp-mgmt-faint",R.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),C.append(S,R),e.appendChild(C),e}let m=t.awaiting??0,c=t.blocked??0,u=t.done??0,p=t.total??0,d=t.revision??0,b=zn(t),y=Jn(t),f=y.reduce((C,S)=>C+S.count,0),g=document.createElement("div");g.className="bp-plan-status";let E=document.createElement("div");E.className="bp-plan-status-top";let x=document.createElement("span");if(x.className=`bp-plan-status-badge tone-${b.tone}`,x.textContent=h(b.key,b.label),E.appendChild(x),d>0){let C=document.createElement("span");C.className="bp-dim",C.textContent=`v${d}`,E.appendChild(C)}let k=document.createElement("span");if(k.className="bp-mgmt-flex1 "+(m>0?"bp-tone-warn":c>0?"bp-tone-bad":"bp-dim"),k.textContent=p>0?`${u}/${p} ${h("gpui.mgmt.plan.done","done")}`:m>0?h("web.plan.awaiting","{n} awaiting approval",{n:m}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),E.appendChild(k),!t.live){let C=document.createElement("span");C.className="bp-mgmt-pill",C.textContent=h("gpui.mgmt.plan.saved","saved plan"),E.appendChild(C)}if(g.appendChild(E),f>0){let C=document.createElement("div");C.className="bp-plan-segbar";for(let S of y){if(S.count<=0)continue;let R=document.createElement("div");R.className=`bp-plan-seg bp-tone-bg-${S.tone}`,R.style.flexGrow=String(S.count),C.appendChild(R)}g.appendChild(C)}e.appendChild(g);let A=document.createElement("div");if(A.className="bp-mgmt-head",m>0){let C=document.createElement("button");C.type="button",C.className="primary bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-approve-all"),C.textContent=h("gpui.mgmt.plan.all","Approve all"),C.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(C)}if(t.routing){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-stop"),C.textContent=h("gpui.mgmt.plan.stop","Stop routing"),C.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(C)}if(t.live&&u>0){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-verify"),C.textContent=h("gpui.mgmt.plan.verify","Verify"),C.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(C)}let N=document.createElement("span");N.className="bp-mgmt-flex1";let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.setAttribute("data-testid","mgmt-plan-hide"),M.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),M.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.append(N,M),e.appendChild(A);let D=Array.isArray(t.asks)?t.asks:[];if(D.length>0){let C=D.map((J)=>J.what||"").filter(Boolean).join(", "),S=D[0]?.note||"",R=document.createElement("div");R.className="bp-plan-elsewhere";let Y=document.createElement("div");Y.className="bp-plan-ask-col";let T=document.createElement("div");if(T.className="bp-tone-warn",T.textContent=C?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:C}):h("gpui.mgmt.plan.reqplain","Approval requested"),Y.appendChild(T),S){let J=document.createElement("div");J.className="bp-dim",J.textContent=S,Y.appendChild(J)}R.appendChild(Y),e.appendChild(R)}if(this.planStatus){let C=document.createElement("div");C.className="bp-mgmt-note bp-plan-err bp-tone-bad";let S=document.createElement("span");S.className="bp-mgmt-flex1",S.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):xe(this.planStatus);let R=document.createElement("button");R.type="button",R.className="icon",R.textContent="×",R.title=h("common.close","Close"),R.addEventListener("click",()=>{this.planStatus="",this.render()}),C.append(S,R),e.appendChild(C)}if(t.keys_note){let C=document.createElement("div");C.className="bp-mgmt-note bp-dim";let S="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";C.textContent=t.keys_note===S?h("gpui.mgmt.plan.keysnote",S):xe(t.keys_note),e.appendChild(C)}let W=t.stackup_summary??"",_=Array.isArray(t.impedances)?t.impedances:[];if(W||_.length>0){let C=document.createElement("div");C.className="bp-plan-stackup";let S=document.createElement("button");S.type="button",S.className="bp-plan-stackup-head",S.setAttribute("data-testid","mgmt-plan-stackup-toggle"),S.setAttribute("aria-expanded",this.planStackupOpen?"true":"false");let R=document.createElement("span");R.className="bp-plan-chev",R.textContent=this.planStackupOpen?"▾":"▸";let Y=document.createElement("span");if(Y.textContent=h("gpui.mgmt.plan.stackup","Stackup & impedances"),S.append(R,Y),S.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),C.appendChild(S),this.planStackupOpen){let T=document.createElement("div");if(T.className="bp-plan-stackup-body",T.setAttribute("data-testid","mgmt-plan-stackup-body"),W){let J=document.createElement("div");J.className="bp-dim",J.textContent=W,T.appendChild(J)}for(let J of _){let K=document.createElement("div");K.className="bp-mgmt-faint",K.textContent=`· ${J}`,T.appendChild(K)}C.appendChild(T)}e.appendChild(C)}let H=(C,S,R,Y)=>{let T=document.createElement("button");return T.type="button",T.className="bp-mgmt-btn bp-plan-chip-btn"+(S?" active":""),T.setAttribute("data-testid",R),T.setAttribute("aria-pressed",S?"true":"false"),T.textContent=C,T.addEventListener("click",Y),T},he=document.createElement("div");if(he.className="bp-plan-viewbar",he.append(H(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),H(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),H(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let C=document.createElement("span");C.className="bp-plan-sep";let S=document.createElement("span");S.className="bp-plan-sep";let R=document.createElement("button");R.type="button",R.className="bp-mgmt-btn bp-plan-mini-btn",R.setAttribute("data-testid","mgmt-plan-fit"),R.textContent=h("gpui.mgmt.plan.fit","Fit"),R.addEventListener("click",()=>this.planCanvas?.fitAll()),he.append(C,H(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),H(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),H(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),S,H(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),R)}let me=document.createElement("span");me.className="bp-mgmt-flex1";let se=document.createElement("button");se.type="button",se.className="bp-mgmt-btn bp-plan-mini-btn",se.setAttribute("data-testid","mgmt-plan-expand"),se.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),se.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),he.append(me,se),e.appendChild(he);let ye=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),Le=ye&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},Ae=ye&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(Ae.bands??[]).map((C)=>{let S=this.planOptimistic.get(C.id);if(!S)return{...C};return{...C,...S,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Be=(Ae.regions??[]).map((C)=>{let S=this.planOptimistic.get(C.id);if(!S)return{...C};return{...C,...S,edited:!0,state:C.state==="proposed"?"edited":C.state}}),B=[],pe=(t.layers??[]).map((C)=>{let S=[];for(let R of C.items??[]){let Y=this.planOptimistic.get(R.id);if(!Y){S.push(R);continue}let T={...R,width:typeof Y.width==="number"?Y.width:R.width,locked:typeof Y.locked==="boolean"?Y.locked:R.locked,edited:!0,state:R.state==="proposed"?"edited":R.state};if(typeof Y.layer==="string"&&Y.layer!==C.layer)B.push({target:Y.layer,item:T});else S.push(T)}return{...C,items:S}});for(let C of B){let S=pe.find((R)=>R.layer===C.target);if(S)S.items=[...S.items??[],C.item]}let ne=Rt(pe,t.copper_layers),Z=this.planGridMode==="all"?ne.map((C)=>C.layer):this.planGridMode==="single"?[this.planShownLayers.find((C)=>ne.some((S)=>S.layer===C))??rt(ne)[0]??ne[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((C)=>ne.some((S)=>S.layer===C))?this.planShownLayers.slice(0,2):rt(ne);if(this.planViewMode!=="list"&&ne.length>1){let C=document.createElement("div");C.className="bp-plan-layerbar";for(let S of ne){let R=Z.includes(S.layer);C.appendChild(H(S.title||S.layer,R,`mgmt-plan-layerpill-${S.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"){if(!Z.includes(S.layer))this.planShownLayers=Z.length>=2?[Z[0],S.layer]:[...Z,S.layer]}else this.planGridMode="single",this.planShownLayers=[S.layer];this.render()}))}e.appendChild(C)}let le=(C,S)=>{let R=this.planOptimistic.get(C)??{};if(this.planOptimistic.set(C,{...R,...S}),typeof S.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[S.layer];else if(this.planGridMode==="pair"&&!Z.includes(S.layer))this.planShownLayers=Z.length>=2?[Z[0],S.layer]:[...Z,S.layer]}let Y=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:C,fields:S}],...Y!==void 0?{base:Y}:{}})};if(this.planCommitFields=le,this.planSelectedId){let C="",S=null;for(let R of pe){let Y=(R.items??[]).find((T)=>T.id===this.planSelectedId);if(Y){C=R.layer,S=Y;break}}if(S){let R=document.createElement("div");R.className="bp-plan-inspector",R.setAttribute("data-testid","mgmt-plan-inspector");let Y=document.createElement("div");Y.className="bp-plan-ins-row";let T=document.createElement("span");T.className="bp-plan-ins-sw",T.style.background=S.kind==="corridor"?vt(S.name||S.id,S.color||""):ft(S.name||S.id,S.color||"");let J=document.createElement("span");J.className="bp-mgmt-strong",J.textContent=S.name||S.id;let K=document.createElement("span");if(K.className="bp-dim",K.textContent=C,Y.append(T,J,K),S.edited||S.state==="edited"){let be=document.createElement("span");be.className="bp-plan-ins-pill warn",be.textContent=h("gpui.mgmt.plan.edited","Edited"),Y.appendChild(be)}if(S.locked){let be=document.createElement("span");be.className="bp-plan-ins-pill",be.textContent=h("gpui.mgmt.plan.locked","Locked"),Y.appendChild(be)}let Me=document.createElement("span");Me.className="bp-mgmt-flex1",Y.appendChild(Me);let re=document.createElement("button");if(re.type="button",re.className="bp-mgmt-btn bp-plan-mini-btn",re.setAttribute("data-testid","mgmt-plan-lock"),re.textContent=S.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),re.addEventListener("click",()=>le(S.id,{locked:!S.locked})),Y.appendChild(re),S.state==="proposed"||S.state==="edited"){let be=document.createElement("button");be.type="button",be.className="primary bp-mgmt-btn bp-plan-mini-btn",be.textContent=h("android.hub.machines.approve","Approve"),be.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!0}));let de=document.createElement("button");de.type="button",de.className="bp-mgmt-btn bp-plan-mini-btn",de.textContent=h("gpui.mgmt.plan.reject","Reject"),de.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[S.id],approve:!1})),Y.append(be,de)}let ke=document.createElement("button");ke.type="button",ke.className="bp-mgmt-btn bp-plan-mini-btn",ke.setAttribute("data-testid","mgmt-plan-note-toggle"),ke.textContent=h("gpui.mgmt.plan.addnote","Add note"),ke.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let He=document.createElement("button");if(He.type="button",He.className="icon",He.textContent="×",He.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.render()}),Y.append(ke,He),R.appendChild(Y),!S.locked){let be=document.createElement("div");if(be.className="bp-plan-ins-row",S.kind==="corridor"){let ue=typeof S.width==="number"?S.width:1.5,Re=document.createElement("span");Re.className="bp-dim",Re.textContent=h("gpui.mgmt.plan.width","Width");let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn bp-plan-mini-btn",X.setAttribute("data-testid","mgmt-plan-w-down"),X.textContent="-",X.addEventListener("click",()=>{let Ke=Math.round(Math.max(0.15,ue-0.25)*100)/100;le(S.id,{width:Ke})});let oe=document.createElement("span");oe.className="bp-plan-ins-val",oe.textContent=`${ue.toFixed(2)}mm`;let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn bp-plan-mini-btn",je.setAttribute("data-testid","mgmt-plan-w-up"),je.textContent="+",je.addEventListener("click",()=>{let Ke=Math.round(Math.min(25,ue+0.25)*100)/100;le(S.id,{width:Ke})});let We=document.createElement("span");We.className="bp-plan-sep",be.append(Re,X,oe,je,We)}let de=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ue)=>ue.layer):pe.map((ue)=>ue.layer);if(de.length>0){let ue=document.createElement("span");ue.className="bp-dim",ue.textContent=h("gpui.mgmt.plan.layer.move","Move to layer"),be.appendChild(ue);for(let Re of de)be.appendChild(H(Re,Re===C,`mgmt-plan-move-${Re}`,()=>{if(Re!==C)le(S.id,{layer:Re})}))}R.appendChild(be)}if(this.planNoteOpen){let be=document.createElement("form");be.className="bp-plan-note-form";let de=document.createElement("input");de.type="text",de.className="bp-plan-note-input",de.setAttribute("data-testid","mgmt-plan-note-input"),de.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let ue=document.createElement("button");ue.type="submit",ue.className="primary bp-mgmt-btn bp-plan-mini-btn",ue.setAttribute("data-testid","mgmt-plan-note-submit"),ue.textContent=h("gpui.mgmt.plan.addnote","Add note"),be.append(de,ue),be.addEventListener("submit",(Re)=>{Re.preventDefault();let X=de.value.trim();if(!X)return;de.value="",this.planNoteOpen=!1;let oe=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:S.id,text:X}],...oe!==void 0?{base:oe}:{}})}),R.appendChild(be)}if(this.planViewMode!=="list"&&!S.locked){let be=document.createElement("div");be.className="bp-plan-hint",be.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),R.appendChild(be)}e.appendChild(R)}}let j=document.createElement("div");j.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),j.setAttribute("data-testid","mgmt-plan-rows");let z=h("gpui.mgmt.plan.done","done");for(let C of pe){let S=C.items??[],R=document.createElement("div");R.className="bp-mgmt-group-head bp-plan-layer-head";let Y=document.createElement("div");Y.className="bp-mgmt-row-line";let T=document.createElement("span");T.className="bp-mgmt-strong",T.textContent=C.layer;let J=document.createElement("span");if(J.className="bp-dim bp-mgmt-flex1",J.textContent=`${C.role?`${C.role} · `:""}${C.done??0}/${S.length} ${z}`,Y.append(T,J),C.status!=="approved"&&S.length>0){let K=document.createElement("button");K.type="button",K.className="bp-mgmt-btn",K.textContent=h("gpui.mgmt.plan.layer","Approve layer"),K.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!0}));let Me=document.createElement("button");Me.type="button",Me.className="bp-mgmt-btn",Me.textContent=h("gpui.mgmt.plan.reject","Reject"),Me.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!1})),Y.append(K,Me)}if(R.appendChild(Y),C.stackup){let K=document.createElement("div");K.className="bp-plan-layer-stackup",K.textContent=C.stackup,R.appendChild(K)}j.appendChild(R);for(let K of S){if(this.planHideDone&&qn(K))continue;let Me=this.planSelectedId===K.id,re=document.createElement("div");re.className="bp-mgmt-row bp-plan-row"+(Me?" active":""),re.setAttribute("data-testid",`mgmt-plan-row-${K.id}`);let ke=document.createElement("div");ke.className="bp-mgmt-row-line";let He=document.createElement("span");He.className=`bp-plan-swatch bp-plan-st-${K.state||"proposed"}`,He.style.setProperty("--swatch-color",K.color||"#8a8a8a");let be=document.createElement("span");be.className="bp-mgmt-flex1"+(K.state==="blocked"||K.state==="failed"?" bp-tone-bad":K.state==="edited"?" bp-tone-warn":K.state==="rejected"||K.state==="routed"||K.state==="verified"?" bp-dim":""),be.textContent=`${K.name||K.id}${K.locked?" \uD83D\uDD12":""}`;let de=[];if(K.kind==="plane"){if(K.reference)de.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:K.reference}))}else{let X=K.nets??0;de.push(X===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:X}))}if(typeof K.width==="number"&&Number.isFinite(K.width))de.push(`${K.width.toFixed(2)}mm`);if(K.impedance)de.push(K.impedance);let ue=de.join(" · "),Re=document.createElement("span");if(Re.className="bp-plan-mark "+(K.state==="blocked"||K.state==="failed"?"bp-tone-bad":K.state==="verified"||K.state==="routed"?"bp-tone-ok":K.state==="approved"?"bp-tone-accent":"bp-dim"),Re.textContent=Kn(K),ke.append(He,be,Re),K.state==="proposed"||K.state==="edited"){let X=document.createElement("button");X.type="button",X.className="bp-mgmt-btn",X.textContent="✓",X.title=h("gpui.mgmt.plan.layer","Approve layer"),X.addEventListener("click",(je)=>{je.stopPropagation(),n("plan.approve",{layer:"",ids:[K.id],approve:!0})});let oe=document.createElement("button");oe.type="button",oe.className="bp-mgmt-btn",oe.textContent="✗",oe.title=h("gpui.mgmt.plan.reject","Reject"),oe.addEventListener("click",(je)=>{je.stopPropagation(),n("plan.approve",{layer:"",ids:[K.id],approve:!1})}),ke.append(X,oe)}if(re.appendChild(ke),ue){let X=document.createElement("div");X.className="bp-mgmt-row-sub bp-plan-detail bp-dim",X.textContent=ue,re.appendChild(X)}if(K.state==="routing"&&typeof K.total==="number"&&K.total>0){let X=document.createElement("div");X.className="bp-plan-microbar";let oe=document.createElement("div");oe.className="bp-plan-microbar-fill";let je=Math.max(0,Math.min(100,Math.round((K.routed??0)/K.total*100)));oe.style.width=`${je}%`,X.appendChild(oe),re.appendChild(X)}if(K.problem_text){let X=document.createElement("div");X.className="bp-plan-problem",X.textContent=K.problem_text,re.appendChild(X)}re.addEventListener("click",()=>{this.planSelectedId=K.id,n("plan.focus",{id:K.id}),this.render()}),j.appendChild(re)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new tn({onSelect:(Y)=>{if(this.planSelectedId=Y,!Y)this.planNoteOpen=!1;this.render()},onFocusItem:(Y)=>{n("plan.focus",{id:Y})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(Y,T)=>{(this.planCommitFields??le)(Y,T)},onApproveLayer:(Y,T)=>{n("plan.approve",{layer:Y,ids:[],approve:T})},onQuickApprove:(Y,T)=>{n("plan.approve",{layer:"",ids:Y,approve:T})}});let C=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,S=this.planExpanded||this.panelEl.clientWidth>=540||C;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:Z,selectedId:this.planSelectedId,board:Le,bands:we,regions:Be,layers:ne,copperLayers:t.copper_layers},S);let R=document.createElement("div");R.className="bp-plan-canvas-scroll",R.appendChild(this.planCanvas.root),e.appendChild(R)}if(this.planViewMode!=="canvas")e.appendChild(j);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let C=document.createElement("div");C.className="bp-plan-footer",C.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(C)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,x={})=>{let k=this.watchGen,A=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:A,action:E,...x}).catch((N)=>{if(k!==this.watchGen||A!==this.project)return;this.fabStatus=N instanceof Error?N.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Xn(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=h("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let l=t.review,m=document.createElement("div");m.className="bp-mgmt-row";let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span"),p=(l?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),u.textContent=l?.running?"Reviewing the design…":l?.at==null?"No design review yet":`${l.counts?.error??0} must-fix · ${l.counts?.warning??0} should-fix · ${l.counts?.info??0} notes${l.scope?` (${l.scope})`:""}`,c.appendChild(u),l?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),c.appendChild(E)}if(!l?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),c.appendChild(E)}if(l?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=h("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(l.judge)this.cb.onSendText(l.judge)}),c.appendChild(E)}m.appendChild(c),o.appendChild(m);let d=Yn(t.drc?.state??""),b=document.createElement("div");b.className="bp-mgmt-row";let y=document.createElement("div");y.className="bp-mgmt-row-line";let f=document.createElement("span");if(f.className="bp-mgmt-flex1 "+(d.button?"bp-tone-warn":"bp-dim"),f.textContent=d.text,y.appendChild(f),d.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=d.button,E.addEventListener("click",()=>n("drc")),y.appendChild(E)}b.appendChild(y),o.appendChild(b);for(let E of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=E,o.appendChild(x)}for(let E of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=h("gpui.mgmt.fab.apply","Apply"),N.addEventListener("click",()=>n("apply",{key:E.key})),k.append(A,N),x.appendChild(k),o.appendChild(x)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let k=t.stackup.by==="proposed",A=document.createElement("span");if(A.className="bp-mgmt-flex1 "+(k?"bp-tone-warn":"bp-dim"),A.textContent=`${k?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(A),k){let N=t.stackup.chosen,M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=h("gpui.mgmt.fab.use","Use"),M.addEventListener("click",()=>n("stackup",{id:N})),x.appendChild(M)}E.appendChild(x),o.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let k=document.createElement("span");k.className="bp-mgmt-flex1 bp-tone-warn",k.textContent=h("gpui.mgmt.fab.changed","Changed since you last looked");let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=h("gpui.mgmt.fab.seen","Seen"),A.addEventListener("click",()=>n("seen")),x.append(k,A),E.appendChild(x);for(let N of t.changed.slice(0,12)){let M=document.createElement("div");M.className="bp-mgmt-faint",M.textContent=N,E.appendChild(M)}o.appendChild(E)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=h("gpui.mgmt.fab.limit","Limit");let k=document.createElement("span");k.className="bp-mgmt-col",k.textContent=h("gpui.mgmt.fab.free","Base price");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=h("gpui.mgmt.fab.extra","Costs more");let N=document.createElement("span");N.className="bp-mgmt-col bp-mgmt-col-read",N.textContent=h("gpui.mgmt.fab.readcol","Read"),E.append(x,k,A,N),o.appendChild(E);for(let D of g){let W=document.createElement("div");W.className="bp-mgmt-row";let _=document.createElement("div");_.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(D.changed?" bp-tone-warn":D.inherited?" bp-dim":""),H.textContent=`${D.changed?"• ":""}${D.label??""}`;let he=document.createElement("span");he.className="bp-mgmt-col",he.textContent=D.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=D.extra?.text||"—";let se=D.free&&typeof D.free==="object"?D.free:D.extra,ye=se?.fetched??"",Le=Boolean(ye)&&se?.confidence!=="published",Ae=ye?Le?`${ye}*`:ye:"—",we=se?.source??"",Be;if(we.startsWith("https://")&&ye){let B=document.createElement("a");B.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",B.href=we,B.target="_blank",B.rel="noopener noreferrer",B.textContent=Ae,Be=B}else{let B=document.createElement("span");B.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",B.textContent=Ae,Be=B}_.append(H,he,me,Be),W.appendChild(_),o.appendChild(W)}let M=document.createElement("div");M.className="bp-mgmt-note bp-mgmt-faint",M.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(M)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var xs={trs:(e)=>e,t:(e,t)=>t},Cs=new Set(["/settle"]);function pi(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function ui(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function hi(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function bi(e,t=xs){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let l=Cs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:l}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:l,want:m}=mi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:l,want:m,dotClass:ui(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function gi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,l=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let b of i)p.set(b.id,b.title||b.id);let d=new Set;for(let b of l)if(b.action.type==="thread")d.add(b.action.id);for(let b of n.threads){if(!b.id||d.has(b.id))continue;d.add(b.id);let{urgency:y,want:f}=mi(b);l.push({label:b.title||"Untitled thread",place:b.project?p.get(b.project)??"":"",kind:"thread",urgency:y,want:f,dotClass:ui(b),action:{type:"thread",id:b.id}})}}let m=[];for(let p=0;p0)m.push({score:f,index:p,item:d})}m.sort((p,d)=>{if(o){let f=(d.item.urgency??0)-(p.item.urgency??0);if(f!==0)return f}if(d.score!==p.score)return d.score-p.score;let b=p.item.kind==="thread"?0:1,y=d.item.kind==="thread"?0:1;if(b!==y)return b-y;return p.index-d.index});let c=new Set,u=[];for(let p of m){let d=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(c.has(d))continue;if(c.add(d),u.push(p.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=bi(t,{t:h,trs:xe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=gi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)m.appendChild(document.createTextNode(o.label.slice(0,p)));let b=document.createElement("strong");if(b.className="bp-palette-mark",b.textContent=o.label.slice(p,d),m.appendChild(b),d{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),l.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=l;s.appendChild(l)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var Ss=new Set(["resume","raise","retry","move","signin"]);function yi(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function jt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Ss.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function wi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class rn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${h("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let m=document.createElement("section");m.className="bp-set-section",m.setAttribute("data-testid","settings-home");let c=document.createElement("div");c.className="bp-set-head",c.textContent=h("home.machine","Home machine");let u=document.createElement("div");u.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div"),b=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";d.textContent=b,p.appendChild(d);let y=document.createElement("div");if(y.className="bp-dim",t.moving?.state==="moving")y.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")y.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)y.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else y.textContent="Online";if(p.appendChild(y),u.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=h("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),u.appendChild(f)}m.append(c,u),e.appendChild(m)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=h("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let l=document.createElement("div");l.className="bp-set-head",l.textContent="Paired devices",o.appendChild(l);try{let m=await this.cb.onLoadDevices();if(m.length===0){let c=document.createElement("div");c.className="bp-dim",c.textContent="No devices listed.",o.appendChild(c)}else for(let c of m){let u=document.createElement("div");u.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let d=document.createElement("div");if(d.textContent=c.title||c.head||"",p.appendChild(d),c.text||c.detail){let b=document.createElement("div");b.className="bp-dim",b.textContent=c.text||c.detail||"",p.appendChild(b)}if(u.appendChild(p),c.buttons?.length){let b=document.createElement("div");b.className="bp-set-btns";for(let y of c.buttons){let f=document.createElement("button");if(f.type="button",y.primary)f.className="primary";if(y.danger)f.className="primary stop";f.textContent=y.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(y.action,y.value).finally(()=>{this.refresh()})}),b.appendChild(f)}u.appendChild(b)}o.appendChild(u)}}catch(m){let c=document.createElement("div");c.className="bp-dim";let u=m instanceof Error&&m.message?m.message:"Not available from a browser";c.textContent=`${u} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(c)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function Ce(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function yt(e,t,n=!1){let i=Ce("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function on(e){return Ce("pre","bp-context-code",e)}function Ls(e){return Ce("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,xe(e))}function Ht(e,t){let n=Ce("div","bp-context-row");return n.append(Ce("strong",void 0,e),Ls(t)),n}class ln{fetchContext;dialog=Ce("dialog","bp-context");title=Ce("h2");cwd=Ce("div","bp-context-path");tabs=Ce("div","bp-context-tabs");body=Ce("div","bp-context-body");notice=Ce("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ce("div","bp-context-head"),i=Ce("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,yt(h("common.refresh","Refresh"),()=>{this.load()}),yt(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=yt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ce("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ce("details","bp-context-card"),i=Ce("summary");if(i.append(Ht(t.path,t.status),Ce("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,on(t.preview)),t.note)n.append(Ce("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ce("div","bp-context-row"),n=yt(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ce("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ce("h3",void 0,i),on(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ce("h3",void 0,xe(t)));for(let i of n){let s=Ce("article","bp-context-card");s.append(Ht(i.name,i.status),Ce("p",void 0,i.description),Ce("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ce("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ce("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ce("article","bp-context-card");n.append(Ht(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Ht(s.name,s.status),on(a)),s.cwd)n.append(Ce("small","bp-context-path",s.cwd))}if(t.error)n.append(Ce("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),a=yt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ce("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var Ei="http://www.w3.org/2000/svg";function xi(){let e=document.createElementNS(Ei,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ei,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function As(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ci(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class cn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let l=document.createElement("button");l.type="button",l.className="icon bp-side-add",l.textContent="+",l.title=h("thread.new","New thread"),l.setAttribute("aria-label",h("thread.new","New thread")),l.setAttribute("data-testid","sidebar-new-thread"),l.addEventListener("click",()=>{let c=this.firstProjectId();if(c)this.cb.onNewThread(c)}),r.append(this.filterInput,l),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let m=document.createElement("div");m.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),m.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,m)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),n.appendChild(u)}let i=document.createElement("span");i.className=`bp-dot ${As(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let u=document.createElement("span");if(u.className="bp-badge-need",u.textContent=e.want==="approval"?"!":"•",e.say)u.title=e.say;n.appendChild(u)}else if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");n.appendChild(u)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?yi(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let m=document.createElement("span");m.className="bp-need-line",m.textContent=r.line,m.title=r.line,l.appendChild(m);for(let u of r.actions){if(!jt(u,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=u.label,p.setAttribute("data-testid",`need-${u.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(d)=>{d.stopPropagation();let b=this.cb.onNeedAct;if(!b)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),b(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(p)}o.append(n,l);let c=this.needErr.get(e.id);if(c){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=c,o.appendChild(u)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let l of o.threads??[])i.add(l.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((c)=>{if(!t)return!0;return`${c.title} ${c.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let l=document.createElement("section");l.className="bp-side-section",l.setAttribute("data-section-id",r.id);let m=document.createElement("div");m.className="bp-side-section-head",m.textContent=r.title.toUpperCase(),l.appendChild(m);for(let c of o)l.appendChild(this.renderSectionThreadRow(c,!1));e.appendChild(l);continue}if(r.kind==="projects"){let o=r.rows.filter((c)=>{if(!t)return!0;if((c.title||c.id).toLowerCase().includes(t))return!0;if((c.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((c.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),l=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!l&&r.id!=="active"&&o.length===0)continue;let m=document.createElement("section");if(m.className="bp-side-section",m.setAttribute("data-section-id",r.id),l){let c=document.createElement("button");c.type="button",c.className="bp-side-section-head bp-side-section-toggle";let u=r.count??o.length,p=r.open?"▾":"▸";if(c.textContent=`${r.title.toUpperCase()} (${u}) ${p}`,r.hint)c.title=r.hint;c.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),m.appendChild(c)}else m.appendChild(this.projectsHead(r.title.toUpperCase()));if(!l||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let c=document.createElement("div");c.className="bp-side-empty",c.textContent="No projects yet.",m.appendChild(c)}for(let c of o){let u=document.createElement("div");if(u.className="bp-proj-group"+(c.off?" bp-dim":""),u.setAttribute("data-project-id",c.id),c.nav||c.key)u.setAttribute("data-project-key",c.nav||c.key||"");let p=document.createElement("div");p.className="bp-proj-head";let d=document.createElement("button");d.type="button",d.className="bp-proj-toggle";let b=xi();if(c.css)b.style.color=c.css;let y=document.createElement("span");if(y.className="bp-proj-name",y.textContent=c.title||c.id,d.append(b,y),c.fold==="project-fold"&&c.nav)d.addEventListener("click",()=>this.cb.onToggleProjectFold?.(c.nav));let f=document.createElement("button");if(f.type="button",f.className="icon bp-proj-add",f.title=h("thread.new","New thread"),f.textContent="+",f.setAttribute("data-testid",`new-thread-${c.id}`),c.off)f.disabled=!0;if(f.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(c.id)}),p.append(d,f),u.appendChild(p),!c.folded||Boolean(t)){let g=Boolean(t)&&(c.title||c.id).toLowerCase().includes(t);for(let E of c.swarms??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(E,!0))}for(let E of c.threads??[]){if(t&&!g&&!E.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(E,!0))}if(s&&s.project===c.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Ci(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}m.appendChild(u)}}e.appendChild(m)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let l=this.collapsedProjects.has(i.id)&&!t,m=xi();if(i.css)m.style.color=i.css;let c=document.createElement("span");c.className="bp-proj-name",c.textContent=i.title||i.id,o.append(m,c),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,u),a.appendChild(r),!l)for(let p of s)a.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:Ci(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=h("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let c of this.bots){let u=document.createElement("div");u.className="bp-thread-row"+(c.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",c.color)p.style.backgroundColor=c.color;let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`@${c.name}`,u.append(p,d),u.addEventListener("click",()=>this.cb.onSelectBot(c)),n.appendChild(u)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let l=document.createElement("span");l.textContent=h("bots.rooms","Rooms").toUpperCase();let m=document.createElement("span");m.className="bp-side-sec-plus",m.textContent="+",m.setAttribute("aria-hidden","true"),o.append(l,m),r.appendChild(o);for(let c of this.rooms){let u=document.createElement("div");u.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${c.name}`,u.appendChild(p),r.appendChild(u)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Ps(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function wt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ns(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?l/m:0));s[a]=c<0?c*32768:c*32767}return s}class dn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){wt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(wt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Ps(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(wt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),l=i.slice(0,o)+a+i.slice(r);this.mark=o+a.length,this.cb.setDraft(l)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Ns(r.inputBuffer.getChannelData(0),i.sampleRate);for(let l=0;l=3200){let l=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(l.buffer),!1,t)}},s.connect(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;wt(this.stream),this.stream=null}}var ki=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Si=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Li=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Ai=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ms=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Et(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[l]++,l>i)i=l}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[l]++]=o}return{counts:n,symbols:r,maxBits:i}}var Ts=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),Et(e,288)})(),Bs=(()=>{let e=new Uint8Array(32);return e.fill(5),Et(e,32)})();class pn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,p},r=(u)=>{let p=0,d=0,b=0;for(let y=1;y<=u.maxBits;y++){p|=a(1);let f=u.counts[y];if(p-f{let p=l+u;if(p>t)throw Error("inflated frame exceeds limit");if(p<=o.length)return;let d=o.length;while(d{m(1),o[l++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=a(1),p=a(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let d=e[n]|e[n+1]<<8,b=e[n+2]|e[n+3]<<8;if(n+=4,(d^65535)!==b)throw Error("invalid stored block length");if(n+d>e.length)throw Error("truncated stored payload");m(d);for(let y=0;y=e.length)break}else if(p===1||p===2){let d=Ts,b=Bs;if(p===2){let y=a(5)+257,f=a(5)+1,g=a(4)+4,E=new Uint8Array(19);for(let M=0;Mk)throw Error("code length overflow");for(let _=0;_k)throw Error("code length overflow");N+=D}else if(M===18){let D=a(7)+11;if(N+D>k)throw Error("code length overflow");N+=D}else throw Error("invalid code length symbol")}d=Et(A,y),b=Et(A.subarray(y),f)}while(!0){let y=r(d);if(y<256)c(y);else if(y===256)break;else{let f=y-257;if(f>=ki.length)throw Error("invalid length symbol");let g=ki[f]+(Si[f]?a(Si[f]):0),E=r(b);if(E>=Li.length)throw Error("invalid distance symbol");let x=Li[E]+(Ai[E]?a(Ai[E]):0);m(g);let k=this.winPos-x&32767;for(let A=0;A{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new pn:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,l=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(l))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Is=new TextDecoder;function Pi(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Ni(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],l=o>>5,m=i(o&31);if(m===null)return null;switch(l){case 0:return m;case 1:return-1-m;case 2:{if(t+m>e.length)return null;let c=e.subarray(t,t+m);return t+=m,c}case 3:{if(t+m>e.length)return null;let c=Is.decode(e.subarray(t,t+m));return t+=m,c}case 4:{if(m>e.length)return null;let c=Array(m);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Ti(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[y]==="number"?e[y]:f,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,l=a===0&&r!==0,m=e.d instanceof Uint8Array?e.d:new Uint8Array(0),c=new Mi(m),u=[],p=[],d=0,b=0;while(c.more()){let y=c.nextU32(),f=u.length,g=1/0,E=1/0,x=-1/0,k=-1/0;if(a===2)d=d+c.nextI32()|0,b=b+c.nextI32()|0,u.push(d,b),g=x=d,E=k=b;else{let N=Math.min(c.nextU32(),1048576);for(let M=0;Mx)x=d;if(bk)k=b}}let A=(u.length-f)/2;if(A>0){let N=a===2||A===1?2:a===0?0:1,M=a===0?0:o;p.push({info:y,x0:g-M,y0:E-M,x1:x+M,y1:k+M,at:f,n:A,kind:N})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:l,pts:new Float32Array(u),pieces:p}}function Bi(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,l);while(n.size>1024){let m=n.keys().next().value;if(m!==void 0)n.delete(m);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function Ii(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,l=i?n.top:n.top+(n.height-r)/2,m=(e-o)/a,c=(t-l)/r;if(m<0||m>1||c<0||c>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(m*1000))),y:Math.max(0,Math.min(1000,Math.round(c*1000)))}}var Ri=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ji(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class un{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Hi(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,l=!1,m=-1,c=null,u=new un,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let d=document.createElement("div");d.className="bp-pane-bar bp-browser-nav";function b(Z,le,j){let z=document.createElement("button");if(z.type="button",z.className="bp-v-btn",z.textContent=Z,z.setAttribute("data-testid",le),j)z.title=j;return z}let y=b("←","browser-back","Back"),f=b("→","browser-forward","Forward"),g=b("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let k=b("Go","browser-go","Navigate");k.type="submit",E.append(x,k);let A=b("Take over","browser-takeover");A.classList.add("is-primary"),d.append(y,f,g,E,A);let N=document.createElement("div");N.className="bp-browser-drive-bar",N.hidden=!0;let M=document.createElement("div");M.className="bp-browser-keys-row";let D=document.createElement("input");D.type="text",D.className="bp-browser-input",D.placeholder="Type text or press Enter/Tab/Arrows…",D.autocomplete="off",D.spellcheck=!1,D.setAttribute("data-testid","browser-keys");let W=b("Send","browser-type-send");M.append(D,W);let _=document.createElement("div");_.className="bp-browser-quick-keys";for(let[Z,le]of Ri){let j=b(Z,`browser-key-${le}`);j.addEventListener("click",()=>we("press",{key:le})),_.append(j)}N.append(M,_);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let he=document.createElement("div");he.className="bp-browser-stage",he.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let se=document.createElement("div");se.className="bp-pane-empty",se.setAttribute("data-testid","browser-empty"),se.textContent="Loading browser screen…",he.append(me,se);let ye=document.createElement("div");ye.className="bp-browser-hint",ye.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ye.hidden=!0,p.append(d,N,H,he,ye),e.replaceChildren(p);function Le(Z){H.textContent=Z,H.hidden=!Z}function Ae(){N.hidden=!s,ye.hidden=!s,A.textContent=s?"Hand back":"Take over",A.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),A.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function we(Z,le={},j){u.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:Z,...le}),!i)return;j?.(),pe()}catch(z){if(!i)return;Le(z instanceof Error?z.message:String(z))}})}function Be(Z){we("toolbar",{command:Z},()=>{s=!0,Ae()})}y.addEventListener("click",()=>Be("back")),f.addEventListener("click",()=>Be("forward")),g.addEventListener("click",()=>Be("reload")),E.addEventListener("submit",(Z)=>{Z.preventDefault();let le=ji(x.value);if(!le)return;if(x.value=le,!s)we("takeover",{},()=>{s=!0,Ae()});we("navigate",{url:le},()=>{s=!0,Ae()})}),A.addEventListener("click",()=>{if(s)we("handback",{},()=>{s=!1,Ae()});else we("takeover",{},()=>{s=!0,Ae(),D.focus()})});function B(){let Z=D.value;if(!Z)return;D.value="",we("type",{text:Z})}W.addEventListener("click",B),D.addEventListener("keydown",(Z)=>{if(!s)return;if(Z.key==="Enter"){if(Z.preventDefault(),D.value)B();we("press",{key:"Enter"});return}if(Z.key==="Tab"||Z.key==="Escape"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="ArrowLeft"||Z.key==="ArrowRight"||Z.key==="Backspace"&&D.value==="")Z.preventDefault(),we("press",{key:Z.key})}),me.addEventListener("click",(Z)=>{if(!s||!a)return;let le=me.getBoundingClientRect(),j=Ii(Z.clientX,Z.clientY,{left:le.left,top:le.top,width:le.width,height:le.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!j)return;we("click",j)}),me.addEventListener("wheel",(Z)=>{if(!s||!a)return;Z.preventDefault();let le=Math.round(Z.deltaX),j=Math.round(Z.deltaY);if(le===0&&j===0)return;we("scroll",{dx:le,dy:j})},{passive:!1});async function pe(){if(!i)return;if(o){l=!0;return}o=!0;try{do{l=!1,c=new AbortController;let Z=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:c.signal});if(!i)return;if(Z.ok){let le=await Z.blob();if(!i)return;let j=URL.createObjectURL(le),z=r;if(r=j,me.src=j,me.hidden=!1,se.hidden=!0,a=!0,z)URL.revokeObjectURL(z)}else if(!a)me.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&l)}catch{if(!i)return;if(!a)me.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}finally{c=null,o=!1}}let ne=t.hub.onFrame((Z)=>{if(!i)return;if(Z.t==="shot"&&Z.bot===n){if(typeof Z.n==="number"){if(Z.n===m)return;m=Z.n}pe()}});return pe(),{destroy(){if(i=!1,ne(),c?.abort(),r)URL.revokeObjectURL(r),r=""}}}function V(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Dt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Fi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function js(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Di(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Hs(e){let t=Fi(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function $i(e,t,n,i){let s=!0,a="",r="",o=V("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let l=V("div","bp-pane-bar"),m=V("div","bp-files-crumbs"),c=V("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void f(a)),l.append(m,c);let u=V("div","bp-files-split"),p=V("div","bp-files-list");p.setAttribute("data-testid","files-list");let d=V("div","bp-files-preview");d.setAttribute("data-testid","files-preview"),d.append(V("div","bp-pane-empty","Select a file to preview")),u.append(p,d),o.append(l,u),e.replaceChildren(o);function b(){m.replaceChildren();let g=V("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void f("")),m.append(g),!a)return;let E=a.split("/").filter(Boolean),x="";for(let k of E){x=x?`${x}/${k}`:k;let A=x;m.append(V("span","bp-vh-sep","/"));let N=V("button","bp-crumb-btn",k);N.type="button",N.addEventListener("click",()=>void f(A)),m.append(N)}}async function y(g,E,x){r=g,d.replaceChildren();let k=V("div","bp-files-prev-head");k.append(V("span","bp-files-prev-name",g));let A=V("div","bp-files-prev-acts"),N=Hs(E);if(N){let _=V("button","bp-v-btn is-primary",`Open in ${N}`);_.type="button",_.setAttribute("data-testid","files-open-viewer"),_.addEventListener("click",()=>i(N,g)),A.append(_)}let M=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,D=V("a","bp-v-btn","Download");D.href=M,D.download=E,A.append(D),k.append(A),d.append(k);let W=Fi(E);if(js(W)){let _=V("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=E,H.src=M,_.append(H),d.append(_);return}if(x>524288&&!Di(W)){d.append(V("div","bp-pane-empty",`Binary file (${Dt(x)}). Use Download to save.`));return}if(Di(W)||x<=65536){let _=V("div","bp-pane-empty","Loading…");d.append(_);try{let H=await fetch(M,{credentials:"same-origin"});if(!s||r!==g)return;if(!H.ok){_.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){_.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=E,ne.src=M,d.append(ne);return}let me=262144,se=[],ye=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:Z,value:le}=await ne.read();if(Z||!le)break;if(ye+le.byteLength>me){let j=me-ye;if(j>0)se.push(le.subarray(0,j)),ye+=j;Le=!0,await ne.cancel();break}se.push(le),ye+=le.byteLength}}finally{ne.releaseLock()}}if(!s||r!==g)return;let Ae=new Uint8Array(ye),we=0;for(let ne of se)Ae.set(ne,we),we+=ne.byteLength;let Be=!1;for(let ne=0;nek.dir===A.dir?k.name.localeCompare(A.name):k.dir?-1:1),p.replaceChildren(),g){let k=V("button","bp-file-row is-dir");k.type="button",k.append(V("span","bp-file-icon","↰"),V("span","bp-file-name",".."));let A=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";k.addEventListener("click",()=>void f(A)),p.append(k)}if(x.length===0){p.append(V("div","bp-pane-empty","Empty folder"));return}for(let k of x){let A=g?`${g}/${k.name}`:k.name,N=V("button","bp-file-row"+(k.dir?" is-dir":"")+(A===r?" is-sel":""));N.type="button",N.setAttribute("data-testid",`file-row-${k.name}`),N.append(V("span","bp-file-icon",k.dir?"▸":"·"),V("span","bp-file-name",k.name),V("span","bp-file-size",k.dir?"":Dt(k.size))),N.addEventListener("click",()=>{if(k.dir)f(A);else p.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),N.classList.add("is-sel"),y(A,k.name,k.size)}),p.append(N)}}catch(E){if(!s)return;p.replaceChildren(V("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return f(""),{destroy(){s=!1}}}function Gi(e,t,n){let i=!0,s=V("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=V("div","bp-pane-bar"),r=V("span","bp-diff-summary","Loading diff…"),o=V("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void m()),a.append(r,o);let l=V("div","bp-diff-body");l.setAttribute("data-testid","diff-body"),s.append(a,l),e.replaceChildren(s);async function m(){r.textContent="Loading diff…",l.replaceChildren();try{let c=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(c?.nogit){r.textContent="Not a git repository",l.append(V("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof c?.diff==="string"?c.diff:"";if(!u.trim()){r.textContent="Clean working tree",l.append(V("div","bp-pane-empty","No uncommitted changes."));return}let p=u.split(` +`),d=0,b=0,y=0,f=document.createDocumentFragment(),g=V("div","bp-diff-file");for(let E of p){if(E.startsWith("diff --git ")){if(g.childNodes.length>0)f.append(g);g=V("div","bp-diff-file"),d++;let x=E.match(/ b\/(.+)$/);g.append(V("div","bp-diff-file-head",x?x[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))g.append(V("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))g.append(V("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))b++,g.append(V("div","bp-diff-line is-add",E));else if(E.startsWith("-"))y++,g.append(V("div","bp-diff-line is-del",E));else g.append(V("div","bp-diff-line",E))}if(g.childNodes.length>0)f.append(g);r.textContent=`${d||1} file${d===1?"":"s"} · +${b} -${y}`,l.append(f)}catch(c){if(!i)return;r.textContent="Diff unavailable",l.append(V("div","bp-pane-empty",c instanceof Error?c.message:String(c)))}}return m(),{destroy(){i=!1}}}function Ui(e,t,n){let i=!0,s="checks",a=V("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=V("div","bp-pane-bar"),o=V("div","bp-review-tabs"),l=V("button","bp-v-btn is-on","Checks"),m=V("button","bp-v-btn","BOM"),c=V("button","bp-v-btn","Comments");l.type=m.type=c.type="button",o.append(l,m,c);let u=V("button","bp-v-btn","Refresh");u.type="button",u.addEventListener("click",()=>void y()),r.append(o,u);let p=V("div","bp-review-body");p.setAttribute("data-testid","review-body"),a.append(r,p),e.replaceChildren(a);function d(f){s=f,l.classList.toggle("is-on",s==="checks"),m.classList.toggle("is-on",s==="bom"),c.classList.toggle("is-on",s==="comments"),y()}l.addEventListener("click",()=>d("checks")),m.addEventListener("click",()=>d("bom")),c.addEventListener("click",()=>d("comments"));function b(f){let g=V("div","bp-review-md"),E=f.split(` +`),x=0;while(x{M.preventDefault();let D=A.value.trim();if(!D)return;N.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:D}).then(()=>{A.value="",N.disabled=!1,y()},()=>{N.disabled=!1})}),p.append(k),x.length===0){p.append(V("div","bp-pane-empty","No review comments yet."));return}for(let M of x){let D=V("div","bp-review-comment"+(M.resolved?" is-resolved":"")),W=[M.by||"review",M.file,M.layer,M.item].filter(Boolean).join(" · ");D.append(V("div","bp-review-comment-meta",W),V("div","bp-review-comment-text",M.text)),p.append(D)}return}let f=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=f?.report||{};if(p.replaceChildren(),g.line||g.gate){let E=V("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));p.append(E)}if(g.err)p.append(V("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let E=V("div","bp-review-tasks");g.tasks.forEach((x,k)=>{let A=V("label","bp-review-task"),N=document.createElement("input");N.type="checkbox",N.checked=!!(x.done??x.checked);let M=typeof x.index==="number"?x.index:k;N.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void y(),()=>{})}),A.append(N,V("span",void 0,x.text||x.label||`Item ${k+1}`)),E.append(A)}),p.append(E)}if(g.md&&g.md.trim())p.append(b(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))p.append(V("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(f){if(!i)return;p.replaceChildren(V("div","bp-pane-empty",f instanceof Error?f.message:String(f)))}}return y(),{destroy(){i=!1}}}function Vi(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class hn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),l=Math.max(o.width,200),m=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(l/a,m/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let l=t*0.5,m=n*0.5,c=this.scale,u=this.cx,p=this.cy,d=u-l/c,b=u+l/c,y=p-m/c,f=p+m/c,{off:g,dim:E,lift:x}=this.masks,k=[],A=[];for(let M=0;M>>D&1)===1)continue;if(D===x)A.push(M);else k.push(M)}let N=k.concat(A);r.lineCap="round",r.lineJoin="round";for(let M=0;M>>W.layer&1)===1,H=W.alpha*(_?0.25:1);if(H<=0.01)continue;this.drawChunk(r,W,H,d,y,b,f,u,p,c,l,m)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let M=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let D=0;Da||f.y1r)continue;if(f.n<3)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+u;e.moveTo(g,E);for(let x=1;x0)e.fill()}else if(t.mode===2){let b=Math.max(0.75,t.r*m);e.fillStyle=d,e.beginPath();let y=0;for(let f=0;fa||g.y1r)continue;let E=(p[g.at]-o)*m+c,x=(p[g.at+1]-l)*m+u;e.moveTo(E+b,x),e.arc(E,x,b,0,Math.PI*2),y++}if(y>0)e.fill()}else{e.strokeStyle=d,e.lineWidth=Math.max(1,t.r*2*m),e.beginPath();let b=0;for(let y=0;ya||f.y1r)continue;let g=(p[f.at]-o)*m+c,E=(p[f.at+1]-l)*m+u;if(f.n===1)e.moveTo(g,E),e.lineTo(g+0.01,E);else{e.moveTo(g,E);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,l,m,c,u,p){let d=t.pts,b=Vi(t.color,t.alpha);for(let y=0;yr||f.y1o)continue;let g=(d[f.at]-l)*c+u,E=(d[f.at+1]-m)*c+p;if(f.kind===2){let x=Math.max(1.5,t.r*c);e.fillStyle=b,e.beginPath(),e.arc(g,E,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(f.kind===0&&f.n>=3){e.fillStyle=b,e.beginPath(),e.moveTo(g,E);for(let x=1;x=0;c--){let u=n.chunks[c];if(u.layer<32&&(m>>>u.layer&1)===1)continue;for(let p=0;pd.x1+r||ad.y1+r)continue;let b=(d.x1-d.x0+1)*(d.y1-d.y0+1);if(b{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),l=this.canvas.getBoundingClientRect(),m=this.pinchStart.midX-l.left-l.width*0.5,c=this.pinchStart.midY-l.top-l.height*0.5,u=s-l.left-l.width*0.5,p=a-l.top-l.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+m/this.pinchStart.scale-u/o,this.cy=this.pinchStart.cy+c/this.pinchStart.scale-p/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Oi=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Wi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function bn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` `),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),l=i.replace(/\\/g,"/");if(l.startsWith("/")||/^[A-Za-z]:\//.test(l))return o===l;return o===l||o.endsWith(`/${l}`)}class gn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Ds=`#version 300 es precision highp float; out vec2 vUv; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Os=[qe(77),qe(83),qe(94)],Us=[qe(53),qe(58),qe(67)],Vs=[qe(245),qe(246),qe(248)],Ws=[qe(225),qe(228),qe(233)];function _i(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function qi(e,t,n){let i=_i(e,e.VERTEX_SHADER,t),s=_i(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function _s(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function qs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Ki(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function zi(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function fn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class vn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=qi(n,Ds,Fs),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=qi(n,$s,Gs),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Ti(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,h=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,d=0,b=0;for(let g=0;g>>24&255,k=1-x/255,A=(E>>>16&255)/255,N=(E>>>8&255)/255,M=(E&255)/255,D=g*9;if(x===0&&o&&l&&m){let W=d*9;for(let H=0;H<9;H++)o[W+H]=e[D+H],l[W+H]=t[D+H];let _=d*12;for(let H=0;H<3;H++)m[_+H*4]=A,m[_+H*4+1]=N,m[_+H*4+2]=M,m[_+H*4+3]=1;d++}else if(c&&h&&p){let W=b*9;for(let H=0;H<9;H++)c[W+H]=e[D+H],h[W+H]=t[D+H];let _=b*12;for(let H=0;H<3;H++)p[_+H*4]=A,p[_+H*4+1]=N,p[_+H*4+2]=M,p[_+H*4+3]=k;b++}}let y=o&&l&&m?this.createSubBatch(o,l,m,a*3):null,f=c&&h&&p?this.createSubBatch(c,h,p,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Wi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Vs:Os,_=this.lightTheme?Ws:Us;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),m=Math.sin(this.pitch),c=Math.cos(this.yaw),h=Math.sin(this.yaw),p=[this.target[0]+this.dist*l*h,this.target[1]-this.dist*l*c,this.target[2]+this.dist*m],d=Ki([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),b=Math.abs(d[2])>0.99?[0,1,0]:[0,0,1],y=Ki(zi(d,b)),f=zi(y,d),g=new Float32Array([y[0],f[0],-d[0],0,y[1],f[1],-d[1],0,y[2],f[2],-d[2],0,-fn(y,p),-fn(f,p),fn(d,p),1]),E=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),k=qs(35*Math.PI/180,r/o,E,x),A=_s(k,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,A),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,d[0],d[1],d[2]);let N=!1,M=[],D=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,H=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(H<1){if(N=!0,H>0)D.push({batch:W,fade:H})}else M.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of M)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of M)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of D)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),N}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var Ji=64,Ks=16777216;function zs(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Yi(e){switch(e){case"board":return u("viewer.board","Board");case"schematic":return u("viewer.schematic","Schematic");case"3d":return u("viewer.solid","3D");case"gerbers":return u("gpui.gerbers","Gerbers");case"mech":return u("viewer.mech","Mech");case"files":return u("viewer.files","Files");case"diff":return u("viewer.diff","Diff");case"review":return u("viewer.review","Review");case"browser":return u("bots.tab.browser","Browser");case"terminal":return u("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function yn(e){return e==="board"||e==="schematic"||e==="gerbers"}function Js(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function wn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let d=document.createElement("div");d.className="bp-v-layers",d.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,c.append(h,p,d,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,l,m,c,y);let f="",g="",E=0,x=!1,k=new Set,A=[],N=0,M=new Map,D=new Map,W={},_=[],H="",ue="",me=!1,se=!1,ye=0,Le=!1,Ae=0,we="",Be=0,B=null,pe=null,ne=null,Z=null,le=null,j=new gn,Y=0,C=!1,S="",R="",q="",T="";document.addEventListener("click",(I)=>{if(!C)return;if(I.target instanceof Node&&y.contains(I.target))return;C=!1,re()}),document.addEventListener("keydown",(I)=>{if(C&&I.key==="Escape")C=!1,re()});function z(){if(Y)window.clearInterval(Y),Y=0;j.playing=!1}function J(){let I=g==="3d"||g==="mech";if(l.hidden=!I,!I)return;if(l.childElementCount>0)return;for(let O of Vi){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=O.label,G.setAttribute("data-testid",`solid-view-${O.id}`),G.addEventListener("click",()=>{ne?.setView(O.id)}),l.append(G)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent="Snap view",F.setAttribute("data-testid","solid-snap"),F.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((O)=>{if(!O)return;let G=URL.createObjectURL(O),K=document.createElement("a");K.href=G;let ee=(Re()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");K.download=`${ee}-snap.png`,K.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),l.append(F)}async function Me(){if(!f||g!=="board"&&g!=="schematic")return;re();let I=j.compareRequest();if(!I){S="",R="",q="",T="",await Ge(!1);return}let F=`${g}|${I.commit}|${I.bits}|${ue}`;if(F===T&&k.size>0){he(j.highlightEdits?`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)}`,!1);return}let O=++E;k.clear(),M.clear(),Xe(),x=!0,S="",R=I.commit,q="",T=F;try{let G=ue||(g==="schematic"?W.sch:W.pcb)||"";if(!G){let fe=await t.hub.rpc("viewer.files",{thread:f});if(O!==E)return;W=fe||{},X(),G=(g==="schematic"?W.sch:W.pcb)||""}if(!G)throw Error(`Unable to resolve ${g} file path for compare`);let K=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:I.commit,bits:I.bits,...ue?{path:ue}:{}});if(O!==E)return;let ee=typeof K?.root==="string"?K.root:"",te=g==="schematic"?"1":"0";S=ee?`${te}|${ee}|diff -`:`${te}|`,R=I.commit,q=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!ee?G:`${ee.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,x=!1;let ge=A;Xe();for(let fe of ge)if(fe.kind==="bin")Oe(fe.buf);else Ue(fe.key,fe.none,fe.retryable);he(j.highlightEdits?`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${j.activeRef()?.label||I.commit.slice(0,7)}`,!1)}catch(G){if(O!==E)return;x=!1,S="",R="",q="",T="",Xe(),he(G instanceof Error?G.message:String(G),!0)}}function re(){let I=g==="board"||g==="schematic";if(y.hidden=!I,!I)return;let F=document.createElement("div");F.className="bp-history-group";let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="<",O.title="Older snapshot",O.disabled=j.refs.length===0||j.index>=j.refs.length-1,O.setAttribute("data-testid","history-prev"),O.addEventListener("click",()=>{if(z(),j.step(1))Me()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(j.playing?" is-on":""),G.textContent=j.playing?"⏸":"▶",G.title=j.playing?"Pause history":"Play history",G.disabled=j.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(j.playing){z(),re();return}if(j.refs.length===0)return;if(j.playing=!0,j.isLive())j.index=j.refs.length-1,Me();else re();Y=window.setInterval(()=>{if(!j.playing||g!=="board"&&g!=="schematic"){z(),re();return}if(j.step(-1))Me();else z(),re()},1400)});let K=document.createElement("button");K.type="button",K.className="bp-v-btn",K.textContent=">",K.title="Newer snapshot",K.disabled=j.isLive(),K.setAttribute("data-testid","history-next"),K.addEventListener("click",()=>{if(z(),j.step(-1))Me()});let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn"+(j.isLive()?" is-on":""),ee.textContent="Live",ee.setAttribute("data-testid","history-live"),ee.addEventListener("click",()=>{if(z(),j.goLive())he("",!1),Me()});let te=document.createElement("span");te.className="bp-history-label",te.setAttribute("data-testid","history-label");let ge=j.activeRef();te.textContent=ge?ge.label||ge.commit.slice(0,7):j.refs.length>0?`Live (${j.refs.length} saved)`:"Live",F.append(O,G,K,ee,te);let fe=document.createElement("div");fe.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(j.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=j.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{z(),j.toggleHighlight(),Me()});let Ee=document.createElement("div");Ee.className="bp-history-menu-wrap";let Te=document.createElement("button");if(Te.type="button",Te.className="bp-v-btn"+(C||!j.isLive()?" is-on":""),Te.disabled=j.refs.length===0,Te.setAttribute("data-testid","history-compare"),Te.setAttribute("aria-haspopup","menu"),Te.setAttribute("aria-expanded",String(C)),Te.textContent=ge?`Compare: ${ge.label||ge.commit.slice(0,7)} ▾`:"Compare ▾",Te.addEventListener("click",(Ie)=>{Ie.stopPropagation(),C=!C,re()}),Ee.append(Te),C&&j.refs.length>0){let Ie=document.createElement("div");Ie.className="bp-history-menu",Ie.setAttribute("role","menu"),Ie.setAttribute("data-testid","history-compare-menu");let _e=(Fe,Ze,St)=>{let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-history-menu-item"+(St?" is-active":""),Ve.setAttribute("role","menuitem"),Ve.setAttribute("data-commit",Ze),Ve.textContent=Fe,Ve.addEventListener("click",()=>{if(C=!1,z(),j.selectCommit(Ze)){if(j.isLive())he("",!1);Me()}else re()}),Ie.append(Ve)};_e("Live (working tree)","",j.isLive());for(let Fe of j.refs)_e(Fe.label||Fe.commit.slice(0,7),Fe.commit,ge?.commit===Fe.commit);Ee.append(Ie)}fe.append(Pe,Ee),y.replaceChildren(F,fe)}async function ke(I){if(!I)return;try{let F=await t.hub.rpc("viewer.refs",{thread:I});if(I!==f)return;j.setRefs(Array.isArray(F?.refs)?F.refs:[]),re()}catch{if(I!==f)return;j.setRefs([]),re()}}function He(){return document.documentElement.classList.contains("light")}let be=new MutationObserver(()=>{let I=He();pe?.setTheme(I),ne?.setTheme(I),le?.setTheme(I)});be.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function de(I,F="",O=!1){if(I==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${I}`;let G=document.createElement("div");G.className="bp-v-state-card";let K=document.createElement("div");if(K.className="bp-v-state-msg",K.textContent=F,G.append(K),O){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn is-primary",ee.textContent=u("tools.retry","Retry"),ee.addEventListener("click",()=>void Ge(!0)),G.append(ee)}p.replaceChildren(G)}function he(I,F){m.textContent=I,m.hidden=!I,m.classList.toggle("is-warn",F)}function Re(){if(ue)return xt(ue);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(H);return""}function X(){s.textContent=Yi(g);let I=Re();if(a.hidden=!I,r.hidden=!I,r.textContent=I,o.replaceChildren(),g==="mech"&&_.length>1){let O=document.createElement("select");O.className="bp-v-select",O.setAttribute("aria-label",u("viewer.mech","Mech"));for(let G of _){let K=document.createElement("option");K.value=G,K.textContent=xt(G),K.selected=G===H,O.append(K)}O.addEventListener("change",()=>{H=O.value,X(),Ge(!1)}),o.append(O)}if(yn(g)){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(Le?" is-on":""),O.textContent=B?.layerHead||"Layers",O.setAttribute("data-testid","viewer-layers-btn"),O.addEventListener("click",()=>{if(Le=!Le,d.hidden=!Le,O.classList.toggle("is-on",Le),Le)je("","")}),o.append(O)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="Fit",O.setAttribute("data-testid","viewer-fit-btn"),O.addEventListener("click",()=>{pe?.fit(),ne?.fit()}),o.append(O)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let O=document.createElement("button");O.type="button",O.className="bp-v-btn"+(me&&!se?" is-on":""),O.textContent=me?se?u("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",O.setAttribute("data-testid","viewer-follow-btn"),O.addEventListener("click",()=>void Ke()),o.append(O)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn bp-v-close",F.textContent="✕",F.title=u("common.close","Close"),F.setAttribute("aria-label",u("common.close","Close")),F.setAttribute("data-testid","viewer-close-btn"),F.addEventListener("click",()=>t.closeViewer()),o.append(F)}function oe(){if(!B){d.replaceChildren();return}let I=document.createDocumentFragment(),F=document.createElement("div");F.className="bp-v-layers-head";let O=document.createElement("span");if(O.textContent=B.layerHead||"Layers",F.append(O),B.layerReset){let te=document.createElement("button");te.type="button",te.className="bp-v-btn",te.textContent="Reset",te.addEventListener("click",()=>void je("reset","")),F.append(te)}if(I.append(F),B.layerModes){let te=document.createElement("div");te.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ge,fe)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(B?.layerMode===fe?" is-on":""),Pe.textContent=ge,Pe.addEventListener("click",()=>void je("mode",String(fe))),te.append(Pe)}),I.append(te)}let G=pe?.presentColors()??new Map,K=(B.layerList||[]).concat(B.layerMarks||[]),ee=document.createElement("div");ee.className="bp-v-layers-list";for(let te of K){let ge=G.get(te.layer);if(ge===void 0)continue;let fe=document.createElement("div");fe.className="bp-v-layer-row"+(te.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=te.on!==!1,Pe.addEventListener("change",()=>void je("toggle",String(te.layer)));let Ee=document.createElement("span");Ee.className="bp-v-layer-swatch";let Te=ge>>>16&255,Ie=ge>>>8&255,_e=ge&255;Ee.style.background=te.on!==!1?`rgb(${Te},${Ie},${_e})`:`rgba(${Te},${Ie},${_e},0.2)`;let Fe=document.createElement("button");Fe.type="button",Fe.className="bp-v-layer-name",Fe.textContent=te.name,Fe.addEventListener("click",()=>void je("pick",String(te.layer))),fe.append(Pe,Ee,Fe),ee.append(fe)}I.append(ee),d.replaceChildren(I)}async function je(I,F){if(!yn(g))return;let O=E;try{let G=await t.hub.rpc("viewer.layers",{kind:g,present:Be,off:Ae,focus:we,...I?{action:I,value:F}:{}});if(O!==E||!G)return;Ae=Number(G.own)||0,we=typeof G.focus==="string"?G.focus:"",B=G;let K={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(pe?.setLayers(K),X(),Le)oe()}catch{}}async function We(){if(!me||se||!f||!t.hub.hasFeature("follow"))return;se=!0,X();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function Ke(){if(!f||!t.hub.hasFeature("follow"))return;let I=!me?"on":se?"resume":"off";try{let F=await t.hub.rpc("viewer.follow",{thread:f,action:I});if(me=!!F.on,se=!!F.paused,X(),F.on&&!F.paused&&F.focus&&Array.isArray(F.focus.box)&&F.focus.box.length===4&&(F.seq||0)>ye)ye=F.seq||ye,pe?.zoomToBoxMm([F.focus.box[0],F.focus.box[1],F.focus.box[2],F.focus.box[3]])}catch{}}function ce(){b.hidden=!0,b.replaceChildren(),pe?.setHighlights([])}function lt(I){let F=I.split(";").filter(Boolean),O=F.shift()||I,G=[],K="",ee="";for(let Ee of F){if(Ee.startsWith("g="))continue;let Te=Ee.indexOf("=");if(Te>0){let Ie=Ee.slice(0,Te),_e=Ee.slice(Te+1);if((Ie==="ref"||Ie==="symbol")&&!K)K=_e;if(Ie==="net"&&!ee)ee=_e;G.push([Ie,_e])}else G.push([Ee,""])}let te=document.createElement("div");te.className="bp-v-info-head";let ge=document.createElement("span");ge.className="bp-v-info-title",ge.textContent=O;let fe=document.createElement("button");fe.type="button",fe.className="bp-v-info-x",fe.textContent="×",fe.setAttribute("aria-label","Clear selection"),fe.addEventListener("click",ce),te.append(ge,fe);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Ee,Te]of G){let Ie=document.createElement("span");Ie.className="bp-v-info-chip",Ie.textContent=Te?`${Ee}: ${Te}`:Ee,Pe.append(Ie)}return b.replaceChildren(te,...G.length>0?[Pe]:[]),b.hidden=!1,{ref:K||void 0,net:ee||void 0}}async function Ye(I){if(!I){ce();return}let F=Array.from(k)[0]||"";if(!F)return;let O=E;try{let G=await t.hub.rpc("viewer.info",{key:F,at:I.at,idx:I.idx});if(O!==E)return;let K=typeof G.info==="string"?G.info:"";if(!K){ce();return}let{ref:ee,net:te}=lt(K),ge=[];if(ee)ge.push(["ref",ee]);if(te)ge.push(["net",te]);let fe=[[I.at,I.idx]];for(let[Pe,Ee]of ge){let Te=await t.hub.rpc("viewer.probe",{key:F,name:Pe,value:Ee});if(O!==E)return;if(Array.isArray(Te.matches))for(let Ie of Te.matches)fe.push(Ie)}pe?.setHighlights(fe)}catch{ce()}}function ct(){Z?.destroy(),Z=null,le?.destroy(),le=null,pe?.destroy(),pe=null,ne?.destroy(),ne=null,h.replaceChildren(),Le=!1,d.hidden=!0,b.hidden=!0,b.replaceChildren(),he("",!1),de("none")}function Xe(){A=[],N=0}async function Ge(I){if(!f||!g)return;let F=++E;if(k.clear(),x=!1,Xe(),ct(),X(),J(),re(),(g==="board"||g==="schematic")&&f)ke(f);if(Js(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")Z=$i(h,t,f,(K,ee)=>{if(g=K,ue=ee,K==="mech")H=ee;Ge(!1)});else if(g==="diff")Z=Gi(h,t,f);else if(g==="review")Z=Oi(h,t,f);else if(g==="browser")Z=Hi(h,t,f);else if(g==="terminal")de("loading","Loading terminal…"),import("/assets/terminal.js").then((ee)=>{if(F!==E)return;if(de("none"),ee?.mountTerminalPane)le=ee.mountTerminalPane(h,t,f,He());else de("error","Terminal chunk missing",!0)},(ee)=>{if(F!==E)return;de("error",ee instanceof Error?ee.message:String(ee),!0)});return}if(de("loading","Loading…"),!W.root)try{let K=await t.hub.rpc("viewer.files",{thread:f});if(F!==E)return;W=K||{},X()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){de("empty","No Gerbers in this project",!1);return}let O=He();if(g==="3d"||g==="mech")ne=new vn(h,{onStatus:(K,ee)=>{if(ee)de("none"),he(K,!1);else if(K)de("loading",K);else de("none"),he("",!1)},onUserMove:()=>void We()}),ne.setTheme(O);else if(g==="board"||g==="schematic"||g==="gerbers")pe=new un(h,{onPick:(K)=>void Ye(K),onUserMove:()=>void We()}),pe.setTheme(O);else{de("empty",`${Yi(g)} is not available in this viewer`,!1);return}let G={thread:f};if(I)G.force=!0;if(g==="mech"){if(_.length===0)try{let K=await t.hub.rpc("mech.list",{thread:f});if(F!==E)return;if(_=Array.isArray(K.parts)?K.parts:[],!H)H=K.primary||_[0]||"";X()}catch(K){if(F!==E)return;de("error",K instanceof Error?K.message:String(K),!0);return}if(!H){de("empty",u("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=H}else{if(G.kind=g,ue&&(g==="board"||g==="schematic"))G.path=ue;if(g==="3d"&&!I&&ne){let K=ne.keptToken();if(K)G.kept=K}if((g==="board"||g==="schematic"||g==="gerbers")&&!I&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(D.keys())}x=!0,S="",R="",q="",T="";try{let K=await t.hub.rpc("viewer.watch",G);if(F!==E)return;k=new Set(Array.isArray(K.keys)?K.keys:[]),x=!1;let ee=A;Xe();for(let te of ee)if(te.kind==="bin")Oe(te.buf);else Ue(te.key,te.none,te.retryable)}catch(K){if(F!==E)return;x=!1,k.clear(),Xe();let ee=K instanceof Error?K.message:String(K),te=/no gerbers|not in this project|another machine/i.test(ee);de(te?"empty":"error",ee,!te)}}function Ue(I,F,O){if(x){if(A.length{if(I.t==="plot"&&typeof I.none==="string"&&typeof I.key==="string")Ue(I.key,I.none,I.retryable===!0)}),Ft=At(()=>{if(g)X()}),kt=(I)=>{if(I.key==="Escape"&&g&&!b.hidden)ce()};return window.addEventListener("keydown",kt),{open(I,F){if(F!==f){if(f=F,W={},_=[],H="",M.clear(),me=!1,se=!1,ye=0,Ae=0,we="",Be=0,B=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:F}).then((O)=>{if(F!==f)return;if(me=!!O.on,se=!!O.paused,ye=Number(O.seq)||0,g)X()}).catch(()=>{})}if(I!==g)z(),j.goLive(),Ae=0,we="",Be=0,B=null;g=I,ue="",Ge(!1)},reconcileHas(I){if(g&&!zs(g,I))t.closeViewer()},close(){if(E++,x=!1,z(),C=!1,S="",R="",q="",T="",j.goLive(),l.hidden=!0,y.hidden=!0,Xe(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",k.clear(),ct()}}}var Xi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(Xi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Xi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ys(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Zi(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Qi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function Xs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function es(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,m,c);let h=document.createElement("div");h.className="bp-top-state bp-hide-phone bp-hidden";let p=document.createElement("span");p.className="bp-top-state-lbl",p.textContent="STATE";let d=document.createElement("span");d.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",h.append(p,d,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=u("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=u("menu.settle","Settle"),E.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let k=document.createElement("div");k.className="bp-menu-wrap";let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost bp-top-act",A.textContent="▾",A.title="Thread menu",A.setAttribute("aria-label","Thread menu"),A.setAttribute("data-testid","thread-menu-btn");let N=document.createElement("div");N.className="bp-popover bp-hidden",N.setAttribute("data-testid","thread-menu"),k.append(A,N),y.append(f,E,k);let M=document.createElement("div");M.className="bp-top-right";let D=document.createElement("button");D.type="button",D.className="bp-btn-ghost bp-top-act bp-hide-tablet",D.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=u("gpui.improvements","Improvements"),D.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ue=document.createElement("button");ue.type="button",ue.className="icon bp-top-icon",ue.title=u("palette.settings","Settings"),ue.setAttribute("aria-label",u("palette.settings","Settings")),ue.setAttribute("data-testid","settings-btn"),ue.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(D,_,H,ue),t.append(n,i,h,y,M);let me=document.createElement("div");me.className="bp-body";let se=document.createElement("aside");se.className="bp-sidebar",se.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ae=document.createElement("div");Ae.className="bp-right-top";let we=document.createElement("section");we.className="bp-viewer-pane bp-hidden",we.setAttribute("data-testid","viewer-pane"),Ae.appendChild(we),Le.appendChild(Ae);let Be=document.createElement("nav");Be.className="bp-rail",Be.setAttribute("aria-label","Viewer rail"),Be.setAttribute("data-testid","viewer-rail"),me.append(se,ye,Le,Be),e.append(t,me);let B=new mn,pe=null,ne=new Set,Z=0,le=null,j=[],Y=[],C=[],S=[],R=[],q=[],T="",z=0,J=0,Me=null,re=null,ke="",He=null,be=20,de={},he=new Map;function Re(v,w){he.delete(v),he.set(v,w);while(he.size>be){let L=he.keys().next().value;if(L!==void 0)he.delete(L);else break}}let X=new cn(se,{onSelectThread:(v)=>{if(v===T&&Me!==null){se.classList.remove("bp-sidebar-open");return}Ee(v)},onNewThread:(v)=>{Fe(v)},onSelectBot:(v)=>{Ee(v.thread)},onThreadAct:(v,w)=>{et(v,w)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ge()},onToggleProjectFold:(v)=>{B.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ge()).catch(()=>{})},onCollapseSidebar:()=>{se.classList.remove("bp-sidebar-open"),se.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let w=jt(v,!1);if(!w)return;if(w.kind==="thread"){Ee(w.id);return}if(w.kind!=="call")return;let L=wi(await B.rpc(w.method,w.params));if(L?.kind==="thread")Ee(L.id);ge()},hasRoomView:!1,onAddProject:()=>Ue.open({mode:"folder"})}),oe=new Kt(ye,{onLoadOlder:()=>{_e()},onGoToEntry:(v)=>{Ie(v)},onAnswerAsk:(v,w)=>{B.rpc("ask.answer",{ask:v,answer:w}).catch((L)=>{ce.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!T)return;let w=z;B.rpc("thread.review",{thread:T,on:v}).then((L)=>{if(w===z)oe.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,w)=>{if(!T)return;if(v==="again"||v==="thread-again")B.rpc("thread.again",{thread:T,value:w}).catch(()=>{});else B.rpc("thread.act",{thread:T,action:v,value:w}).catch(()=>{})},onReplyEntry:(v)=>{if(!B.hasFeature("reply")){let w=(v.text||"").split(` +`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Us=[qe(77),qe(83),qe(94)],Vs=[qe(53),qe(58),qe(67)],Os=[qe(245),qe(246),qe(248)],Ws=[qe(225),qe(228),qe(233)];function _i(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function qi(e,t,n){let i=_i(e,e.VERTEX_SHADER,t),s=_i(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function _s(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function qs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Ki(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function zi(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function fn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class vn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=qi(n,Ds,Fs),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=qi(n,$s,Gs),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Ti(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,l=a>0?new Float32Array(a*9):null,m=a>0?new Float32Array(a*12):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,d=0,b=0;for(let g=0;g>>24&255,k=1-x/255,A=(E>>>16&255)/255,N=(E>>>8&255)/255,M=(E&255)/255,D=g*9;if(x===0&&o&&l&&m){let W=d*9;for(let H=0;H<9;H++)o[W+H]=e[D+H],l[W+H]=t[D+H];let _=d*12;for(let H=0;H<3;H++)m[_+H*4]=A,m[_+H*4+1]=N,m[_+H*4+2]=M,m[_+H*4+3]=1;d++}else if(c&&u&&p){let W=b*9;for(let H=0;H<9;H++)c[W+H]=e[D+H],u[W+H]=t[D+H];let _=b*12;for(let H=0;H<3;H++)p[_+H*4]=A,p[_+H*4+1]=N,p[_+H*4+2]=M,p[_+H*4+3]=k;b++}}let y=o&&l&&m?this.createSubBatch(o,l,m,a*3):null,f=c&&u&&p?this.createSubBatch(c,u,p,r*3):null;if(!y&&!f)return null;return{opaque:y,translucent:f,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Wi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let W=this.lightTheme?Os:Us,_=this.lightTheme?Ws:Vs;t.uniform3f(this.uBgTop,W[0],W[1],W[2]),t.uniform3f(this.uBgBot,_[0],_[1],_[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let l=Math.cos(this.pitch),m=Math.sin(this.pitch),c=Math.cos(this.yaw),u=Math.sin(this.yaw),p=[this.target[0]+this.dist*l*u,this.target[1]-this.dist*l*c,this.target[2]+this.dist*m],d=Ki([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),b=Math.abs(d[2])>0.99?[0,1,0]:[0,0,1],y=Ki(zi(d,b)),f=zi(y,d),g=new Float32Array([y[0],f[0],-d[0],0,y[1],f[1],-d[1],0,y[2],f[2],-d[2],0,-fn(y,p),-fn(f,p),fn(d,p),1]),E=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),k=qs(35*Math.PI/180,r/o,E,x),A=_s(k,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,A),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,y[0],y[1],y[2]),t.uniform3f(this.uUp,f[0],f[1],f[2]),t.uniform3f(this.uFwd,d[0],d[1],d[2]);let N=!1,M=[],D=[];for(let W of this.partBatches){let _=e-W.fadeStartMs,H=W.fadeStartMs===0?1:Math.min(1,Math.max(0,_/300));if(H<1){if(N=!0,H>0)D.push({batch:W,fade:H})}else M.push(W)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let W of M)this.drawSubBatch(W.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let W of M)this.drawSubBatch(W.translucent);for(let{batch:W,fade:_}of D)t.uniform1f(this.uFade,_),this.drawSubBatch(W.opaque),this.drawSubBatch(W.translucent);return t.depthMask(!0),t.bindVertexArray(null),N}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var Ji=64,Ks=16777216;function zs(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function xt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Yi(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function yn(e){return e==="board"||e==="schematic"||e==="gerbers"}function Js(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function wn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let l=document.createElement("div");l.className="bp-solid-bar",l.setAttribute("data-testid","solid-presets-bar"),l.hidden=!0;let m=document.createElement("div");m.className="bp-v-banner",m.hidden=!0;let c=document.createElement("div");c.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let d=document.createElement("div");d.className="bp-v-layers",d.hidden=!0;let b=document.createElement("div");b.className="bp-v-info",b.hidden=!0,c.append(u,p,d,b);let y=document.createElement("div");y.className="bp-history-bar",y.setAttribute("data-testid","viewer-history-bar"),y.hidden=!0,e.replaceChildren(n,l,m,c,y);let f="",g="",E=0,x=!1,k=new Set,A=[],N=0,M=new Map,D=new Map,W={},_=[],H="",he="",me=!1,se=!1,ye=0,Le=!1,Ae=0,we="",Be=0,B=null,pe=null,ne=null,Z=null,le=null,j=new gn,z=0,C=!1,S="",R="",Y="",T="";document.addEventListener("click",(I)=>{if(!C)return;if(I.target instanceof Node&&y.contains(I.target))return;C=!1,re()}),document.addEventListener("keydown",(I)=>{if(C&&I.key==="Escape")C=!1,re()});function J(){if(z)window.clearInterval(z),z=0;j.playing=!1}function K(){let I=g==="3d"||g==="mech";if(l.hidden=!I,!I)return;if(l.childElementCount>0)return;for(let U of Oi){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=U.label,G.setAttribute("data-testid",`solid-view-${U.id}`),G.addEventListener("click",()=>{ne?.setView(U.id)}),l.append(G)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn",F.textContent="Snap view",F.setAttribute("data-testid","solid-snap"),F.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((U)=>{if(!U)return;let G=URL.createObjectURL(U),q=document.createElement("a");q.href=G;let ee=(Re()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");q.download=`${ee}-snap.png`,q.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),l.append(F)}async function Me(){if(!f||g!=="board"&&g!=="schematic")return;re();let I=j.compareRequest();if(!I){S="",R="",Y="",T="",await Ge(!1);return}let F=`${g}|${I.commit}|${I.bits}|${he}`;if(F===T&&k.size>0){ue(j.highlightEdits?`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)}`,!1);return}let U=++E;k.clear(),M.clear(),Xe(),x=!0,S="",R=I.commit,Y="",T=F;try{let G=he||(g==="schematic"?W.sch:W.pcb)||"";if(!G){let fe=await t.hub.rpc("viewer.files",{thread:f});if(U!==E)return;W=fe||{},X(),G=(g==="schematic"?W.sch:W.pcb)||""}if(!G)throw Error(`Unable to resolve ${g} file path for compare`);let q=await t.hub.rpc("viewer.compare",{thread:f,kind:g,commit:I.commit,bits:I.bits,...he?{path:he}:{}});if(U!==E)return;let ee=typeof q?.root==="string"?q.root:"",te=g==="schematic"?"1":"0";S=ee?`${te}|${ee}|diff +`:`${te}|`,R=I.commit,Y=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!ee?G:`${ee.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,x=!1;let ge=A;Xe();for(let fe of ge)if(fe.kind==="bin")Ue(fe.buf);else Ve(fe.key,fe.none,fe.retryable);ue(j.highlightEdits?`Comparing against ${j.activeRef()?.label||I.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${j.activeRef()?.label||I.commit.slice(0,7)}`,!1)}catch(G){if(U!==E)return;x=!1,S="",R="",Y="",T="",Xe(),ue(G instanceof Error?G.message:String(G),!0)}}function re(){let I=g==="board"||g==="schematic";if(y.hidden=!I,!I)return;let F=document.createElement("div");F.className="bp-history-group";let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="<",U.title="Older snapshot",U.disabled=j.refs.length===0||j.index>=j.refs.length-1,U.setAttribute("data-testid","history-prev"),U.addEventListener("click",()=>{if(J(),j.step(1))Me()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(j.playing?" is-on":""),G.textContent=j.playing?"⏸":"▶",G.title=j.playing?"Pause history":"Play history",G.disabled=j.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(j.playing){J(),re();return}if(j.refs.length===0)return;if(j.playing=!0,j.isLive())j.index=j.refs.length-1,Me();else re();z=window.setInterval(()=>{if(!j.playing||g!=="board"&&g!=="schematic"){J(),re();return}if(j.step(-1))Me();else J(),re()},1400)});let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent=">",q.title="Newer snapshot",q.disabled=j.isLive(),q.setAttribute("data-testid","history-next"),q.addEventListener("click",()=>{if(J(),j.step(-1))Me()});let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn"+(j.isLive()?" is-on":""),ee.textContent="Live",ee.setAttribute("data-testid","history-live"),ee.addEventListener("click",()=>{if(J(),j.goLive())ue("",!1),Me()});let te=document.createElement("span");te.className="bp-history-label",te.setAttribute("data-testid","history-label");let ge=j.activeRef();te.textContent=ge?ge.label||ge.commit.slice(0,7):j.refs.length>0?`Live (${j.refs.length} saved)`:"Live",F.append(U,G,q,ee,te);let fe=document.createElement("div");fe.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(j.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=j.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{J(),j.toggleHighlight(),Me()});let Ee=document.createElement("div");Ee.className="bp-history-menu-wrap";let Te=document.createElement("button");if(Te.type="button",Te.className="bp-v-btn"+(C||!j.isLive()?" is-on":""),Te.disabled=j.refs.length===0,Te.setAttribute("data-testid","history-compare"),Te.setAttribute("aria-haspopup","menu"),Te.setAttribute("aria-expanded",String(C)),Te.textContent=ge?`Compare: ${ge.label||ge.commit.slice(0,7)} ▾`:"Compare ▾",Te.addEventListener("click",(Ie)=>{Ie.stopPropagation(),C=!C,re()}),Ee.append(Te),C&&j.refs.length>0){let Ie=document.createElement("div");Ie.className="bp-history-menu",Ie.setAttribute("role","menu"),Ie.setAttribute("data-testid","history-compare-menu");let _e=(Fe,Ze,St)=>{let Oe=document.createElement("button");Oe.type="button",Oe.className="bp-history-menu-item"+(St?" is-active":""),Oe.setAttribute("role","menuitem"),Oe.setAttribute("data-commit",Ze),Oe.textContent=Fe,Oe.addEventListener("click",()=>{if(C=!1,J(),j.selectCommit(Ze)){if(j.isLive())ue("",!1);Me()}else re()}),Ie.append(Oe)};_e("Live (working tree)","",j.isLive());for(let Fe of j.refs)_e(Fe.label||Fe.commit.slice(0,7),Fe.commit,ge?.commit===Fe.commit);Ee.append(Ie)}fe.append(Pe,Ee),y.replaceChildren(F,fe)}async function ke(I){if(!I)return;try{let F=await t.hub.rpc("viewer.refs",{thread:I});if(I!==f)return;j.setRefs(Array.isArray(F?.refs)?F.refs:[]),re()}catch{if(I!==f)return;j.setRefs([]),re()}}function He(){return document.documentElement.classList.contains("light")}let be=new MutationObserver(()=>{let I=He();pe?.setTheme(I),ne?.setTheme(I),le?.setTheme(I)});be.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function de(I,F="",U=!1){if(I==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${I}`;let G=document.createElement("div");G.className="bp-v-state-card";let q=document.createElement("div");if(q.className="bp-v-state-msg",q.textContent=F,G.append(q),U){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn is-primary",ee.textContent=h("tools.retry","Retry"),ee.addEventListener("click",()=>void Ge(!0)),G.append(ee)}p.replaceChildren(G)}function ue(I,F){m.textContent=I,m.hidden=!I,m.classList.toggle("is-warn",F)}function Re(){if(he)return xt(he);if(g==="board"||g==="3d")return xt(W.pcb);if(g==="schematic")return xt(W.sch);if(g==="mech")return xt(H);return""}function X(){s.textContent=Yi(g);let I=Re();if(a.hidden=!I,r.hidden=!I,r.textContent=I,o.replaceChildren(),g==="mech"&&_.length>1){let U=document.createElement("select");U.className="bp-v-select",U.setAttribute("aria-label",h("viewer.mech","Mech"));for(let G of _){let q=document.createElement("option");q.value=G,q.textContent=xt(G),q.selected=G===H,U.append(q)}U.addEventListener("change",()=>{H=U.value,X(),Ge(!1)}),o.append(U)}if(yn(g)){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(Le?" is-on":""),U.textContent=B?.layerHead||"Layers",U.setAttribute("data-testid","viewer-layers-btn"),U.addEventListener("click",()=>{if(Le=!Le,d.hidden=!Le,U.classList.toggle("is-on",Le),Le)je("","")}),o.append(U)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Fit",U.setAttribute("data-testid","viewer-fit-btn"),U.addEventListener("click",()=>{pe?.fit(),ne?.fit()}),o.append(U)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(me&&!se?" is-on":""),U.textContent=me?se?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",U.setAttribute("data-testid","viewer-follow-btn"),U.addEventListener("click",()=>void Ke()),o.append(U)}let F=document.createElement("button");F.type="button",F.className="bp-v-btn bp-v-close",F.textContent="✕",F.title=h("common.close","Close"),F.setAttribute("aria-label",h("common.close","Close")),F.setAttribute("data-testid","viewer-close-btn"),F.addEventListener("click",()=>t.closeViewer()),o.append(F)}function oe(){if(!B){d.replaceChildren();return}let I=document.createDocumentFragment(),F=document.createElement("div");F.className="bp-v-layers-head";let U=document.createElement("span");if(U.textContent=B.layerHead||"Layers",F.append(U),B.layerReset){let te=document.createElement("button");te.type="button",te.className="bp-v-btn",te.textContent="Reset",te.addEventListener("click",()=>void je("reset","")),F.append(te)}if(I.append(F),B.layerModes){let te=document.createElement("div");te.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ge,fe)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(B?.layerMode===fe?" is-on":""),Pe.textContent=ge,Pe.addEventListener("click",()=>void je("mode",String(fe))),te.append(Pe)}),I.append(te)}let G=pe?.presentColors()??new Map,q=(B.layerList||[]).concat(B.layerMarks||[]),ee=document.createElement("div");ee.className="bp-v-layers-list";for(let te of q){let ge=G.get(te.layer);if(ge===void 0)continue;let fe=document.createElement("div");fe.className="bp-v-layer-row"+(te.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=te.on!==!1,Pe.addEventListener("change",()=>void je("toggle",String(te.layer)));let Ee=document.createElement("span");Ee.className="bp-v-layer-swatch";let Te=ge>>>16&255,Ie=ge>>>8&255,_e=ge&255;Ee.style.background=te.on!==!1?`rgb(${Te},${Ie},${_e})`:`rgba(${Te},${Ie},${_e},0.2)`;let Fe=document.createElement("button");Fe.type="button",Fe.className="bp-v-layer-name",Fe.textContent=te.name,Fe.addEventListener("click",()=>void je("pick",String(te.layer))),fe.append(Pe,Ee,Fe),ee.append(fe)}I.append(ee),d.replaceChildren(I)}async function je(I,F){if(!yn(g))return;let U=E;try{let G=await t.hub.rpc("viewer.layers",{kind:g,present:Be,off:Ae,focus:we,...I?{action:I,value:F}:{}});if(U!==E||!G)return;Ae=Number(G.own)||0,we=typeof G.focus==="string"?G.focus:"",B=G;let q={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(pe?.setLayers(q),X(),Le)oe()}catch{}}async function We(){if(!me||se||!f||!t.hub.hasFeature("follow"))return;se=!0,X();try{await t.hub.rpc("viewer.follow",{thread:f,action:"pause"})}catch{}}async function Ke(){if(!f||!t.hub.hasFeature("follow"))return;let I=!me?"on":se?"resume":"off";try{let F=await t.hub.rpc("viewer.follow",{thread:f,action:I});if(me=!!F.on,se=!!F.paused,X(),F.on&&!F.paused&&F.focus&&Array.isArray(F.focus.box)&&F.focus.box.length===4&&(F.seq||0)>ye)ye=F.seq||ye,pe?.zoomToBoxMm([F.focus.box[0],F.focus.box[1],F.focus.box[2],F.focus.box[3]])}catch{}}function ce(){b.hidden=!0,b.replaceChildren(),pe?.setHighlights([])}function lt(I){let F=I.split(";").filter(Boolean),U=F.shift()||I,G=[],q="",ee="";for(let Ee of F){if(Ee.startsWith("g="))continue;let Te=Ee.indexOf("=");if(Te>0){let Ie=Ee.slice(0,Te),_e=Ee.slice(Te+1);if((Ie==="ref"||Ie==="symbol")&&!q)q=_e;if(Ie==="net"&&!ee)ee=_e;G.push([Ie,_e])}else G.push([Ee,""])}let te=document.createElement("div");te.className="bp-v-info-head";let ge=document.createElement("span");ge.className="bp-v-info-title",ge.textContent=U;let fe=document.createElement("button");fe.type="button",fe.className="bp-v-info-x",fe.textContent="×",fe.setAttribute("aria-label","Clear selection"),fe.addEventListener("click",ce),te.append(ge,fe);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Ee,Te]of G){let Ie=document.createElement("span");Ie.className="bp-v-info-chip",Ie.textContent=Te?`${Ee}: ${Te}`:Ee,Pe.append(Ie)}return b.replaceChildren(te,...G.length>0?[Pe]:[]),b.hidden=!1,{ref:q||void 0,net:ee||void 0}}async function Ye(I){if(!I){ce();return}let F=Array.from(k)[0]||"";if(!F)return;let U=E;try{let G=await t.hub.rpc("viewer.info",{key:F,at:I.at,idx:I.idx});if(U!==E)return;let q=typeof G.info==="string"?G.info:"";if(!q){ce();return}let{ref:ee,net:te}=lt(q),ge=[];if(ee)ge.push(["ref",ee]);if(te)ge.push(["net",te]);let fe=[[I.at,I.idx]];for(let[Pe,Ee]of ge){let Te=await t.hub.rpc("viewer.probe",{key:F,name:Pe,value:Ee});if(U!==E)return;if(Array.isArray(Te.matches))for(let Ie of Te.matches)fe.push(Ie)}pe?.setHighlights(fe)}catch{ce()}}function ct(){Z?.destroy(),Z=null,le?.destroy(),le=null,pe?.destroy(),pe=null,ne?.destroy(),ne=null,u.replaceChildren(),Le=!1,d.hidden=!0,b.hidden=!0,b.replaceChildren(),ue("",!1),de("none")}function Xe(){A=[],N=0}async function Ge(I){if(!f||!g)return;let F=++E;if(k.clear(),x=!1,Xe(),ct(),X(),K(),re(),(g==="board"||g==="schematic")&&f)ke(f);if(Js(g)){if(t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{}),g==="files")Z=$i(u,t,f,(q,ee)=>{if(g=q,he=ee,q==="mech")H=ee;Ge(!1)});else if(g==="diff")Z=Gi(u,t,f);else if(g==="review")Z=Ui(u,t,f);else if(g==="browser")Z=Hi(u,t,f);else if(g==="terminal")de("loading","Loading terminal…"),import("/assets/terminal.js").then((ee)=>{if(F!==E)return;if(de("none"),ee?.mountTerminalPane)le=ee.mountTerminalPane(u,t,f,He());else de("error","Terminal chunk missing",!0)},(ee)=>{if(F!==E)return;de("error",ee instanceof Error?ee.message:String(ee),!0)});return}if(de("loading","Loading…"),!W.root)try{let q=await t.hub.rpc("viewer.files",{thread:f});if(F!==E)return;W=q||{},X()}catch{}if(g==="gerbers"&&W.hasGerbers===!1){de("empty","No Gerbers in this project",!1);return}let U=He();if(g==="3d"||g==="mech")ne=new vn(u,{onStatus:(q,ee)=>{if(ee)de("none"),ue(q,!1);else if(q)de("loading",q);else de("none"),ue("",!1)},onUserMove:()=>void We()}),ne.setTheme(U);else if(g==="board"||g==="schematic"||g==="gerbers")pe=new hn(u,{onPick:(q)=>void Ye(q),onUserMove:()=>void We()}),pe.setTheme(U);else{de("empty",`${Yi(g)} is not available in this viewer`,!1);return}let G={thread:f};if(I)G.force=!0;if(g==="mech"){if(_.length===0)try{let q=await t.hub.rpc("mech.list",{thread:f});if(F!==E)return;if(_=Array.isArray(q.parts)?q.parts:[],!H)H=q.primary||_[0]||"";X()}catch(q){if(F!==E)return;de("error",q instanceof Error?q.message:String(q),!0);return}if(!H){de("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=H}else{if(G.kind=g,he&&(g==="board"||g==="schematic"))G.path=he;if(g==="3d"&&!I&&ne){let q=ne.keptToken();if(q)G.kept=q}if((g==="board"||g==="schematic"||g==="gerbers")&&!I&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(D.keys())}x=!0,S="",R="",Y="",T="";try{let q=await t.hub.rpc("viewer.watch",G);if(F!==E)return;k=new Set(Array.isArray(q.keys)?q.keys:[]),x=!1;let ee=A;Xe();for(let te of ee)if(te.kind==="bin")Ue(te.buf);else Ve(te.key,te.none,te.retryable)}catch(q){if(F!==E)return;x=!1,k.clear(),Xe();let ee=q instanceof Error?q.message:String(q),te=/no gerbers|not in this project|another machine/i.test(ee);de(te?"empty":"error",ee,!te)}}function Ve(I,F,U){if(x){if(A.length{if(I.t==="plot"&&typeof I.none==="string"&&typeof I.key==="string")Ve(I.key,I.none,I.retryable===!0)}),Ft=At(()=>{if(g)X()}),kt=(I)=>{if(I.key==="Escape"&&g&&!b.hidden)ce()};return window.addEventListener("keydown",kt),{open(I,F){if(F!==f){if(f=F,W={},_=[],H="",M.clear(),me=!1,se=!1,ye=0,Ae=0,we="",Be=0,B=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:F}).then((U)=>{if(F!==f)return;if(me=!!U.on,se=!!U.paused,ye=Number(U.seq)||0,g)X()}).catch(()=>{})}if(I!==g)J(),j.goLive(),Ae=0,we="",Be=0,B=null;g=I,he="",Ge(!1)},reconcileHas(I){if(g&&!zs(g,I))t.closeViewer()},close(){if(E++,x=!1,J(),C=!1,S="",R="",Y="",T="",j.goLive(),l.hidden=!0,y.hidden=!0,Xe(),f)t.hub.rpc("viewer.watch",{thread:f,kind:""}).catch(()=>{});g="",k.clear(),ct()}}}var Xi="http://www.w3.org/2000/svg";function Ct(e){let t=document.createElementNS(Xi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Xi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ys(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Zi(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function Qi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function Xs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function es(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let l=document.createElement("span");l.className="bp-crumb-sep bp-hide-phone",l.textContent="/";let m=document.createElement("span");m.className="bp-crumb-thread",m.setAttribute("data-testid","thread-title");let c=document.createElement("span");c.className="bp-plan-top-badge bp-hidden",c.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,l,m,c);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let p=document.createElement("span");p.className="bp-top-state-lbl",p.textContent="STATE";let d=document.createElement("span");d.className="bp-dot bp-dot-idle";let b=document.createElement("span");b.className="bp-top-state-word",u.append(p,d,b);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=h("menu.pin","Pin"),f.append(Ct(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let x=document.createElement("span");x.textContent=h("menu.settle","Settle"),E.append(Ct(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let k=document.createElement("div");k.className="bp-menu-wrap";let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost bp-top-act",A.textContent="▾",A.title="Thread menu",A.setAttribute("aria-label","Thread menu"),A.setAttribute("data-testid","thread-menu-btn");let N=document.createElement("div");N.className="bp-popover bp-hidden",N.setAttribute("data-testid","thread-menu"),k.append(A,N),y.append(f,E,k);let M=document.createElement("div");M.className="bp-top-right";let D=document.createElement("button");D.type="button",D.className="bp-btn-ghost bp-top-act bp-hide-tablet",D.setAttribute("data-testid","improvements-btn");let W=document.createElement("span");W.textContent=h("gpui.improvements","Improvements"),D.append(Ct(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),W);let _=document.createElement("button");_.type="button",_.className="bp-cmd-box bp-hide-tablet",_.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Ct(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let he=document.createElement("button");he.type="button",he.className="icon bp-top-icon",he.title=h("palette.settings","Settings"),he.setAttribute("aria-label",h("palette.settings","Settings")),he.setAttribute("data-testid","settings-btn"),he.appendChild(Ct(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),M.append(D,_,H,he),t.append(n,i,u,y,M);let me=document.createElement("div");me.className="bp-body";let se=document.createElement("aside");se.className="bp-sidebar",se.setAttribute("data-testid","sidebar");let ye=document.createElement("main");ye.className="bp-center";let Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ae=document.createElement("div");Ae.className="bp-right-top";let we=document.createElement("section");we.className="bp-viewer-pane bp-hidden",we.setAttribute("data-testid","viewer-pane"),Ae.appendChild(we),Le.appendChild(Ae);let Be=document.createElement("nav");Be.className="bp-rail",Be.setAttribute("aria-label","Viewer rail"),Be.setAttribute("data-testid","viewer-rail"),me.append(se,ye,Le,Be),e.append(t,me);let B=new mn,pe=null,ne=new Set,Z=0,le=null,j=[],z=[],C=[],S=[],R=[],Y=[],T="",J=0,K=0,Me=null,re=null,ke="",He=null,be=20,de={},ue=new Map;function Re(v,w){ue.delete(v),ue.set(v,w);while(ue.size>be){let L=ue.keys().next().value;if(L!==void 0)ue.delete(L);else break}}let X=new cn(se,{onSelectThread:(v)=>{if(v===T&&Me!==null){se.classList.remove("bp-sidebar-open");return}Ee(v)},onNewThread:(v)=>{Fe(v)},onSelectBot:(v)=>{Ee(v.thread)},onThreadAct:(v,w)=>{et(v,w)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ge()},onToggleProjectFold:(v)=>{B.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ge()).catch(()=>{})},onCollapseSidebar:()=>{se.classList.remove("bp-sidebar-open"),se.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let w=jt(v,!1);if(!w)return;if(w.kind==="thread"){Ee(w.id);return}if(w.kind!=="call")return;let L=wi(await B.rpc(w.method,w.params));if(L?.kind==="thread")Ee(L.id);ge()},hasRoomView:!1,onAddProject:()=>Ve.open({mode:"folder"})}),oe=new Kt(ye,{onLoadOlder:()=>{_e()},onGoToEntry:(v)=>{Ie(v)},onAnswerAsk:(v,w)=>{B.rpc("ask.answer",{ask:v,answer:w}).catch((L)=>{ce.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!T)return;let w=J;B.rpc("thread.review",{thread:T,on:v}).then((L)=>{if(w===J)oe.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,w)=>{if(!T)return;if(v==="again"||v==="thread-again")B.rpc("thread.again",{thread:T,value:w}).catch(()=>{});else B.rpc("thread.act",{thread:T,action:v,value:w}).catch(()=>{})},onReplyEntry:(v)=>{if(!B.hasFeature("reply")){let w=(v.text||"").split(` `)[0]?.slice(0,100)??"";if(w)ce.prependDraft(`> ${w} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Ve({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,w)=>{try{let L={entry:v,path:w};if(B.hasFeature("blobs"))L.metaOnly=!0;let P=await B.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function je(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function We(v,w){if(!T)return;let L=z,P=T;B.rpc(v,w).then((V)=>{if(L!==z||T!==P)return;if(V.thread){let ie=Y.findIndex((ve)=>ve.id===V.thread.id);if(ie>=0)Y[ie]=V.thread;else Y.unshift(V.thread);X.setData(j,Y,C,S),oe.updateThreadMeta(V.thread),I(),ce.setState(!0,V.thread.state==="working")}}).catch((V)=>{if(L===z&&T===P)ce.showError(V instanceof Error?V.message:"Could not change Plan mode")})}let Ke,ce=new Jt(ye,{onSend:(v,w)=>{En(v,w)},onRunCommand:(v)=>{xn(v)},onInterrupt:()=>{if(T)B.rpc("turn.interrupt",{thread:T}).catch(()=>{})},onQueryMentions:async(v,w)=>{try{return(await B.rpc("mentions.list",{q:v,kind:w,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Ke.toggle()},onCyclePlanMode:()=>{let v=Y.find((L)=>L.id===T)??null,w=je(v);if(!w||!T)return;if(w.interaction!=="plan")We("thread.planonce",{thread:T,on:!0});else if(w.once)We("thread.pick",{thread:T,action:"interaction",value:"plan"});else We("thread.pick",{thread:T,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!T)return;if(v==="once")We("thread.planonce",{thread:T,on:!0});else if(v==="always")We("thread.pick",{thread:T,action:"interaction",value:"plan"});else We("thread.pick",{thread:T,action:"interaction",value:"default"})}});Ke=new dn(B,{getThreadId:()=>T,getDraft:()=>ce.getDraft(),getCaret:()=>ce.getCaret(),setDraft:(v)=>ce.setDraft(v),setRecording:(v)=>ce.setVoiceRecording(v),setLevel:(v)=>ce.setVoiceLevel(v),showError:(v)=>ce.showError(v)});function lt(){let v=ke!=="",w=Ye.isOpen();Le.classList.toggle("bp-hidden",!v&&!w),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",w)}let Ye=new nn(Ae,Le,{hub:B,getThreadId:()=>T,getThreadGen:()=>z,onSendText:(v)=>{En(v)},onOpenChange:()=>lt()});function ct(v){let w=window.prompt("Rename thread",v.title||"");if(!w||!w.trim())return;B.rpc("thread.act",{thread:v.id,action:"rename",title:w.trim()}).then((L)=>{if(L.thread)Y=Y.map((P)=>P.id===L.thread.id?L.thread:P),I(),ge()}).catch((L)=>{ce.showError(L instanceof Error?L.message:"Could not rename thread")})}function Xe(v){switch(v.type){case"thread":Ee(v.id);break;case"rail":if(!T&&v.id!=="terminal")break;if(ke===v.id)F();else O(v.id);break;case"thread-act":if(T)et(T,v.action);break;case"new-thread":Fe(v.projectId);break;case"rename":{let w=Y.find((L)=>L.id===T);if(w)ct(w);break}case"prev-thread":case"next-thread":{let w=Y.filter((ie)=>!ie.archived&&!ie.swarm);if(w.length<2)break;let L=w.findIndex((ie)=>ie.id===T),P=v.type==="next-thread"?1:-1,V=w[(L<0?0:L+P+w.length)%w.length];if(V)Ee(V.id);break}case"command":if(v.runDirectly)xn(v.word);else ce.setDraft(`${v.word} `),ce.focus();break;case"improvements":kt();break;case"settings":ze.open();break;case"sidebar":se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed");break}}let Ge=new sn(e,{getState:()=>({selectedThreadId:T,threads:Y,projects:j,bots:C,railItems:R,commands:q}),onSearch:async(v)=>{if(!B.hasFeature("search"))return{threads:[],projects:[],messages:[]};return B.rpc("search",{q:v,limit:20})},onExecute:Xe}),Ue=new Wt(e,{hub:B,onProjectAdded:(v)=>{if(ge(),v.id)Fe(v.id)},onCloneDone:(v)=>{if(ge(),v.thread)Ee(v.thread)}}),Oe=new an(Be,(v)=>{if(v==="commands"){Ge.open();return}if(!T)return;if(ke===v)F();else O(v)}),it=null,ze=new rn(e,{onLoadDevices:async()=>(await B.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,w)=>{await B.rpc("devices.page.act",{action:v,value:w})},onGetHome:()=>it,onMoveHomeHere:async()=>{await B.rpc("home.move",{to:"back"})},onLogout:()=>Dn(()=>{B.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=Y.find((w)=>w.id===T);if(v)et(v.id,v.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let v=Y.find((w)=>w.id===T);if(v)et(v.id,v.settled?"unsettle":"settle")});let Ft=new ln(e,(v,w)=>w?B.rpc("thread.context.mcp",{thread:v,...w}):B.rpc("thread.context",{thread:v}));A.addEventListener("click",(v)=>{v.stopPropagation();let w=Y.find((V)=>V.id===T);if(!w)return;if(!N.classList.contains("bp-hidden")){N.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ct(w)},{label:w.pinned?u("menu.unpin","Unpin"):u("menu.pin","Pin"),run:()=>{et(w.id,w.pinned?"unpin":"pin")}},{label:w.settled?u("phone.unsettle","Unsettle"):u("menu.settle","Settle"),run:()=>{et(w.id,w.settled?"unsettle":"settle")}},{label:w.archived?"Unarchive":"Archive",run:()=>{et(w.id,w.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))et(w.id,"delete")}}];if(B.hasFeature("threadContext"))L.unshift({label:u("thread.context.title","Context & Prompt"),run:()=>Ft.open(w.id)});let P=document.createDocumentFragment();for(let V of L){let ie=document.createElement("button");ie.type="button",ie.className="bp-popover-item"+(V.danger?" danger":""),ie.textContent=V.label,ie.addEventListener("click",()=>{N.classList.add("bp-hidden"),V.run()}),P.appendChild(ie)}N.replaceChildren(P),N.classList.remove("bp-hidden")}),document.addEventListener("click",()=>N.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let w=document.createElement("div");w.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=u("gpui.improvements","Improvements");let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>v.remove()),L.append(P,V);let ie=document.createElement("div");ie.className="bp-modal-body",ie.textContent="Loading…",w.append(L,ie),v.appendChild(w),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await B.rpc("improvements.projects",{}),De=ve.projects??[];if(De.length===0){ie.textContent="No projects available for Improvements.";return}let tt=document.createDocumentFragment();for(let Se of De){let ae=document.createElement("div");ae.className="bp-set-row";let Qe=document.createElement("div");Qe.className="bp-set-info",Qe.textContent=Se.title||Se.name||Se.id;let nt=document.createElement("button");nt.type="button",nt.className=Se.id===ve.project?"primary":"",nt.textContent=Se.id===ve.project?"Active":"Select",nt.addEventListener("click",()=>{B.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),ae.append(Qe,nt),tt.appendChild(ae)}ie.replaceChildren(tt)}catch(ve){ie.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}D.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>Ge.open()),H.addEventListener("click",()=>Ge.open()),ue.addEventListener("click",()=>{ze.open()}),n.addEventListener("click",()=>{se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed")});function I(){let v=Y.find((P)=>P.id===T)??null,w=v?j.find((P)=>P.id===v.project):void 0;o.textContent=w?.title??"",r.classList.toggle("bp-hidden",!w),l.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let L=je(v);if(ce.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=u("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?u("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?u("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?u("gpui.planmode.top.planning","Planning"):L.phase==="pending"?u("gpui.planmode.top.pending","Review plan"):u("gpui.planmode.top.executing","Building plan");if(h.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){d.className=`bp-dot ${Ys(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?u("menu.unpin","Unpin"):u("menu.pin","Pin"),x.textContent=v.settled?u("phone.unsettle","Unsettle"):u("menu.settle","Settle");let P=v;ce.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),ce.setMemory(v.memory)}else ce.setModelChip("default"),ce.setMemory(null)}function F(v=!0){if(J++,ke="",Oe.setActive(""),we.classList.add("bp-hidden"),He?.close(),lt(),v&&T&&B.getState()==="connected")B.rpc("viewer.watch",{thread:T,kind:""}).catch(()=>{})}function O(v){if(J++,ke=v,Oe.setActive(v),we.classList.remove("bp-hidden"),lt(),!He&&typeof wn==="function")He=wn(we,{hub:B,getThreadId:()=>T,closeViewer:()=>F(!0)});if(He)He.open(v,T);else{let w=document.createElement("div");w.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let V=document.createElement("button");V.type="button",V.className="icon",V.textContent="×",V.addEventListener("click",()=>F(!0)),L.append(P,V);let ie=document.createElement("div");ie.className="bp-dim bp-viewer-msg",ie.textContent=`Viewer pane (${v}).`,w.append(L,ie),we.replaceChildren(w)}}async function G(v,w){if(!v||!B.hasFeature("rail")){if(w===z)R=[],Oe.setItems([]);return}let L=++J;try{let P=await B.rpc("viewer.rail",{thread:v,page:ke});if(w!==z||L!==J)return;let V=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(R=V,Oe.setItems(V),P.has){if(He?.reconcileHas?.(P.has),ke&&!Zi(P.has,ke))F(!0)}}catch{if(w===z&&L===J)R=[],Oe.setItems([])}}function K(v){for(let w of v)if(w.kind==="threads"){for(let L of w.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(w.kind==="projects"){for(let L of w.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function ee(v,w){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===w))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((V)=>(V.nav||V.id)===w))return!0}return!1}function te(v){let w=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)w.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(w.length>0)j=w}async function ge(){if(!B.hasFeature("sections"))return!1;let v=++Z;try{let w=await B.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==Z)return!0;let L=Array.isArray(w.sections)?w.sections:[];return pe=L,te(L),X.setData(j,Y,C,S),X.setSections(L,C,S),I(),!0}catch{return!1}}function fe(){if(!B.hasFeature("sections"))return;if(le!==null)window.clearTimeout(le);le=window.setTimeout(()=>{le=null,ge()},150)}async function Pe(){if(Me=null,B.hasFeature("bots"))try{let w=await B.rpc("bots.list",{});C=w.bots??[],S=w.rooms??[]}catch{}if(B.hasFeature("shell")){let w=await B.rpc("shell.sync",{have:de,settled:25}),L=new Set(w.removed??[]),P=new Set((w.projects??[]).map((V)=>V.id));if(L.size>0||P.size>0)j=[...j.filter((V)=>!L.has(V.id)&&!P.has(V.id)),...w.projects??[]],Y=[...Y.filter((V)=>!L.has(V.project)&&!P.has(V.project)),...w.threads??[]];else if(Array.isArray(w.threads)&&w.threads.length>0){let V=new Map(Y.map((ie)=>[ie.id,ie]));for(let ie of w.threads)V.set(ie.id,ie);Y=Array.from(V.values())}if(w.sections!==void 0){let V=Array.isArray(w.sections)?w.sections:Array.isArray(w.sections?.sections)?w.sections.sections:null;if(V)pe=V,te(V)}if(w.h)de=w.h;X.setData(j,Y,C,S),X.setSections(pe,C,S)}else if(B.hasFeature("sections")){let[w,L]=await Promise.all([B.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),B.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(Y=L.threads??[],w&&Array.isArray(w.sections)){let P=w.sections;if(!P.some((ie)=>ie.kind==="projects"&&ie.rows.length>0)){let ie=P.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(ie?.toggle&&!ne.has(ie.toggle)){ne.add(ie.toggle);let ve=await B.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))P=ve.sections}}pe=P,te(P),X.setData(j,Y,C,S),X.setSections(P,C,S)}else pe=null,j=(await B.rpc("projects.list",{limit:100})).projects??[],X.setSections(null,C,S),X.setData(j,Y,C,S);await B.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{pe=null;let[w,L]=await Promise.all([B.rpc("projects.list",{limit:100}),B.rpc("threads.list",{limit:200,archived:!1})]);j=w.projects??[],Y=L.threads??[],X.setSections(null,C,S),X.setData(j,Y,C,S),await B.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=T;if(!v){let w="";try{w=localStorage.getItem("bp.lastThread")||""}catch{}if(w&&(pe&&ee(pe,w)||Y.some((L)=>L.id===w)))v=w;else if(pe)v=K(pe);if(!v)v=(Y.find((P)=>!P.archived&&!P.swarm&&!P.settled)??Y.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(pe&&ee(pe,v)||Y.some((w)=>w.id===v)))await Ee(v);else T="",R=[],Oe.setItems([]),ce.setState(!1,!1),I()}async function Ee(v){if(T&&T!==v){Ke.cancel();let Se=oe.getEntries();if(Se.length>0){let ae=he.get(T);Re(T,{entries:Se,ids:ae?.ids??Se.map((Qe)=>Qe.id),olderCursor:re,review:ae?.review??null,unanswered:ae?.unanswered??null,rail:ae?.rail??R,hashes:ae?.hashes??{}})}}let w=++z;J++,Ve(null);let L=Me;if(Me=null,L!==null)B.rpc("unsubscribe",{sub:L}).catch(()=>{});T=v;let P=he.get(v);re=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}X.setSelected(v),se.classList.remove("bp-sidebar-open"),I();let V=Y.find((Se)=>Se.id===v)??null;if(P)oe.setThread(V,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),R=P.rail,Oe.setItems(P.rail);else oe.setLoading(V),R=[],Oe.setItems([]);if(ce.setState(!0,V?.state==="working"),B.hasFeature("open")){let Se={};if(P){for(let[Ne,pt]of Object.entries(P.hashes))Se[Ne]=pt;for(let Ne of P.entries)if(Ne.h)Se[Ne.id]=Ne.h}let ae;try{ae=await B.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Ne){if(w===z){let pt=Ne instanceof Error&&Ne.message?Ne.message:"Could not load messages.";oe.setError(V,pt,()=>{Ee(v)})}return}if(w!==z){if(ae.sub!==void 0&&ae.sub!==null)B.rpc("unsubscribe",{sub:ae.sub}).catch(()=>{});return}if(Me=ae.sub??null,ae.thread){V=ae.thread;let Ne=Y.findIndex((pt)=>pt.id===ae.thread.id);if(Ne>=0)Y[Ne]=ae.thread;else Y.unshift(ae.thread);I(),ce.setState(!0,V.state==="working")}if("next"in ae)re=ae.next??null;let Qe=new Map;if(P)for(let Ne of P.entries)Qe.set(Ne.id,Ne);for(let Ne of ae.entries??[])Qe.set(Ne.id,Ne);let nt=ae.ids??P?.ids??(ae.entries??[]).map((Ne)=>Ne.id),kn=nt.map((Ne)=>Qe.get(Ne)).filter((Ne)=>Boolean(Ne)),dt=P?.rail??[];if(ae.rail!==void 0){if(Array.isArray(ae.rail))dt=ae.rail;else if(dt=Array.isArray(ae.rail?.rail)?ae.rail.rail:Array.isArray(ae.rail?.items)?ae.rail.items:[],ae.rail?.has){if(He?.reconcileHas?.(ae.rail.has),ke&&!Zi(ae.rail.has,ke))F(!0)}}R=dt,Oe.setItems(dt);let $t=P?.review??null;if(B.hasFeature("reviewmode"))try{let Ne=await B.rpc("thread.review",{thread:v});if(w!==z)return;$t=Ne.review??null}catch{}if(w!==z)return;let Sn="unanswered"in ae?ae.unanswered??null:P?.unanswered??null,ts=ae.h??P?.hashes??{};if(Re(v,{entries:kn,ids:nt,olderCursor:re,review:$t,unanswered:Sn,rail:dt,hashes:ts}),oe.setThread(V,kn,Boolean(re),$t,Sn),Te(v,w),ke)O(ke);return}let ie;try{ie=await B.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(w===z){let ae=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";oe.setError(V,ae,()=>{Ee(v)})}return}if(w!==z)return;if(ie.thread){let Se=Y.findIndex((ae)=>ae.id===ie.thread.id);if(Se>=0)Y[Se]=ie.thread;else Y.unshift(ie.thread);I()}re=ie.next??null;let ve=null;if(B.hasFeature("reviewmode"))try{let Se=await B.rpc("thread.review",{thread:v});if(w!==z)return;ve=Se.review??null}catch{}if(w!==z)return;let De=ie.entries??[],tt=ie.unanswered??null;Re(v,{entries:De,ids:De.map((Se)=>Se.id),olderCursor:re,review:ve,unanswered:tt,rail:P?.rail??[],hashes:P?.hashes??{}}),oe.setThread(V,De,Boolean(re),ve,tt);try{let ae=(await B.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(ae!==null){if(w!==z){B.rpc("unsubscribe",{sub:ae}).catch(()=>{});return}Me=ae}}catch{}if(w!==z)return;if(G(v,w),Te(v,w),ke)O(ke)}async function Te(v,w){if(!v||!B.hasFeature("mgmt")){if(w===z)Ye.clear();return}let L=Y.find((V)=>V.id===v),P=L?.project?j.find((V)=>V.id===L.project)?.root??"":"";if(!P&&B.hasFeature("viewers"))try{let V=await B.rpc("viewer.files",{thread:v});if(w!==z)return;P=V.pcb||V.sch||V.root||""}catch{}if(w!==z)return;if(P)await Ye.watchProject(P);else Ye.clear()}async function Ie(v){let w=z;for(let L=0;L<25&&w===z;L++){if(oe.goTo(v))return;if(!re)return;let P=re;if(await _e(),re===P)return}}async function _e(){if(!T||!re){oe.clearLoadingOlder();return}let v=z,w=T,L=re;try{let P=await B.rpc("thread.entries",{thread:w,limit:40,before:L});if(v!==z||T!==w)return;re=P.next??null,oe.prependEntries(P.entries??[],Boolean(re))}catch{if(v===z)oe.clearLoadingOlder()}}async function Fe(v){try{let w=await B.rpc("thread.create",{project:v});if(w.thread)Y=[w.thread,...Y.filter((L)=>L.id!==w.thread.id)],X.setData(j,Y,C,S),ge(),await Ee(w.thread.id),ce.focus()}catch(w){ce.showError(w instanceof Error?w.message:"Could not create thread")}}let Ze=null;function St(v){return(v.split(` -`).map((w)=>w.trim()).find((w)=>w.length>0)??"").slice(0,200)}function Ve(v){Ze=v,ce.setReply(v?{who:v.role==="user"?u("secret.you","You"):u("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Ze)Ie(Ze.id)},()=>Ve(null))}async function En(v,w=[]){if(!T)return;let L=z,P=T,V=Xs(),ie=`local-${V}`,ve=Ze&&v.trim()&&B.hasFeature("reply")?Ze:null;if(ve)Ve(null);oe.upsertEntry({id:ie,kind:"user",text:v,at:Date.now(),clientId:V,...ve?{replyTo:{id:ve.id,quote:St(ve.text)}}:{},attachments:w.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:P,text:v,clientId:V};if(w.length>0)De.attachments=w;if(ve)De.replyTo={id:ve.id,text:ve.text};let tt=await B.rpc("message.send",De);if(L!==z||T!==P)return;if(tt.entry)oe.upsertEntry(tt.entry)}catch(De){if(L===z&&T===P){if(oe.removeEntry(ie),ce.setDraft(v),ve&&!Ze)Ve(ve);ce.showError(De instanceof Error?De.message:"Failed to send message")}}}async function xn(v){if(!T)return;let w=z,L=T;try{let P=await B.rpc("composer.run",{thread:L,text:v});if(w!==z||T!==L)return;if(P.error)ce.setDraft(v),ce.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")ce.setDraft(P.text);else if(P.kind==="project")Ue.open({mode:"folder"});else if(P.kind==="clone")Ue.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(w===z&&T===L)ce.setDraft(v),ce.showError(P instanceof Error?P.message:"Command refused")}}async function et(v,w){try{let L=await B.rpc("thread.act",{thread:v,action:w});if(L.thread){if(Y=Y.map((P)=>P.id===L.thread.id?L.thread:P),X.setData(j,Y,C,S),L.thread.id===T)oe.updateThreadMeta(L.thread),I()}ge()}catch(L){ce.showError(L instanceof Error?L.message:`Action "${w}" not allowed`)}}function Cn(v,w){if(!v||!v.text||w-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return u("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return u("hub.stopped",v.text);return u("hub.restarting",v.text)}function Lt(v){if(v==="connected")X.setConnStatus(u("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Cn(B.restarting,Date.now()))X.setConnStatus(Cn(B.restarting,Date.now()),"");else if(v==="reconnecting")X.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")X.setConnStatus(u("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else X.setConnStatus("Connecting…","")}At(()=>{Lt(B.getState()),W.textContent=u("gpui.improvements","Improvements"),ue.title=u("palette.settings","Settings"),ue.setAttribute("aria-label",u("palette.settings","Settings")),I(),X.refreshLocale(),oe.refreshLocale(),ce.refreshLocale(),Oe.render(),ze.refreshLocale(),Ue.refreshLocale()}),B.onState((v,w)=>{if(v==="connected"&&w){if(w.locale)Tn(w.locale);if(w.theme)Qi(w.theme);if(w.name)X.setHostName(w.name);if(it=w.home??null,X.setHome(it),ze.isOpen())ze.refresh();Lt(v);let L=typeof w.hubBack==="string"?String(w.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")X.setConnStatus(u("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Lt(B.getState()),6000)}catch{}if(ce.setFeatures(B.hasFeature("images"),B.hasFeature("voice")),Array.isArray(w.commands))q=w.commands,ce.setCommands(q);else q=[];Pe(),Ue.reconcile()}else Ke.cancel(),Lt(v)}),B.onFrame((v)=>{if(v.t==="voice"){Ke.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Ye.handleInfo(v.info);return}if(v.t!=="d")return;let w=v;if(w.k==="clone"||w.k==="clone.repos"||w.k==="clone.signin"){Ue.handleFrame(w);return}switch(w.k){case"project":{let L=w.project;if(!L)break;let P=j.findIndex((V)=>V.id===L.id);if(P>=0)j[P]=L;else j.unshift(L);X.setData(j,Y,C,S),I(),fe();break}case"thread":{let L=w.thread;if(!L)break;let P=Y.findIndex((V)=>V.id===L.id);if(P>=0)Y[P]=L;else Y.unshift(L);if(X.setData(j,Y,C,S),L.id===T)oe.updateThreadMeta(L),I(),ce.setState(!0,L.state==="working");fe();break}case"thread.removed":{let L=String(w.id??"");Y=Y.filter((P)=>P.id!==L),X.setData(j,Y,C,S),fe();break}case"entry":{if(w.thread===T&&w.entry)oe.upsertEntry(w.entry);break}case"text":{if(w.thread===T)oe.appendLiveText(String(w.entry??""),String(w.append??""),Number(w.at??Date.now()));break}case"turn":{if(w.thread===T){let L=String(w.state??"idle");ce.setState(!0,L==="working"),G(T,z)}fe();break}case"btw":{if(w.thread===T)oe.showBtw(String(w.q??""),String(w.a??""));break}case"unanswered":{if(w.thread===T)oe.setUnanswered(w.unanswered??null);break}case"theme":{if(typeof w.theme==="string")Qi(w.theme);break}case"home":{if(it=w.home??null,X.setHome(it),ze.isOpen())ze.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let w=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(w==="k"||v.shiftKey&&w==="p"))if(v.preventDefault(),Ge.isOpen())Ge.close();else Ge.open();else if(v.key==="Escape"){if(Ge.isOpen())Ge.close();else if(Ue.isOpen())Ue.escape();else if(ze.isOpen())ze.close();else if(oe.closePlanRevise());else if(Ye.isOpen())Ye.closePanel()}}),B.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",es);else es(); +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;Oe({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,w)=>{try{let L={entry:v,path:w};if(B.hasFeature("blobs"))L.metaOnly=!0;let P=await B.rpc("message.image",L);if(P.blob&&P.blob.startsWith("/blob/"))return{url:P.blob};if(P.mime&&P.data)return{mime:P.mime,data:P.data}}catch{}return null}});function je(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function We(v,w){if(!T)return;let L=J,P=T;B.rpc(v,w).then((O)=>{if(L!==J||T!==P)return;if(O.thread){let ie=z.findIndex((ve)=>ve.id===O.thread.id);if(ie>=0)z[ie]=O.thread;else z.unshift(O.thread);X.setData(j,z,C,S),oe.updateThreadMeta(O.thread),I(),ce.setState(!0,O.thread.state==="working")}}).catch((O)=>{if(L===J&&T===P)ce.showError(O instanceof Error?O.message:"Could not change Plan mode")})}let Ke,ce=new Jt(ye,{onSend:(v,w)=>{En(v,w)},onRunCommand:(v)=>{xn(v)},onInterrupt:()=>{if(T)B.rpc("turn.interrupt",{thread:T}).catch(()=>{})},onQueryMentions:async(v,w)=>{try{return(await B.rpc("mentions.list",{q:v,kind:w,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Ke.toggle()},onCyclePlanMode:()=>{let v=z.find((L)=>L.id===T)??null,w=je(v);if(!w||!T)return;if(w.interaction!=="plan")We("thread.planonce",{thread:T,on:!0});else if(w.once)We("thread.pick",{thread:T,action:"interaction",value:"plan"});else We("thread.pick",{thread:T,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!T)return;if(v==="once")We("thread.planonce",{thread:T,on:!0});else if(v==="always")We("thread.pick",{thread:T,action:"interaction",value:"plan"});else We("thread.pick",{thread:T,action:"interaction",value:"default"})}});Ke=new dn(B,{getThreadId:()=>T,getDraft:()=>ce.getDraft(),getCaret:()=>ce.getCaret(),setDraft:(v)=>ce.setDraft(v),setRecording:(v)=>ce.setVoiceRecording(v),setLevel:(v)=>ce.setVoiceLevel(v),showError:(v)=>ce.showError(v)});function lt(){let v=ke!=="",w=Ye.isOpen();Le.classList.toggle("bp-hidden",!v&&!w),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",w)}let Ye=new nn(Ae,Le,{hub:B,getThreadId:()=>T,getThreadGen:()=>J,onSendText:(v)=>{En(v)},onOpenChange:()=>lt()});function ct(v){let w=window.prompt("Rename thread",v.title||"");if(!w||!w.trim())return;B.rpc("thread.act",{thread:v.id,action:"rename",title:w.trim()}).then((L)=>{if(L.thread)z=z.map((P)=>P.id===L.thread.id?L.thread:P),I(),ge()}).catch((L)=>{ce.showError(L instanceof Error?L.message:"Could not rename thread")})}function Xe(v){switch(v.type){case"thread":Ee(v.id);break;case"rail":if(!T&&v.id!=="terminal")break;if(ke===v.id)F();else U(v.id);break;case"thread-act":if(T)et(T,v.action);break;case"new-thread":Fe(v.projectId);break;case"rename":{let w=z.find((L)=>L.id===T);if(w)ct(w);break}case"prev-thread":case"next-thread":{let w=z.filter((ie)=>!ie.archived&&!ie.swarm);if(w.length<2)break;let L=w.findIndex((ie)=>ie.id===T),P=v.type==="next-thread"?1:-1,O=w[(L<0?0:L+P+w.length)%w.length];if(O)Ee(O.id);break}case"command":if(v.runDirectly)xn(v.word);else ce.setDraft(`${v.word} `),ce.focus();break;case"improvements":kt();break;case"settings":ze.open();break;case"sidebar":se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed");break}}let Ge=new sn(e,{getState:()=>({selectedThreadId:T,threads:z,projects:j,bots:C,railItems:R,commands:Y}),onSearch:async(v)=>{if(!B.hasFeature("search"))return{threads:[],projects:[],messages:[]};return B.rpc("search",{q:v,limit:20})},onExecute:Xe}),Ve=new Wt(e,{hub:B,onProjectAdded:(v)=>{if(ge(),v.id)Fe(v.id)},onCloneDone:(v)=>{if(ge(),v.thread)Ee(v.thread)}}),Ue=new an(Be,(v)=>{if(v==="commands"){Ge.open();return}if(!T)return;if(ke===v)F();else U(v)}),it=null,ze=new rn(e,{onLoadDevices:async()=>(await B.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,w)=>{await B.rpc("devices.page.act",{action:v,value:w})},onGetHome:()=>it,onMoveHomeHere:async()=>{await B.rpc("home.move",{to:"back"})},onLogout:()=>Dn(()=>{B.disconnect(),window.location.replace("/")})});f.addEventListener("click",()=>{let v=z.find((w)=>w.id===T);if(v)et(v.id,v.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let v=z.find((w)=>w.id===T);if(v)et(v.id,v.settled?"unsettle":"settle")});let Ft=new ln(e,(v,w)=>w?B.rpc("thread.context.mcp",{thread:v,...w}):B.rpc("thread.context",{thread:v}));A.addEventListener("click",(v)=>{v.stopPropagation();let w=z.find((O)=>O.id===T);if(!w)return;if(!N.classList.contains("bp-hidden")){N.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>ct(w)},{label:w.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{et(w.id,w.pinned?"unpin":"pin")}},{label:w.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{et(w.id,w.settled?"unsettle":"settle")}},{label:w.archived?"Unarchive":"Archive",run:()=>{et(w.id,w.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))et(w.id,"delete")}}];if(B.hasFeature("threadContext"))L.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>Ft.open(w.id)});let P=document.createDocumentFragment();for(let O of L){let ie=document.createElement("button");ie.type="button",ie.className="bp-popover-item"+(O.danger?" danger":""),ie.textContent=O.label,ie.addEventListener("click",()=>{N.classList.add("bp-hidden"),O.run()}),P.appendChild(ie)}N.replaceChildren(P),N.classList.remove("bp-hidden")}),document.addEventListener("click",()=>N.classList.add("bp-hidden"));async function kt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let w=document.createElement("div");w.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let P=document.createElement("h2");P.textContent=h("gpui.improvements","Improvements");let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>v.remove()),L.append(P,O);let ie=document.createElement("div");ie.className="bp-modal-body",ie.textContent="Loading…",w.append(L,ie),v.appendChild(w),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await B.rpc("improvements.projects",{}),De=ve.projects??[];if(De.length===0){ie.textContent="No projects available for Improvements.";return}let tt=document.createDocumentFragment();for(let Se of De){let ae=document.createElement("div");ae.className="bp-set-row";let Qe=document.createElement("div");Qe.className="bp-set-info",Qe.textContent=Se.title||Se.name||Se.id;let nt=document.createElement("button");nt.type="button",nt.className=Se.id===ve.project?"primary":"",nt.textContent=Se.id===ve.project?"Active":"Select",nt.addEventListener("click",()=>{B.rpc("improvements.project",{project:Se.id}).then(()=>v.remove()).catch(()=>{})}),ae.append(Qe,nt),tt.appendChild(ae)}ie.replaceChildren(tt)}catch(ve){ie.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}D.addEventListener("click",()=>{kt()}),_.addEventListener("click",()=>Ge.open()),H.addEventListener("click",()=>Ge.open()),he.addEventListener("click",()=>{ze.open()}),n.addEventListener("click",()=>{se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed")});function I(){let v=z.find((P)=>P.id===T)??null,w=v?j.find((P)=>P.id===v.project):void 0;o.textContent=w?.title??"",r.classList.toggle("bp-hidden",!w),l.classList.toggle("bp-hidden",!v),m.textContent=v?v.title||"Untitled thread":"";let L=je(v);if(ce.setPlanMode(L),!L||L.phase==="off")c.classList.add("bp-hidden"),c.classList.remove("is-exec"),c.textContent="";else c.classList.remove("bp-hidden"),c.classList.toggle("is-exec",L.phase==="executing"),c.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),c.textContent=L.phase==="armed"&&L.once?h("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?h("gpui.planmode.top.planning","Planning"):L.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),y.classList.toggle("bp-hidden",!v),v){d.className=`bp-dot ${Ys(v)}`,b.textContent=v.status||v.state||"idle",g.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),x.textContent=v.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle");let P=v;ce.setModelChip(v.chip||v.model||"default",v.provider,P.ctxPct??P.contextPct),ce.setMemory(v.memory)}else ce.setModelChip("default"),ce.setMemory(null)}function F(v=!0){if(K++,ke="",Ue.setActive(""),we.classList.add("bp-hidden"),He?.close(),lt(),v&&T&&B.getState()==="connected")B.rpc("viewer.watch",{thread:T,kind:""}).catch(()=>{})}function U(v){if(K++,ke=v,Ue.setActive(v),we.classList.remove("bp-hidden"),lt(),!He&&typeof wn==="function")He=wn(we,{hub:B,getThreadId:()=>T,closeViewer:()=>F(!0)});if(He)He.open(v,T);else{let w=document.createElement("div");w.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let P=document.createElement("span");P.textContent=v.toUpperCase();let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>F(!0)),L.append(P,O);let ie=document.createElement("div");ie.className="bp-dim bp-viewer-msg",ie.textContent=`Viewer pane (${v}).`,w.append(L,ie),we.replaceChildren(w)}}async function G(v,w){if(!v||!B.hasFeature("rail")){if(w===J)R=[],Ue.setItems([]);return}let L=++K;try{let P=await B.rpc("viewer.rail",{thread:v,page:ke});if(w!==J||L!==K)return;let O=Array.isArray(P.rail)?P.rail:Array.isArray(P.items)?P.items:[];if(R=O,Ue.setItems(O),P.has){if(He?.reconcileHas?.(P.has),ke&&!Zi(P.has,ke))F(!0)}}catch{if(w===J&&L===K)R=[],Ue.setItems([])}}function q(v){for(let w of v)if(w.kind==="threads"){for(let L of w.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(w.kind==="projects"){for(let L of w.rows)for(let P of L.threads??[])if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}return""}function ee(v,w){for(let L of v)if(L.kind==="threads"){if(L.rows.some((P)=>(P.nav||P.id)===w))return!0}else if(L.kind==="projects"){for(let P of L.rows)if((P.threads??[]).some((O)=>(O.nav||O.id)===w))return!0}return!1}function te(v){let w=[];for(let L of v){if(L.kind!=="projects")continue;for(let P of L.rows)w.push({id:P.id,title:P.title,css:P.css,color:P.color})}if(w.length>0)j=w}async function ge(){if(!B.hasFeature("sections"))return!1;let v=++Z;try{let w=await B.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==Z)return!0;let L=Array.isArray(w.sections)?w.sections:[];return pe=L,te(L),X.setData(j,z,C,S),X.setSections(L,C,S),I(),!0}catch{return!1}}function fe(){if(!B.hasFeature("sections"))return;if(le!==null)window.clearTimeout(le);le=window.setTimeout(()=>{le=null,ge()},150)}async function Pe(){if(Me=null,B.hasFeature("bots"))try{let w=await B.rpc("bots.list",{});C=w.bots??[],S=w.rooms??[]}catch{}if(B.hasFeature("shell")){let w=await B.rpc("shell.sync",{have:de,settled:25}),L=new Set(w.removed??[]),P=new Set((w.projects??[]).map((O)=>O.id));if(L.size>0||P.size>0)j=[...j.filter((O)=>!L.has(O.id)&&!P.has(O.id)),...w.projects??[]],z=[...z.filter((O)=>!L.has(O.project)&&!P.has(O.project)),...w.threads??[]];else if(Array.isArray(w.threads)&&w.threads.length>0){let O=new Map(z.map((ie)=>[ie.id,ie]));for(let ie of w.threads)O.set(ie.id,ie);z=Array.from(O.values())}if(w.sections!==void 0){let O=Array.isArray(w.sections)?w.sections:Array.isArray(w.sections?.sections)?w.sections.sections:null;if(O)pe=O,te(O)}if(w.h)de=w.h;X.setData(j,z,C,S),X.setSections(pe,C,S)}else if(B.hasFeature("sections")){let[w,L]=await Promise.all([B.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),B.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(z=L.threads??[],w&&Array.isArray(w.sections)){let P=w.sections;if(!P.some((ie)=>ie.kind==="projects"&&ie.rows.length>0)){let ie=P.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(ie?.toggle&&!ne.has(ie.toggle)){ne.add(ie.toggle);let ve=await B.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))P=ve.sections}}pe=P,te(P),X.setData(j,z,C,S),X.setSections(P,C,S)}else pe=null,j=(await B.rpc("projects.list",{limit:100})).projects??[],X.setSections(null,C,S),X.setData(j,z,C,S);await B.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{pe=null;let[w,L]=await Promise.all([B.rpc("projects.list",{limit:100}),B.rpc("threads.list",{limit:200,archived:!1})]);j=w.projects??[],z=L.threads??[],X.setSections(null,C,S),X.setData(j,z,C,S),await B.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=T;if(!v){let w="";try{w=localStorage.getItem("bp.lastThread")||""}catch{}if(w&&(pe&&ee(pe,w)||z.some((L)=>L.id===w)))v=w;else if(pe)v=q(pe);if(!v)v=(z.find((P)=>!P.archived&&!P.swarm&&!P.settled)??z.find((P)=>!P.archived&&!P.swarm))?.id??""}if(v&&(pe&&ee(pe,v)||z.some((w)=>w.id===v)))await Ee(v);else T="",R=[],Ue.setItems([]),ce.setState(!1,!1),I()}async function Ee(v){if(T&&T!==v){Ke.cancel();let Se=oe.getEntries();if(Se.length>0){let ae=ue.get(T);Re(T,{entries:Se,ids:ae?.ids??Se.map((Qe)=>Qe.id),olderCursor:re,review:ae?.review??null,unanswered:ae?.unanswered??null,rail:ae?.rail??R,hashes:ae?.hashes??{}})}}let w=++J;K++,Oe(null);let L=Me;if(Me=null,L!==null)B.rpc("unsubscribe",{sub:L}).catch(()=>{});T=v;let P=ue.get(v);re=P?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}X.setSelected(v),se.classList.remove("bp-sidebar-open"),I();let O=z.find((Se)=>Se.id===v)??null;if(P)oe.setThread(O,P.entries,Boolean(P.olderCursor),P.review,P.unanswered),R=P.rail,Ue.setItems(P.rail);else oe.setLoading(O),R=[],Ue.setItems([]);if(ce.setState(!0,O?.state==="working"),B.hasFeature("open")){let Se={};if(P){for(let[Ne,pt]of Object.entries(P.hashes))Se[Ne]=pt;for(let Ne of P.entries)if(Ne.h)Se[Ne.id]=Ne.h}let ae;try{ae=await B.rpc("thread.open",{thread:v,limit:40,have:Se})}catch(Ne){if(w===J){let pt=Ne instanceof Error&&Ne.message?Ne.message:"Could not load messages.";oe.setError(O,pt,()=>{Ee(v)})}return}if(w!==J){if(ae.sub!==void 0&&ae.sub!==null)B.rpc("unsubscribe",{sub:ae.sub}).catch(()=>{});return}if(Me=ae.sub??null,ae.thread){O=ae.thread;let Ne=z.findIndex((pt)=>pt.id===ae.thread.id);if(Ne>=0)z[Ne]=ae.thread;else z.unshift(ae.thread);I(),ce.setState(!0,O.state==="working")}if("next"in ae)re=ae.next??null;let Qe=new Map;if(P)for(let Ne of P.entries)Qe.set(Ne.id,Ne);for(let Ne of ae.entries??[])Qe.set(Ne.id,Ne);let nt=ae.ids??P?.ids??(ae.entries??[]).map((Ne)=>Ne.id),kn=nt.map((Ne)=>Qe.get(Ne)).filter((Ne)=>Boolean(Ne)),dt=P?.rail??[];if(ae.rail!==void 0){if(Array.isArray(ae.rail))dt=ae.rail;else if(dt=Array.isArray(ae.rail?.rail)?ae.rail.rail:Array.isArray(ae.rail?.items)?ae.rail.items:[],ae.rail?.has){if(He?.reconcileHas?.(ae.rail.has),ke&&!Zi(ae.rail.has,ke))F(!0)}}R=dt,Ue.setItems(dt);let $t=P?.review??null;if(B.hasFeature("reviewmode"))try{let Ne=await B.rpc("thread.review",{thread:v});if(w!==J)return;$t=Ne.review??null}catch{}if(w!==J)return;let Sn="unanswered"in ae?ae.unanswered??null:P?.unanswered??null,ts=ae.h??P?.hashes??{};if(Re(v,{entries:kn,ids:nt,olderCursor:re,review:$t,unanswered:Sn,rail:dt,hashes:ts}),oe.setThread(O,kn,Boolean(re),$t,Sn),Te(v,w),ke)U(ke);return}let ie;try{ie=await B.rpc("thread.entries",{thread:v,limit:40})}catch(Se){if(w===J){let ae=Se instanceof Error&&Se.message?Se.message:"Could not load messages.";oe.setError(O,ae,()=>{Ee(v)})}return}if(w!==J)return;if(ie.thread){let Se=z.findIndex((ae)=>ae.id===ie.thread.id);if(Se>=0)z[Se]=ie.thread;else z.unshift(ie.thread);I()}re=ie.next??null;let ve=null;if(B.hasFeature("reviewmode"))try{let Se=await B.rpc("thread.review",{thread:v});if(w!==J)return;ve=Se.review??null}catch{}if(w!==J)return;let De=ie.entries??[],tt=ie.unanswered??null;Re(v,{entries:De,ids:De.map((Se)=>Se.id),olderCursor:re,review:ve,unanswered:tt,rail:P?.rail??[],hashes:P?.hashes??{}}),oe.setThread(O,De,Boolean(re),ve,tt);try{let ae=(await B.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(ae!==null){if(w!==J){B.rpc("unsubscribe",{sub:ae}).catch(()=>{});return}Me=ae}}catch{}if(w!==J)return;if(G(v,w),Te(v,w),ke)U(ke)}async function Te(v,w){if(!v||!B.hasFeature("mgmt")){if(w===J)Ye.clear();return}let L=z.find((O)=>O.id===v),P=L?.project?j.find((O)=>O.id===L.project)?.root??"":"";if(!P&&B.hasFeature("viewers"))try{let O=await B.rpc("viewer.files",{thread:v});if(w!==J)return;P=O.pcb||O.sch||O.root||""}catch{}if(w!==J)return;if(P)await Ye.watchProject(P);else Ye.clear()}async function Ie(v){let w=J;for(let L=0;L<25&&w===J;L++){if(oe.goTo(v))return;if(!re)return;let P=re;if(await _e(),re===P)return}}async function _e(){if(!T||!re){oe.clearLoadingOlder();return}let v=J,w=T,L=re;try{let P=await B.rpc("thread.entries",{thread:w,limit:40,before:L});if(v!==J||T!==w)return;re=P.next??null,oe.prependEntries(P.entries??[],Boolean(re))}catch{if(v===J)oe.clearLoadingOlder()}}async function Fe(v){try{let w=await B.rpc("thread.create",{project:v});if(w.thread)z=[w.thread,...z.filter((L)=>L.id!==w.thread.id)],X.setData(j,z,C,S),ge(),await Ee(w.thread.id),ce.focus()}catch(w){ce.showError(w instanceof Error?w.message:"Could not create thread")}}let Ze=null;function St(v){return(v.split(` +`).map((w)=>w.trim()).find((w)=>w.length>0)??"").slice(0,200)}function Oe(v){Ze=v,ce.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Ze)Ie(Ze.id)},()=>Oe(null))}async function En(v,w=[]){if(!T)return;let L=J,P=T,O=Xs(),ie=`local-${O}`,ve=Ze&&v.trim()&&B.hasFeature("reply")?Ze:null;if(ve)Oe(null);oe.upsertEntry({id:ie,kind:"user",text:v,at:Date.now(),clientId:O,...ve?{replyTo:{id:ve.id,quote:St(ve.text)}}:{},attachments:w.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:P,text:v,clientId:O};if(w.length>0)De.attachments=w;if(ve)De.replyTo={id:ve.id,text:ve.text};let tt=await B.rpc("message.send",De);if(L!==J||T!==P)return;if(tt.entry)oe.upsertEntry(tt.entry)}catch(De){if(L===J&&T===P){if(oe.removeEntry(ie),ce.setDraft(v),ve&&!Ze)Oe(ve);ce.showError(De instanceof Error?De.message:"Failed to send message")}}}async function xn(v){if(!T)return;let w=J,L=T;try{let P=await B.rpc("composer.run",{thread:L,text:v});if(w!==J||T!==L)return;if(P.error)ce.setDraft(v),ce.showError(P.error);else if(P.kind==="edit"&&typeof P.text==="string")ce.setDraft(P.text);else if(P.kind==="project")Ve.open({mode:"folder"});else if(P.kind==="clone")Ve.open({mode:"clone",repo:P.repo??"",text:P.text??""})}catch(P){if(w===J&&T===L)ce.setDraft(v),ce.showError(P instanceof Error?P.message:"Command refused")}}async function et(v,w){try{let L=await B.rpc("thread.act",{thread:v,action:w});if(L.thread){if(z=z.map((P)=>P.id===L.thread.id?L.thread:P),X.setData(j,z,C,S),L.thread.id===T)oe.updateThreadMeta(L.thread),I()}ge()}catch(L){ce.showError(L instanceof Error?L.message:`Action "${w}" not allowed`)}}function Cn(v,w){if(!v||!v.text||w-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return h("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function Lt(v){if(v==="connected")X.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Cn(B.restarting,Date.now()))X.setConnStatus(Cn(B.restarting,Date.now()),"");else if(v==="reconnecting")X.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")X.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else X.setConnStatus("Connecting…","")}At(()=>{Lt(B.getState()),W.textContent=h("gpui.improvements","Improvements"),he.title=h("palette.settings","Settings"),he.setAttribute("aria-label",h("palette.settings","Settings")),I(),X.refreshLocale(),oe.refreshLocale(),ce.refreshLocale(),Ue.render(),ze.refreshLocale(),Ve.refreshLocale()}),B.onState((v,w)=>{if(v==="connected"&&w){if(w.locale)Tn(w.locale);if(w.theme)Qi(w.theme);if(w.name)X.setHostName(w.name);if(it=w.home??null,X.setHome(it),ze.isOpen())ze.refresh();Lt(v);let L=typeof w.hubBack==="string"?String(w.hubBack):"";if(L)try{let P=JSON.parse(L);if(P.reason==="crash")X.setConnStatus(h("hub.back.crash",P.text??""),"bp-warn"),window.setTimeout(()=>Lt(B.getState()),6000)}catch{}if(ce.setFeatures(B.hasFeature("images"),B.hasFeature("voice")),Array.isArray(w.commands))Y=w.commands,ce.setCommands(Y);else Y=[];Pe(),Ve.reconcile()}else Ke.cancel(),Lt(v)}),B.onFrame((v)=>{if(v.t==="voice"){Ke.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Ye.handleInfo(v.info);return}if(v.t!=="d")return;let w=v;if(w.k==="clone"||w.k==="clone.repos"||w.k==="clone.signin"){Ve.handleFrame(w);return}switch(w.k){case"project":{let L=w.project;if(!L)break;let P=j.findIndex((O)=>O.id===L.id);if(P>=0)j[P]=L;else j.unshift(L);X.setData(j,z,C,S),I(),fe();break}case"thread":{let L=w.thread;if(!L)break;let P=z.findIndex((O)=>O.id===L.id);if(P>=0)z[P]=L;else z.unshift(L);if(X.setData(j,z,C,S),L.id===T)oe.updateThreadMeta(L),I(),ce.setState(!0,L.state==="working");fe();break}case"thread.removed":{let L=String(w.id??"");z=z.filter((P)=>P.id!==L),X.setData(j,z,C,S),fe();break}case"entry":{if(w.thread===T&&w.entry)oe.upsertEntry(w.entry);break}case"text":{if(w.thread===T)oe.appendLiveText(String(w.entry??""),String(w.append??""),Number(w.at??Date.now()));break}case"turn":{if(w.thread===T){let L=String(w.state??"idle");ce.setState(!0,L==="working"),G(T,J)}fe();break}case"btw":{if(w.thread===T)oe.showBtw(String(w.q??""),String(w.a??""));break}case"unanswered":{if(w.thread===T)oe.setUnanswered(w.unanswered??null);break}case"theme":{if(typeof w.theme==="string")Qi(w.theme);break}case"home":{if(it=w.home??null,X.setHome(it),ze.isOpen())ze.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let w=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(w==="k"||v.shiftKey&&w==="p"))if(v.preventDefault(),Ge.isOpen())Ge.close();else Ge.open();else if(v.key==="Escape"){if(Ge.isOpen())Ge.close();else if(Ve.isOpen())Ve.escape();else if(ze.isOpen())ze.close();else if(oe.closePlanRevise());else if(Ye.isOpen())Ye.closePanel()}}),B.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",es);else es(); diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 852739285f..59e7c0ab46 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 201187, + "totalAssetGzipBytes": 201097, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -279,12 +279,12 @@ "web/src/logout.ts": "9d29482c4671deee1e868ee477b123e067a4c22f7d8ac30b4c2420cf71b8ebe2", "web/src/md.ts": "c606d1ec598b3ce132c7cc9366383dacafc3fcb71c0fccd97b41ec0e19a96c78", "web/src/mgmt-model.ts": "3bf50952af7687afaec3c43e84890176aedf5400a45688fe8ee2e5161040f76b", - "web/src/mgmt.ts": "d4e9fb07c8bfebd4f3308b31f8ff3b3dc31cc2470320f7202fe3831c1f437bed", + "web/src/mgmt.ts": "f186e4d2127ad671d6b9135fd4646d1eb788a0932bea0520e3250954b9a7faa2", "web/src/pair.html": "cf7b94703316f910718356e9ff8e99e088b68211db39b5200213b623c9275f6e", "web/src/pair.ts": "af07d19224043f8176f8cd2298d00b6806248eee453fd2f287c183e71a08179b", "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", - "web/src/plan-canvas.ts": "c4685c70d76fa7b651a9b008017984139a3909afb7370477151f29b0421375d3", + "web/src/plan-canvas.ts": "037d2bbc5d931fce1df1a3f2044e7605b8498590437b24a22ba9d14de7761159", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "7b4d8be26fabc6c2a0b8af94a64572a0e3c1e589bf079bfa58c8985a8acd984a", @@ -317,9 +317,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 335684, - "gzipBytes": 94601, - "sha256": "83e06d714bcfdd30fcf9ae72446381181cd287b22be1a93ee87a0e2c9b5b48b5" + "bytes": 335279, + "gzipBytes": 94511, + "sha256": "977cc1c088bf2c40cac229185c2932b7161fdbed025aaad7ebbfb30d94abcb0a" }, "assets/favicon-light.svg": { "bytes": 1207, diff --git a/web/src/mgmt.ts b/web/src/mgmt.ts index 2451192310..1fb43a1079 100644 --- a/web/src/mgmt.ts +++ b/web/src/mgmt.ts @@ -1832,17 +1832,6 @@ export class MgmtStrip { onFocusItem: (id) => { sendPlan("plan.focus", { id }); }, - onOptimisticPatch: (id, fields) => { - const prev = this.planOptimistic.get(id) ?? {}; - this.planOptimistic.set(id, { ...prev, ...fields }); - }, - onRevertOptimistic: (id) => { - const had = this.planOptimistic.delete(id); - if (had || this.planRenderDeferred) { - this.planRenderDeferred = false; - this.render(); - } - }, onDragEnd: () => { if (this.planRenderDeferred) { this.planRenderDeferred = false; diff --git a/web/src/plan-canvas.ts b/web/src/plan-canvas.ts index 226a51c474..4302d783c0 100644 --- a/web/src/plan-canvas.ts +++ b/web/src/plan-canvas.ts @@ -45,8 +45,6 @@ export interface PlanCanvasStateSnapshot { export interface PlanCanvasCallbacks { onSelect: (id: string) => void; onFocusItem: (id: string) => void; - onOptimisticPatch: (id: string, fields: Record) => void; - onRevertOptimistic?: (id: string) => void; onDragEnd?: () => void; onCommitFields: (id: string, fields: Record) => void; onApproveLayer: (layer: string, approve: boolean) => void; @@ -450,7 +448,6 @@ export class PlanFloorplannerCanvas { const insertedIdx = hit.isPlane && hit.segIdx + 1 >= curPts.length ? newPts.length - 1 : Math.min(hit.segIdx + 1, newPts.length - 1); this.selectedVertex = { id: hit.id, idx: insertedIdx }; this.patchLocalItem(hit.id, hit.isPlane, newPts); - this.cb.onOptimisticPatch(hit.id, { [hit.isPlane ? "outline" : "path"]: newPts }); this.drag = { layer, kind: "vertex", id: hit.id, isPlane: hit.isPlane, idx: insertedIdx, pts: newPts, origPts, moved: true }; this.scheduleDraw(); } else { @@ -487,7 +484,6 @@ export class PlanFloorplannerCanvas { this.drag.pts[this.drag.idx] = rounded; const copy = this.drag.pts.map((p) => [p[0], p[1]] as [number, number]); this.patchLocalItem(this.drag.id, this.drag.isPlane, copy); - this.cb.onOptimisticPatch(this.drag.id, { [this.drag.isPlane ? "outline" : "path"]: copy }); this.scheduleDraw(); return; } @@ -518,13 +514,11 @@ export class PlanFloorplannerCanvas { if (!d || d.layer !== layer) return; this.drag = null; this.downPos = null; - if (d.kind === "vertex") { + if (d.kind === "vertex" && d.moved) { const copy = d.origPts.map((p) => [p[0], p[1]] as [number, number]); this.patchLocalItem(d.id, d.isPlane, copy); - this.cb.onRevertOptimistic?.(d.id); - } else { - this.cb.onDragEnd?.(); } + this.cb.onDragEnd?.(); this.scheduleDraw(); }; canvas.addEventListener("pointercancel", cancelActiveDrag);