File size: 289,862 Bytes
064bfd6 6db367d 064bfd6 6db367d fdc8b59 6db367d 44e0492 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 fdc8b59 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d a8a1ac1 044c1b2 a8a1ac1 044c1b2 a8a1ac1 044c1b2 a8a1ac1 044c1b2 a8a1ac1 044c1b2 a8a1ac1 044c1b2 a8a1ac1 064bfd6 6db367d 064bfd6 6db367d 41f32b4 6db367d 96f34e3 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 41f32b4 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d a8a1ac1 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d a8a1ac1 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d a8a1ac1 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 a8a1ac1 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d f36b9c7 6db367d 41f32b4 6db367d 41f32b4 6db367d 41f32b4 6db367d 41f32b4 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d f36b9c7 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d f36b9c7 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d f36b9c7 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 41f32b4 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 7d2eb5a 44e0492 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 a8a1ac1 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d a8a1ac1 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 41f32b4 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 6db367d 064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 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 804 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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 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 902 903 904 905 906 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 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 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 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 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 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 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 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 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 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 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 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 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 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 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 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 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 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 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 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 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 4795 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 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 | // biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
import { feature } from 'bun:bundle'
import { spawnSync } from 'child_process'
import {
snapshotOutputTokensForTurn,
getCurrentTurnTokenBudget,
getTurnOutputTokens,
getBudgetContinuationCount,
getTotalInputTokens,
} from '../bootstrap/state.js'
import { parseTokenBudget } from '../utils/tokenBudget.js'
import { count } from '../utils/array.js'
import { dirname, join } from 'path'
import { tmpdir } from 'os'
import figures from 'figures'
// eslint-disable-next-line custom-rules/prefer-use-keybindings -- / n N Esc [ v are bare letters in transcript modal context, same class as g/G/j/k in ScrollKeybindingHandler
import { useInput } from '../ink.js'
import { useSearchInput } from '../hooks/useSearchInput.js'
import { useTerminalSize } from '../hooks/useTerminalSize.js'
import { useSearchHighlight } from '../ink/hooks/use-search-highlight.js'
import type { JumpHandle } from '../components/VirtualMessageList.js'
import { renderMessagesToPlainText } from '../utils/exportRenderer.js'
import { openFileInExternalEditor } from '../utils/editor.js'
import { writeFile } from 'fs/promises'
import {
Box,
Text,
useStdin,
useTheme,
useTerminalFocus,
useTerminalTitle,
useTabStatus,
} from '../ink.js'
import type { TabStatusKind } from '../ink/hooks/use-tab-status.js'
import { CostThresholdDialog } from '../components/CostThresholdDialog.js'
import { IdleReturnDialog } from '../components/IdleReturnDialog.js'
import * as React from 'react'
import {
useEffect,
useMemo,
useRef,
useState,
useCallback,
useDeferredValue,
useLayoutEffect,
type RefObject,
} from 'react'
import { useNotifications } from '../context/notifications.js'
import { sendNotification } from '../services/notifier.js'
import {
startPreventSleep,
stopPreventSleep,
} from '../services/preventSleep.js'
import { useTerminalNotification } from '../ink/useTerminalNotification.js'
import { hasCursorUpViewportYankBug } from '../ink/terminal.js'
import {
createFileStateCacheWithSizeLimit,
mergeFileStateCaches,
READ_FILE_STATE_CACHE_SIZE,
} from '../utils/fileStateCache.js'
import {
updateLastInteractionTime,
getLastInteractionTime,
getOriginalCwd,
getProjectRoot,
getSessionId,
switchSession,
setCostStateForRestore,
getTurnHookDurationMs,
getTurnHookCount,
resetTurnHookDuration,
getTurnToolDurationMs,
getTurnToolCount,
resetTurnToolDuration,
getTurnClassifierDurationMs,
getTurnClassifierCount,
resetTurnClassifierDuration,
} from '../bootstrap/state.js'
import { asSessionId, asAgentId } from '../types/ids.js'
import { logForDebugging } from '../utils/debug.js'
import { QueryGuard } from '../utils/QueryGuard.js'
import { useGoalAutoContinue } from '../hooks/useGoalAutoContinue.js'
import { isEnvTruthy } from '../utils/envUtils.js'
import { formatTokens, truncateToWidth } from '../utils/format.js'
import { consumeEarlyInput } from '../utils/earlyInput.js'
import { setMemberActive } from '../utils/swarm/teamHelpers.js'
import {
isSwarmWorker,
generateSandboxRequestId,
sendSandboxPermissionRequestViaMailbox,
sendSandboxPermissionResponseViaMailbox,
} from '../utils/swarm/permissionSync.js'
import { registerSandboxPermissionCallback } from '../hooks/useSwarmPermissionPoller.js'
import { getTeamName, getAgentName } from '../utils/teammate.js'
import { WorkerPendingPermission } from '../components/permissions/WorkerPendingPermission.js'
import {
injectUserMessageToTeammate,
getAllInProcessTeammateTasks,
} from '../tasks/InProcessTeammateTask/InProcessTeammateTask.js'
import {
isLocalAgentTask,
queuePendingMessage,
appendMessageToLocalAgent,
type LocalAgentTaskState,
} from '../tasks/LocalAgentTask/LocalAgentTask.js'
import {
registerLeaderToolUseConfirmQueue,
unregisterLeaderToolUseConfirmQueue,
registerLeaderSetToolPermissionContext,
unregisterLeaderSetToolPermissionContext,
} from '../utils/swarm/leaderPermissionBridge.js'
import { endInteractionSpan } from '../utils/telemetry/sessionTracing.js'
import { useLogMessages } from '../hooks/useLogMessages.js'
import { useFeishuBridge } from '../hooks/useFeishuBridge.js'
import { useReplBridge } from '../hooks/useReplBridge.js'
import {
type Command,
type CommandResultDisplay,
type ResumeEntrypoint,
getCommandName,
isCommandEnabled,
} from '../commands.js'
import type {
PromptInputMode,
QueuedCommand,
VimMode,
} from '../types/textInputTypes.js'
import {
MessageSelector,
selectableUserMessagesFilter,
messagesAfterAreOnlySynthetic,
} from '../components/MessageSelector.js'
import { useIdeLogging } from '../hooks/useIdeLogging.js'
import {
PermissionRequest,
type ToolUseConfirm,
} from '../components/permissions/PermissionRequest.js'
import { ElicitationDialog } from '../components/mcp/ElicitationDialog.js'
import { PromptDialog } from '../components/hooks/PromptDialog.js'
import type { PromptRequest, PromptResponse } from '../types/hooks.js'
import PromptInput from '../components/PromptInput/PromptInput.js'
import { PromptInputQueuedCommands } from '../components/PromptInput/PromptInputQueuedCommands.js'
import { useRemoteSession } from '../hooks/useRemoteSession.js'
import { useDirectConnect } from '../hooks/useDirectConnect.js'
import type { DirectConnectConfig } from '../server/directConnectManager.js'
import { useSSHSession } from '../hooks/useSSHSession.js'
import { useAssistantHistory } from '../hooks/useAssistantHistory.js'
import type { SSHSession } from '../ssh/createSSHSession.js'
import { SkillImprovementSurvey } from '../components/SkillImprovementSurvey.js'
import { useSkillImprovementSurvey } from '../hooks/useSkillImprovementSurvey.js'
import { useMoreRight } from '../moreright/useMoreRight.js'
import {
SpinnerWithVerb,
BriefIdleStatus,
type SpinnerMode,
} from '../components/Spinner.js'
import { getSystemPrompt } from '../constants/prompts.js'
import { buildEffectiveSystemPrompt } from '../utils/systemPrompt.js'
import { getSystemContext, getUserContext } from '../context.js'
import { getMemoryFiles } from '../utils/claudemd.js'
import { startBackgroundHousekeeping } from '../utils/backgroundHousekeeping.js'
import {
getTotalCost,
saveCurrentSessionCosts,
resetCostState,
getStoredSessionCosts,
} from '../cost-tracker.js'
import { useCostSummary } from '../costHook.js'
import { useFpsMetrics } from '../context/fpsMetrics.js'
import { useAfterFirstRender } from '../hooks/useAfterFirstRender.js'
import { useDeferredHookMessages } from '../hooks/useDeferredHookMessages.js'
import {
addToHistory,
removeLastFromHistory,
expandPastedTextRefs,
parseReferences,
} from '../history.js'
import { prependModeCharacterToInput } from '../components/PromptInput/inputModes.js'
import { prependToShellHistoryCache } from '../utils/suggestions/shellHistoryCompletion.js'
import { useApiKeyVerification } from '../hooks/useApiKeyVerification.js'
import { GlobalKeybindingHandlers } from '../hooks/useGlobalKeybindings.js'
import { CommandKeybindingHandlers } from '../hooks/useCommandKeybindings.js'
import { KeybindingSetup } from '../keybindings/KeybindingProviderSetup.js'
import { useShortcutDisplay } from '../keybindings/useShortcutDisplay.js'
import { getShortcutDisplay } from '../keybindings/shortcutFormat.js'
import { CancelRequestHandler } from '../hooks/useCancelRequest.js'
import { useBackgroundTaskNavigation } from '../hooks/useBackgroundTaskNavigation.js'
import { useSwarmInitialization } from '../hooks/useSwarmInitialization.js'
import { useTeammateViewAutoExit } from '../hooks/useTeammateViewAutoExit.js'
import { errorMessage } from '../utils/errors.js'
import { isHumanTurn } from '../utils/messagePredicates.js'
import { logError } from '../utils/log.js'
// Dead code elimination: conditional imports
/* eslint-disable custom-rules/no-process-env-top-level, @typescript-eslint/no-require-imports */
const useVoiceIntegration: typeof import('../hooks/useVoiceIntegration.js').useVoiceIntegration =
feature('VOICE_MODE')
? require('../hooks/useVoiceIntegration.js').useVoiceIntegration
: () => ({
stripTrailing: () => 0,
handleKeyEvent: () => {},
resetAnchor: () => {},
})
const VoiceKeybindingHandler: typeof import('../hooks/useVoiceIntegration.js').VoiceKeybindingHandler =
feature('VOICE_MODE')
? require('../hooks/useVoiceIntegration.js').VoiceKeybindingHandler
: () => null
// Frustration detection is ant-only (dogfooding). Conditional require so external
// builds eliminate the module entirely (including its two O(n) useMemos that run
// on every messages change, plus the GrowthBook fetch).
const useFrustrationDetection: typeof import('../components/FeedbackSurvey/useFrustrationDetection.js').useFrustrationDetection =
"external" === 'ant'
? require('../components/FeedbackSurvey/useFrustrationDetection.js')
.useFrustrationDetection
: () => ({ state: 'closed', handleTranscriptSelect: () => {} })
// Ant-only org warning. Conditional require so the org UUID list is
// eliminated from external builds (one UUID is on excluded-strings).
const useAntOrgWarningNotification: typeof import('../hooks/notifs/useAntOrgWarningNotification.js').useAntOrgWarningNotification =
"external" === 'ant'
? require('../hooks/notifs/useAntOrgWarningNotification.js')
.useAntOrgWarningNotification
: () => {}
// Dead code elimination: conditional import for coordinator mode
const getCoordinatorUserContext: (
mcpClients: ReadonlyArray<{ name: string }>,
scratchpadDir?: string,
) => { [k: string]: string } = feature('COORDINATOR_MODE')
? require('../coordinator/coordinatorMode.js').getCoordinatorUserContext
: () => ({})
/* eslint-enable custom-rules/no-process-env-top-level, @typescript-eslint/no-require-imports */
import useCanUseTool from '../hooks/useCanUseTool.js'
import type { ToolPermissionContext, Tool } from '../Tool.js'
import {
applyPermissionUpdate,
applyPermissionUpdates,
persistPermissionUpdate,
} from '../utils/permissions/PermissionUpdate.js'
import { buildPermissionUpdates } from '../components/permissions/ExitPlanModePermissionRequest/ExitPlanModePermissionRequest.js'
import { stripDangerousPermissionsForAutoMode } from '../utils/permissions/permissionSetup.js'
import {
getScratchpadDir,
isScratchpadEnabled,
} from '../utils/permissions/filesystem.js'
import { WEB_FETCH_TOOL_NAME } from '../tools/WebFetchTool/prompt.js'
import { SLEEP_TOOL_NAME } from '../tools/SleepTool/prompt.js'
import { clearSpeculativeChecks } from '../tools/BashTool/bashPermissions.js'
import type { AutoUpdaterResult } from '../utils/autoUpdater.js'
import {
getGlobalConfig,
saveGlobalConfig,
getGlobalConfigWriteCount,
} from '../utils/config.js'
import { hasConsoleBillingAccess } from '../utils/billing.js'
import {
logEvent,
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
} from 'src/services/analytics/index.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js'
import {
textForResubmit,
handleMessageFromStream,
type StreamingToolUse,
type StreamingThinking,
isCompactBoundaryMessage,
getMessagesAfterCompactBoundary,
getContentText,
createUserMessage,
createAssistantMessage,
createTurnDurationMessage,
createAgentsKilledMessage,
createApiMetricsMessage,
createSystemMessage,
createCommandInputMessage,
formatCommandInputTags,
} from '../utils/messages.js'
import { generateSessionTitle } from '../utils/sessionTitle.js'
import {
BASH_INPUT_TAG,
COMMAND_MESSAGE_TAG,
COMMAND_NAME_TAG,
LOCAL_COMMAND_STDOUT_TAG,
} from '../constants/xml.js'
import { escapeXml } from '../utils/xml.js'
import type { ThinkingConfig } from '../utils/thinking.js'
import { gracefulShutdownSync } from '../utils/gracefulShutdown.js'
import {
handlePromptSubmit,
type PromptInputHelpers,
} from '../utils/handlePromptSubmit.js'
import { useQueueProcessor } from '../hooks/useQueueProcessor.js'
import { useMailboxBridge } from '../hooks/useMailboxBridge.js'
import {
queryCheckpoint,
logQueryProfileReport,
} from '../utils/queryProfiler.js'
import type {
Message as MessageType,
UserMessage,
ProgressMessage,
HookResultMessage,
PartialCompactDirection,
} from '../types/message.js'
import { query } from '../query.js'
import { mergeClients, useMergedClients } from '../hooks/useMergedClients.js'
import { getQuerySourceForREPL } from '../utils/promptCategory.js'
import { useMergedTools } from '../hooks/useMergedTools.js'
import { mergeAndFilterTools } from '../utils/toolPool.js'
import { useMergedCommands } from '../hooks/useMergedCommands.js'
import { useSkillsChange } from '../hooks/useSkillsChange.js'
import { useManagePlugins } from '../hooks/useManagePlugins.js'
import { Messages } from '../components/Messages.js'
import { TaskListV2 } from '../components/TaskListV2.js'
import { TeammateViewHeader } from '../components/TeammateViewHeader.js'
import { useTasksV2WithCollapseEffect } from '../hooks/useTasksV2.js'
import { maybeMarkProjectOnboardingComplete } from '../projectOnboardingState.js'
import type { MCPServerConnection } from '../services/mcp/types.js'
import type { ScopedMcpServerConfig } from '../services/mcp/types.js'
import { randomUUID, type UUID } from 'crypto'
import { processSessionStartHooks } from '../utils/sessionStart.js'
import {
executeSessionEndHooks,
getSessionEndHookTimeoutMs,
} from '../utils/hooks.js'
import { type IDESelection, useIdeSelection } from '../hooks/useIdeSelection.js'
import { getTools, assembleToolPool } from '../tools.js'
import type { AgentDefinition } from '../tools/AgentTool/loadAgentsDir.js'
import { resolveAgentTools } from '../tools/AgentTool/agentToolUtils.js'
import { resumeAgentBackground } from '../tools/AgentTool/resumeAgent.js'
import { useMainLoopModel } from '../hooks/useMainLoopModel.js'
import {
useAppState,
useSetAppState,
useAppStateStore,
} from '../state/AppState.js'
import type {
ContentBlockParam,
ImageBlockParam,
} from '@anthropic-ai/sdk/resources/messages.mjs'
import type { ProcessUserInputContext } from '../utils/processUserInput/processUserInput.js'
import type { PastedContent } from '../utils/config.js'
import {
copyPlanForFork,
copyPlanForResume,
getPlanSlug,
setPlanSlug,
} from '../utils/plans.js'
import {
clearSessionMetadata,
resetSessionFilePointer,
adoptResumedSessionFile,
removeTranscriptMessage,
restoreSessionMetadata,
getCurrentSessionTitle,
isEphemeralToolProgress,
isLoggableMessage,
saveWorktreeState,
getAgentTranscript,
} from '../utils/sessionStorage.js'
import { deserializeMessages } from '../utils/conversationRecovery.js'
import {
extractReadFilesFromMessages,
extractBashToolsFromMessages,
} from '../utils/queryHelpers.js'
import { resetMicrocompactState } from '../services/compact/microCompact.js'
import { runPostCompactCleanup } from '../services/compact/postCompactCleanup.js'
import {
provisionContentReplacementState,
reconstructContentReplacementState,
type ContentReplacementRecord,
} from '../utils/toolResultStorage.js'
import { partialCompactConversation } from '../services/compact/compact.js'
import type { LogOption } from '../types/logs.js'
import type { AgentColorName } from '../tools/AgentTool/agentColorManager.js'
import {
fileHistoryMakeSnapshot,
type FileHistoryState,
fileHistoryRewind,
type FileHistorySnapshot,
copyFileHistoryForResume,
fileHistoryEnabled,
fileHistoryHasAnyChanges,
} from '../utils/fileHistory.js'
import {
type AttributionState,
incrementPromptCount,
} from '../utils/commitAttribution.js'
import { recordAttributionSnapshot } from '../utils/sessionStorage.js'
import {
computeStandaloneAgentContext,
restoreAgentFromSession,
restoreSessionStateFromLog,
restoreWorktreeForResume,
exitRestoredWorktree,
} from '../utils/sessionRestore.js'
import {
isBgSession,
updateSessionName,
updateSessionActivity,
} from '../utils/concurrentSessions.js'
import {
isInProcessTeammateTask,
type InProcessTeammateTaskState,
} from '../tasks/InProcessTeammateTask/types.js'
import { restoreRemoteAgentTasks } from '../tasks/RemoteAgentTask/RemoteAgentTask.js'
import { useInboxPoller } from '../hooks/useInboxPoller.js'
// Dead code elimination: conditional import for loop mode
/* eslint-disable @typescript-eslint/no-require-imports */
const proactiveModule =
feature('PROACTIVE') || feature('KAIROS')
? require('../proactive/index.js')
: null
const PROACTIVE_NO_OP_SUBSCRIBE = (_cb: () => void) => () => {}
const PROACTIVE_FALSE = () => false
const SUGGEST_BG_PR_NOOP = (_p: string, _n: string): boolean => false
const useProactive =
feature('PROACTIVE') || feature('KAIROS')
? require('../proactive/useProactive.js').useProactive
: null
const useScheduledTasks = feature('AGENT_TRIGGERS')
? require('../hooks/useScheduledTasks.js').useScheduledTasks
: null
/* eslint-enable @typescript-eslint/no-require-imports */
import { isAgentSwarmsEnabled } from '../utils/agentSwarmsEnabled.js'
import { useTaskListWatcher } from '../hooks/useTaskListWatcher.js'
import type {
SandboxAskCallback,
NetworkHostPattern,
} from '../utils/sandbox/sandbox-adapter.js'
import {
type IDEExtensionInstallationStatus,
closeOpenDiffs,
getConnectedIdeClient,
type IdeType,
} from '../utils/ide.js'
import { useIDEIntegration } from '../hooks/useIDEIntegration.js'
import exit from '../commands/exit/index.js'
import { ExitFlow } from '../components/ExitFlow.js'
import { getCurrentWorktreeSession } from '../utils/worktree.js'
import {
popAllEditable,
enqueue,
type SetAppState,
getCommandQueue,
getCommandQueueLength,
removeByFilter,
} from '../utils/messageQueueManager.js'
import { useCommandQueue } from '../hooks/useCommandQueue.js'
import { SessionBackgroundHint } from '../components/SessionBackgroundHint.js'
import { startBackgroundSession } from '../tasks/LocalMainSessionTask.js'
import { useSessionBackgrounding } from '../hooks/useSessionBackgrounding.js'
import { diagnosticTracker } from '../services/diagnosticTracking.js'
import {
handleSpeculationAccept,
type ActiveSpeculationState,
} from '../services/PromptSuggestion/speculation.js'
import { IdeOnboardingDialog } from '../components/IdeOnboardingDialog.js'
import {
EffortCallout,
shouldShowEffortCallout,
} from '../components/EffortCallout.js'
import type { EffortValue } from '../utils/effort.js'
import { RemoteCallout } from '../components/RemoteCallout.js'
/* eslint-disable custom-rules/no-process-env-top-level, @typescript-eslint/no-require-imports */
const AntModelSwitchCallout =
"external" === 'ant'
? require('../components/AntModelSwitchCallout.js').AntModelSwitchCallout
: null
const shouldShowAntModelSwitch =
"external" === 'ant'
? require('../components/AntModelSwitchCallout.js')
.shouldShowModelSwitchCallout
: (): boolean => false
const UndercoverAutoCallout =
"external" === 'ant'
? require('../components/UndercoverAutoCallout.js').UndercoverAutoCallout
: null
/* eslint-enable custom-rules/no-process-env-top-level, @typescript-eslint/no-require-imports */
import { activityManager } from '../utils/activityManager.js'
import { createAbortController } from '../utils/abortController.js'
import { MCPConnectionManager } from 'src/services/mcp/MCPConnectionManager.js'
import { useFeedbackSurvey } from 'src/components/FeedbackSurvey/useFeedbackSurvey.js'
import { useMemorySurvey } from 'src/components/FeedbackSurvey/useMemorySurvey.js'
import { usePostCompactSurvey } from 'src/components/FeedbackSurvey/usePostCompactSurvey.js'
import { FeedbackSurvey } from 'src/components/FeedbackSurvey/FeedbackSurvey.js'
import { useInstallMessages } from 'src/hooks/notifs/useInstallMessages.js'
import { useAwaySummary } from 'src/hooks/useAwaySummary.js'
import { useChromeExtensionNotification } from 'src/hooks/useChromeExtensionNotification.js'
import { useOfficialMarketplaceNotification } from 'src/hooks/useOfficialMarketplaceNotification.js'
import { usePromptsFromClaudeInChrome } from 'src/hooks/usePromptsFromClaudeInChrome.js'
import {
getTipToShowOnSpinner,
recordShownTip,
} from 'src/services/tips/tipScheduler.js'
import type { Theme } from 'src/utils/theme.js'
import {
checkAndDisableBypassPermissionsIfNeeded,
checkAndDisableAutoModeIfNeeded,
useKickOffCheckAndDisableBypassPermissionsIfNeeded,
useKickOffCheckAndDisableAutoModeIfNeeded,
} from 'src/utils/permissions/bypassPermissionsKillswitch.js'
import { SandboxManager } from 'src/utils/sandbox/sandbox-adapter.js'
import { SANDBOX_NETWORK_ACCESS_TOOL_NAME } from 'src/cli/structuredIO.js'
import { useFileHistorySnapshotInit } from 'src/hooks/useFileHistorySnapshotInit.js'
import { SandboxPermissionRequest } from 'src/components/permissions/SandboxPermissionRequest.js'
import { SandboxViolationExpandedView } from 'src/components/SandboxViolationExpandedView.js'
import { useSettingsErrors } from 'src/hooks/notifs/useSettingsErrors.js'
import { useMcpConnectivityStatus } from 'src/hooks/notifs/useMcpConnectivityStatus.js'
import { useAutoModeUnavailableNotification } from 'src/hooks/notifs/useAutoModeUnavailableNotification.js'
import { AUTO_MODE_DESCRIPTION } from 'src/components/AutoModeOptInDialog.js'
import { useLspInitializationNotification } from 'src/hooks/notifs/useLspInitializationNotification.js'
import { useLspPluginRecommendation } from 'src/hooks/useLspPluginRecommendation.js'
import { LspRecommendationMenu } from 'src/components/LspRecommendation/LspRecommendationMenu.js'
import { useClaudeCodeHintRecommendation } from 'src/hooks/useClaudeCodeHintRecommendation.js'
import { PluginHintMenu } from 'src/components/ClaudeCodeHint/PluginHintMenu.js'
import {
DesktopUpsellStartup,
shouldShowDesktopUpsellStartup,
} from 'src/components/DesktopUpsell/DesktopUpsellStartup.js'
import { usePluginInstallationStatus } from 'src/hooks/notifs/usePluginInstallationStatus.js'
import { usePluginAutoupdateNotification } from 'src/hooks/notifs/usePluginAutoupdateNotification.js'
import { performStartupChecks } from 'src/utils/plugins/performStartupChecks.js'
import { UserTextMessage } from 'src/components/messages/UserTextMessage.js'
import { AwsAuthStatusBox } from '../components/AwsAuthStatusBox.js'
import { useRateLimitWarningNotification } from 'src/hooks/notifs/useRateLimitWarningNotification.js'
import { useDeprecationWarningNotification } from 'src/hooks/notifs/useDeprecationWarningNotification.js'
import { useNpmDeprecationNotification } from 'src/hooks/notifs/useNpmDeprecationNotification.js'
import { useIDEStatusIndicator } from 'src/hooks/notifs/useIDEStatusIndicator.js'
import { useModelMigrationNotifications } from 'src/hooks/notifs/useModelMigrationNotifications.js'
import { useCanSwitchToExistingSubscription } from 'src/hooks/notifs/useCanSwitchToExistingSubscription.js'
import { useTeammateLifecycleNotification } from 'src/hooks/notifs/useTeammateShutdownNotification.js'
import { useFastModeNotification } from 'src/hooks/notifs/useFastModeNotification.js'
import {
AutoRunIssueNotification,
shouldAutoRunIssue,
getAutoRunIssueReasonText,
getAutoRunCommand,
type AutoRunIssueReason,
} from '../utils/autoRunIssue.js'
import type { HookProgress } from '../types/hooks.js'
import { TungstenLiveMonitor } from '../tools/TungstenTool/TungstenLiveMonitor.js'
/* eslint-disable @typescript-eslint/no-require-imports */
const WebBrowserPanelModule = feature('WEB_BROWSER_TOOL')
? (require('../tools/WebBrowserTool/WebBrowserPanel.js') as typeof import('../tools/WebBrowserTool/WebBrowserPanel.js'))
: null
/* eslint-enable @typescript-eslint/no-require-imports */
import { IssueFlagBanner } from '../components/PromptInput/IssueFlagBanner.js'
import { useIssueFlagBanner } from '../hooks/useIssueFlagBanner.js'
import {
CompanionSprite,
CompanionFloatingBubble,
MIN_COLS_FOR_FULL_SPRITE,
} from '../buddy/CompanionSprite.js'
import { DevBar } from '../components/DevBar.js'
// Session manager removed - using AppState now
import type { RemoteSessionConfig } from '../remote/RemoteSessionManager.js'
import { REMOTE_SAFE_COMMANDS } from '../commands.js'
import type { RemoteMessageContent } from '../utils/teleport/api.js'
import {
FullscreenLayout,
useUnseenDivider,
computeUnseenDivider,
} from '../components/FullscreenLayout.js'
import {
isFullscreenEnvEnabled,
maybeGetTmuxMouseHint,
isMouseTrackingEnabled,
} from '../utils/fullscreen.js'
import { AlternateScreen } from '../ink/components/AlternateScreen.js'
import { ScrollKeybindingHandler } from '../components/ScrollKeybindingHandler.js'
import {
useMessageActions,
MessageActionsKeybindings,
MessageActionsBar,
type MessageActionsState,
type MessageActionsNav,
type MessageActionCaps,
} from '../components/messageActions.js'
import { setClipboard } from '../ink/termio/osc.js'
import type { ScrollBoxHandle } from '../ink/components/ScrollBox.js'
import {
createAttachmentMessage,
getQueuedCommandAttachments,
} from '../utils/attachments.js'
// Stable empty array for hooks that accept MCPServerConnection[] — avoids
// creating a new [] literal on every render in remote mode, which would
// cause useEffect dependency changes and infinite re-render loops.
const EMPTY_MCP_CLIENTS: MCPServerConnection[] = []
// Stable stub for useAssistantHistory's non-KAIROS branch — avoids a new
// function identity each render, which would break composedOnScroll's memo.
const HISTORY_STUB = { maybeLoadOlder: (_: ScrollBoxHandle) => {} }
// Window after a user-initiated scroll during which type-into-empty does NOT
// repin to bottom. Josh Rosen's workflow: Claude emits long output → scroll
// up to read the start → start typing → before this fix, snapped to bottom.
// https://anthropic.slack.com/archives/C07VBSHV7EV/p1773545449871739
const RECENT_SCROLL_REPIN_WINDOW_MS = 3000
// Use LRU cache to prevent unbounded memory growth
// 100 files should be sufficient for most coding sessions while preventing
// memory issues when working across many files in large projects
function median(values: number[]): number {
const sorted = [...values].sort((a, b) => a - b)
const mid = Math.floor(sorted.length / 2)
return sorted.length % 2 === 0
? Math.round((sorted[mid - 1]! + sorted[mid]!) / 2)
: sorted[mid]!
}
/**
* Small component to display transcript mode footer with dynamic keybinding.
* Must be rendered inside KeybindingSetup to access keybinding context.
*/
function TranscriptModeFooter({
showAllInTranscript,
virtualScroll,
searchBadge,
suppressShowAll = false,
status,
}: {
showAllInTranscript: boolean
virtualScroll: boolean
/** Minimap while navigating a closed-bar search. Shows n/N hints +
* right-aligned count instead of scroll hints. */
searchBadge?: { current: number; count: number }
/** Hide the ctrl+e hint. The [ dump path shares this footer with
* env-opted dump (CLAUDE_CODE_NO_FLICKER=0 / DISABLE_VIRTUAL_SCROLL=1),
* but ctrl+e only works in the env case — useGlobalKeybindings.tsx
* gates on !virtualScrollActive which is env-derived, doesn't know
* [ happened. */
suppressShowAll?: boolean
/** Transient status (v-for-editor progress). Notifications render inside
* PromptInput which isn't mounted in transcript — addNotification queues
* but nothing draws it. */
status?: string
}): React.ReactNode {
const toggleShortcut = useShortcutDisplay(
'app:toggleTranscript',
'Global',
'ctrl+o',
)
const showAllShortcut = useShortcutDisplay(
'transcript:toggleShowAll',
'Transcript',
'ctrl+e',
)
return (
<Box
noSelect
alignItems="center"
alignSelf="center"
borderTopDimColor
borderBottom={false}
borderLeft={false}
borderRight={false}
borderStyle="single"
marginTop={1}
paddingLeft={2}
width="100%"
>
<Text dimColor>
Showing detailed transcript · {toggleShortcut} to toggle
{searchBadge
? ' · n/N to navigate'
: virtualScroll
? ` · ${figures.arrowUp}${figures.arrowDown} scroll · home/end top/bottom`
: suppressShowAll
? ''
: ` · ${showAllShortcut} to ${showAllInTranscript ? 'collapse' : 'show all'}`}
</Text>
{status ? (
// v-for-editor render progress — transient, preempts the search
// badge since the user just pressed v and wants to see what's
// happening. Clears after 4s.
<>
<Box flexGrow={1} />
<Text>{status} </Text>
</>
) : searchBadge ? (
// Engine-counted — close enough for a rough location hint. May
// drift from render-count for ghost/phantom messages.
<>
<Box flexGrow={1} />
<Text dimColor>
{searchBadge.current}/{searchBadge.count}
{' '}
</Text>
</>
) : null}
</Box>
)
}
/** less-style / bar. 1-row, same border-top styling as TranscriptModeFooter
* so swapping them in the bottom slot doesn't shift ScrollBox height.
* useSearchInput handles readline editing; we report query changes and
* render the counter. Incremental — re-search + highlight per keystroke. */
function TranscriptSearchBar({
jumpRef,
count,
current,
onClose,
onCancel,
setHighlight,
initialQuery,
}: {
jumpRef: RefObject<JumpHandle | null>
count: number
current: number
/** Enter — commit. Query persists for n/N. */
onClose: (lastQuery: string) => void
/** Esc/ctrl+c/ctrl+g — undo to pre-/ state. */
onCancel: () => void
setHighlight: (query: string) => void
// Seed with the previous query (less: / shows last pattern). Mount-fire
// of the effect re-scans with the same query — idempotent (same matches,
// nearest-ptr, same highlights). User can edit or clear.
initialQuery: string
}): React.ReactNode {
const { query, cursorOffset } = useSearchInput({
isActive: true,
initialQuery,
onExit: () => onClose(query),
onCancel,
})
// Index warm-up runs before the query effect so it measures the real
// cost — otherwise setSearchQuery fills the cache first and warm
// reports ~0ms while the user felt the actual lag.
// First / in a transcript session pays the extractSearchText cost.
// Subsequent / return 0 immediately (indexWarmed ref in VML).
// Transcript is frozen at ctrl+o so the cache stays valid.
// Initial 'building' so warmDone is false on mount — the [query] effect
// waits for the warm effect's first resolve instead of racing it. With
// null initial, warmDone would be true on mount → [query] fires →
// setSearchQuery fills cache → warm reports ~0ms while the user felt
// the real lag.
const [indexStatus, setIndexStatus] = React.useState<
'building' | { ms: number } | null
>('building')
React.useEffect(() => {
let alive = true
const warm = jumpRef.current?.warmSearchIndex
if (!warm) {
setIndexStatus(null) // VML not mounted yet — rare, skip indicator
return
}
setIndexStatus('building')
warm().then(ms => {
if (!alive) return
// <20ms = imperceptible. No point showing "indexed in 3ms".
if (ms < 20) {
setIndexStatus(null)
} else {
setIndexStatus({ ms })
setTimeout(() => alive && setIndexStatus(null), 2000)
}
})
return () => {
alive = false
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []) // mount-only: bar opens once per /
// Gate the query effect on warm completion. setHighlight stays instant
// (screen-space overlay, no indexing). setSearchQuery (the scan) waits.
const warmDone = indexStatus !== 'building'
useEffect(() => {
if (!warmDone) return
jumpRef.current?.setSearchQuery(query)
setHighlight(query)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query, warmDone])
const off = cursorOffset
const cursorChar = off < query.length ? query[off] : ' '
return (
<Box
borderTopDimColor
borderBottom={false}
borderLeft={false}
borderRight={false}
borderStyle="single"
marginTop={1}
paddingLeft={2}
width="100%"
// applySearchHighlight scans the whole screen buffer. The query
// text rendered here IS on screen — /foo matches its own 'foo' in
// the bar. With no content matches that's the ONLY visible match →
// gets CURRENT → underlined. noSelect makes searchHighlight.ts:76
// skip these cells (same exclusion as gutters). You can't text-
// select the bar either; it's transient chrome, fine.
noSelect
>
<Text>/</Text>
<Text>{query.slice(0, off)}</Text>
<Text inverse>{cursorChar}</Text>
{off < query.length && <Text>{query.slice(off + 1)}</Text>}
<Box flexGrow={1} />
{indexStatus === 'building' ? (
<Text dimColor>indexing… </Text>
) : indexStatus ? (
<Text dimColor>indexed in {indexStatus.ms}ms </Text>
) : count === 0 && query ? (
<Text color="error">no matches </Text>
) : count > 0 ? (
// Engine-counted (indexOf on extractSearchText). May drift from
// render-count for ghost/phantom messages — badge is a rough
// location hint. scanElement gives exact per-message positions
// but counting ALL would cost ~1-3ms × matched-messages.
<Text dimColor>
{current}/{count}
{' '}
</Text>
) : null}
</Box>
)
}
const TITLE_ANIMATION_FRAMES = ['⠂', '⠐']
const TITLE_STATIC_PREFIX = '✳'
const TITLE_ANIMATION_INTERVAL_MS = 960
/**
* Sets the terminal tab title, with an animated prefix glyph while a query
* is running. Isolated from REPL so the 960ms animation tick re-renders only
* this leaf component (which returns null — pure side-effect) instead of the
* entire REPL tree. Before extraction, the tick was ~1 REPL render/sec for
* the duration of every turn, dragging PromptInput and friends along.
*/
function AnimatedTerminalTitle({
isAnimating,
title,
disabled,
noPrefix,
}: {
isAnimating: boolean
title: string
disabled: boolean
noPrefix: boolean
}): null {
const terminalFocused = useTerminalFocus()
const [frame, setFrame] = useState(0)
useEffect(() => {
if (disabled || noPrefix || !isAnimating || !terminalFocused) return
const interval = setInterval(
setFrame => setFrame(f => (f + 1) % TITLE_ANIMATION_FRAMES.length),
TITLE_ANIMATION_INTERVAL_MS,
setFrame,
)
return () => clearInterval(interval)
}, [disabled, noPrefix, isAnimating, terminalFocused])
const prefix = isAnimating
? (TITLE_ANIMATION_FRAMES[frame] ?? TITLE_STATIC_PREFIX)
: TITLE_STATIC_PREFIX
useTerminalTitle(disabled ? null : noPrefix ? title : `${prefix} ${title}`)
return null
}
export type Props = {
commands: Command[]
debug: boolean
initialTools: Tool[]
// Initial messages to populate the REPL with
initialMessages?: MessageType[]
// Deferred hook messages promise — REPL renders immediately and injects
// hook messages when they resolve. Awaited before the first API call.
pendingHookMessages?: Promise<HookResultMessage[]>
initialFileHistorySnapshots?: FileHistorySnapshot[]
// Content-replacement records from a resumed session's transcript — used to
// reconstruct contentReplacementState so the same results are re-replaced
initialContentReplacements?: ContentReplacementRecord[]
// Initial agent context for session resume (name/color set via /rename or /color)
initialAgentName?: string
initialAgentColor?: AgentColorName
mcpClients?: MCPServerConnection[]
dynamicMcpConfig?: Record<string, ScopedMcpServerConfig>
autoConnectIdeFlag?: boolean
strictMcpConfig?: boolean
systemPrompt?: string
appendSystemPrompt?: string
// Optional callback invoked before query execution
// Called after user message is added to conversation but before API call
// Return false to prevent query execution
onBeforeQuery?: (
input: string,
newMessages: MessageType[],
) => Promise<boolean>
// Optional callback when a turn completes (model finishes responding)
onTurnComplete?: (messages: MessageType[]) => void | Promise<void>
// When true, disables REPL input (hides prompt and prevents message selector)
disabled?: boolean
// Optional agent definition to use for the main thread
mainThreadAgentDefinition?: AgentDefinition
// When true, disables all slash commands
disableSlashCommands?: boolean
// Task list id: when set, enables tasks mode that watches a task list and auto-processes tasks.
taskListId?: string
// Remote session config for --remote mode (uses CCR as execution engine)
remoteSessionConfig?: RemoteSessionConfig
// Direct connect config for `claude connect` mode (connects to a claude server)
directConnectConfig?: DirectConnectConfig
// SSH session for `claude ssh` mode (local REPL, remote tools over ssh)
sshSession?: SSHSession
// Thinking configuration to use when thinking is enabled
thinkingConfig: ThinkingConfig
}
export type Screen = 'prompt' | 'transcript'
export function REPL({
commands: initialCommands,
debug,
initialTools,
initialMessages,
pendingHookMessages,
initialFileHistorySnapshots,
initialContentReplacements,
initialAgentName,
initialAgentColor,
mcpClients: initialMcpClients,
dynamicMcpConfig: initialDynamicMcpConfig,
autoConnectIdeFlag,
strictMcpConfig = false,
systemPrompt: customSystemPrompt,
appendSystemPrompt,
onBeforeQuery,
onTurnComplete,
disabled = false,
mainThreadAgentDefinition: initialMainThreadAgentDefinition,
disableSlashCommands = false,
taskListId,
remoteSessionConfig,
directConnectConfig,
sshSession,
thinkingConfig,
}: Props): React.ReactNode {
const isRemoteSession = !!remoteSessionConfig
// Env-var gates hoisted to mount-time — isEnvTruthy does toLowerCase+trim+
// includes, and these were on the render path (hot during PageUp spam).
const titleDisabled = useMemo(
() => isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE),
[],
)
const moreRightEnabled = useMemo(
() =>
"external" === 'ant' &&
isEnvTruthy(process.env.CLAUDE_MORERIGHT),
[],
)
const disableVirtualScroll = useMemo(
() => isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL),
[],
)
const disableMessageActions = feature('MESSAGE_ACTIONS')
? // biome-ignore lint/correctness/useHookAtTopLevel: feature() is a compile-time constant
useMemo(
() => isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_MESSAGE_ACTIONS),
[],
)
: false
// Log REPL mount/unmount lifecycle
useEffect(() => {
logForDebugging(`[REPL:mount] REPL mounted, disabled=${disabled}`)
return () => logForDebugging(`[REPL:unmount] REPL unmounting`)
}, [disabled])
// Agent definition is state so /resume can update it mid-session
const [mainThreadAgentDefinition, setMainThreadAgentDefinition] = useState(
initialMainThreadAgentDefinition,
)
const toolPermissionContext = useAppState(s => s.toolPermissionContext)
const verbose = useAppState(s => s.verbose)
const mcp = useAppState(s => s.mcp)
const plugins = useAppState(s => s.plugins)
const agentDefinitions = useAppState(s => s.agentDefinitions)
const fileHistory = useAppState(s => s.fileHistory)
const initialMessage = useAppState(s => s.initialMessage)
const queuedCommands = useCommandQueue()
// feature() is a build-time constant — dead code elimination removes the hook
// call entirely in external builds, so this is safe despite looking conditional.
// These fields contain excluded strings that must not appear in external builds.
const spinnerTip = useAppState(s => s.spinnerTip)
const showExpandedTodos = useAppState(s => s.expandedView) === 'tasks'
const pendingWorkerRequest = useAppState(s => s.pendingWorkerRequest)
const pendingSandboxRequest = useAppState(s => s.pendingSandboxRequest)
const teamContext = useAppState(s => s.teamContext)
const tasks = useAppState(s => s.tasks)
const workerSandboxPermissions = useAppState(s => s.workerSandboxPermissions)
const elicitation = useAppState(s => s.elicitation)
const ultraplanPendingChoice = useAppState(s => s.ultraplanPendingChoice)
const ultraplanLaunchPending = useAppState(s => s.ultraplanLaunchPending)
const viewingAgentTaskId = useAppState(s => s.viewingAgentTaskId)
const setAppState = useSetAppState()
// Bootstrap: retained local_agent that hasn't loaded disk yet → read
// sidechain JSONL and UUID-merge with whatever stream has appended so far.
// Stream appends immediately on retain (no defer); bootstrap fills the
// prefix. Disk-write-before-yield means live is always a suffix of disk.
const viewedLocalAgent = viewingAgentTaskId
? tasks[viewingAgentTaskId]
: undefined
const needsBootstrap =
isLocalAgentTask(viewedLocalAgent) &&
viewedLocalAgent.retain &&
!viewedLocalAgent.diskLoaded
useEffect(() => {
if (!viewingAgentTaskId || !needsBootstrap) return
const taskId = viewingAgentTaskId
void getAgentTranscript(asAgentId(taskId)).then(result => {
setAppState(prev => {
const t = prev.tasks[taskId]
if (!isLocalAgentTask(t) || t.diskLoaded || !t.retain) return prev
const live = t.messages ?? []
const liveUuids = new Set(live.map(m => m.uuid))
const diskOnly = result
? result.messages.filter(m => !liveUuids.has(m.uuid))
: []
return {
...prev,
tasks: {
...prev.tasks,
[taskId]: {
...t,
messages: [...diskOnly, ...live],
diskLoaded: true,
},
},
}
})
})
}, [viewingAgentTaskId, needsBootstrap, setAppState])
const store = useAppStateStore()
const terminal = useTerminalNotification()
const mainLoopModel = useMainLoopModel()
// Note: standaloneAgentContext is initialized in main.tsx (via initialState) or
// ResumeConversation.tsx (via setAppState before rendering REPL) to avoid
// useEffect-based state initialization on mount (per CLAUDE.md guidelines)
// Local state for commands (hot-reloadable when skill files change)
const [localCommands, setLocalCommands] = useState(initialCommands)
// Watch for skill file changes and reload all commands
useSkillsChange(
isRemoteSession ? undefined : getProjectRoot(),
setLocalCommands,
)
// Track proactive mode for tools dependency - SleepTool filters by proactive state
const proactiveActive = React.useSyncExternalStore(
proactiveModule?.subscribeToProactiveChanges ?? PROACTIVE_NO_OP_SUBSCRIBE,
proactiveModule?.isProactiveActive ?? PROACTIVE_FALSE,
)
// BriefTool.isEnabled() reads getUserMsgOptIn() from bootstrap state, which
// /brief flips mid-session alongside isBriefOnly. The memo below needs a
// React-visible dep to re-run getTools() when that happens; isBriefOnly is
// the AppState mirror that triggers the re-render. Without this, toggling
// /brief mid-session leaves the stale tool list (no SendUserMessage) and
// the model emits plain text the brief filter hides.
const isBriefOnly = useAppState(s => s.isBriefOnly)
const localTools = useMemo(
() => getTools(toolPermissionContext),
[toolPermissionContext, proactiveActive, isBriefOnly],
)
useKickOffCheckAndDisableBypassPermissionsIfNeeded()
useKickOffCheckAndDisableAutoModeIfNeeded()
const [dynamicMcpConfig, setDynamicMcpConfig] = useState<
Record<string, ScopedMcpServerConfig> | undefined
>(initialDynamicMcpConfig)
const onChangeDynamicMcpConfig = useCallback(
(config: Record<string, ScopedMcpServerConfig>) => {
setDynamicMcpConfig(config)
},
[setDynamicMcpConfig],
)
const [screen, setScreen] = useState<Screen>('prompt')
const [showAllInTranscript, setShowAllInTranscript] = useState(false)
// [ forces the dump-to-scrollback path inside transcript mode. Separate
// from CLAUDE_CODE_NO_FLICKER=0 (which is process-lifetime) — this is
// ephemeral, reset on transcript exit. Diagnostic escape hatch so
// terminal/tmux native cmd-F can search the full flat render.
const [dumpMode, setDumpMode] = useState(false)
// v-for-editor render progress. Inline in the footer — notifications
// render inside PromptInput which isn't mounted in transcript.
const [editorStatus, setEditorStatus] = useState('')
// Incremented on transcript exit. Async v-render captures this at start;
// each status write no-ops if stale (user left transcript mid-render —
// the stable setState would otherwise stamp a ghost toast into the next
// session). Also clears any pending 4s auto-clear.
const editorGenRef = useRef(0)
const editorTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
)
const editorRenderingRef = useRef(false)
const { addNotification, removeNotification } = useNotifications()
// eslint-disable-next-line prefer-const
let trySuggestBgPRIntercept = SUGGEST_BG_PR_NOOP
const mcpClients = useMergedClients(initialMcpClients, mcp.clients)
// IDE integration
const [ideSelection, setIDESelection] = useState<IDESelection | undefined>(
undefined,
)
const [ideToInstallExtension, setIDEToInstallExtension] =
useState<IdeType | null>(null)
const [ideInstallationStatus, setIDEInstallationStatus] =
useState<IDEExtensionInstallationStatus | null>(null)
const [showIdeOnboarding, setShowIdeOnboarding] = useState(false)
// Dead code elimination: model switch callout state (ant-only)
const [showModelSwitchCallout, setShowModelSwitchCallout] = useState(() => {
if ("external" === 'ant') {
return shouldShowAntModelSwitch()
}
return false
})
const [showEffortCallout, setShowEffortCallout] = useState(() =>
shouldShowEffortCallout(mainLoopModel),
)
const showRemoteCallout = useAppState(s => s.showRemoteCallout)
const [showDesktopUpsellStartup, setShowDesktopUpsellStartup] = useState(() =>
shouldShowDesktopUpsellStartup(),
)
// notifications
useModelMigrationNotifications()
useCanSwitchToExistingSubscription()
useIDEStatusIndicator({ ideSelection, mcpClients, ideInstallationStatus })
useMcpConnectivityStatus({ mcpClients })
useAutoModeUnavailableNotification()
usePluginInstallationStatus()
usePluginAutoupdateNotification()
useSettingsErrors()
useRateLimitWarningNotification(mainLoopModel)
useFastModeNotification()
useDeprecationWarningNotification(mainLoopModel)
useNpmDeprecationNotification()
useAntOrgWarningNotification()
useInstallMessages()
useChromeExtensionNotification()
useOfficialMarketplaceNotification()
useLspInitializationNotification()
useTeammateLifecycleNotification()
const {
recommendation: lspRecommendation,
handleResponse: handleLspResponse,
} = useLspPluginRecommendation()
const {
recommendation: hintRecommendation,
handleResponse: handleHintResponse,
} = useClaudeCodeHintRecommendation()
// Memoize the combined initial tools array to prevent reference changes
const combinedInitialTools = useMemo(() => {
return [...localTools, ...initialTools]
}, [localTools, initialTools])
// Initialize plugin management
useManagePlugins({ enabled: !isRemoteSession })
const tasksV2 = useTasksV2WithCollapseEffect()
// Start background plugin installations
// SECURITY: This code is guaranteed to run ONLY after the "trust this folder" dialog
// has been confirmed by the user. The trust dialog is shown in cli.tsx (line ~387)
// before the REPL component is rendered. The dialog blocks execution until the user
// accepts, and only then is the REPL component mounted and this effect runs.
// This ensures that plugin installations from repository and user settings only
// happen after explicit user consent to trust the current working directory.
useEffect(() => {
if (isRemoteSession) return
void performStartupChecks(setAppState)
}, [setAppState, isRemoteSession])
// Allow Claude in Chrome MCP to send prompts through MCP notifications
// and sync permission mode changes to the Chrome extension
usePromptsFromClaudeInChrome(
isRemoteSession ? EMPTY_MCP_CLIENTS : mcpClients,
toolPermissionContext.mode,
)
// Initialize swarm features: teammate hooks and context
// Handles both fresh spawns and resumed teammate sessions
useSwarmInitialization(setAppState, initialMessages, {
enabled: !isRemoteSession,
})
const mergedTools = useMergedTools(
combinedInitialTools,
mcp.tools,
toolPermissionContext,
)
// Apply agent tool restrictions if mainThreadAgentDefinition is set
const { tools, allowedAgentTypes } = useMemo(() => {
if (!mainThreadAgentDefinition) {
return {
tools: mergedTools,
allowedAgentTypes: undefined as string[] | undefined,
}
}
const resolved = resolveAgentTools(
mainThreadAgentDefinition,
mergedTools,
false,
true,
)
return {
tools: resolved.resolvedTools,
allowedAgentTypes: resolved.allowedAgentTypes,
}
}, [mainThreadAgentDefinition, mergedTools])
// Merge commands from local state, plugins, and MCP
const commandsWithPlugins = useMergedCommands(
localCommands,
plugins.commands as Command[],
)
const mergedCommands = useMergedCommands(
commandsWithPlugins,
mcp.commands as Command[],
)
// Filter out all commands if disableSlashCommands is true
const commands = useMemo(
() => (disableSlashCommands ? [] : mergedCommands),
[disableSlashCommands, mergedCommands],
)
useIdeLogging(isRemoteSession ? EMPTY_MCP_CLIENTS : mcp.clients)
useIdeSelection(
isRemoteSession ? EMPTY_MCP_CLIENTS : mcp.clients,
setIDESelection,
)
const [streamMode, setStreamMode] = useState<SpinnerMode>('responding')
// Ref mirror so onSubmit can read the latest value without adding
// streamMode to its deps. streamMode flips between
// requesting/responding/tool-use ~10x per turn during streaming; having it
// in onSubmit's deps was recreating onSubmit on every flip, which
// cascaded into PromptInput prop churn and downstream useCallback/useMemo
// invalidation. The only consumers inside callbacks are debug logging and
// telemetry (handlePromptSubmit.ts), so a stale-by-one-render value is
// harmless — but ref mirrors sync on every render anyway so it's fresh.
const streamModeRef = useRef(streamMode)
streamModeRef.current = streamMode
const [streamingToolUses, setStreamingToolUses] = useState<
StreamingToolUse[]
>([])
const [streamingThinking, setStreamingThinking] =
useState<StreamingThinking | null>(null)
// Auto-hide streaming thinking after 30 seconds of being completed
useEffect(() => {
if (
streamingThinking &&
!streamingThinking.isStreaming &&
streamingThinking.streamingEndedAt
) {
const elapsed = Date.now() - streamingThinking.streamingEndedAt
const remaining = 30000 - elapsed
if (remaining > 0) {
const timer = setTimeout(setStreamingThinking, remaining, null)
return () => clearTimeout(timer)
} else {
setStreamingThinking(null)
}
}
}, [streamingThinking])
const [abortController, setAbortController] =
useState<AbortController | null>(null)
// Ref that always points to the current abort controller, used by the
// REPL bridge to abort the active query when a remote interrupt arrives.
const abortControllerRef = useRef<AbortController | null>(null)
abortControllerRef.current = abortController
// Ref for the bridge result callback — set after useReplBridge initializes,
// read in the onQuery finally block to notify mobile clients that a turn ended.
const sendBridgeResultRef = useRef<() => void>(() => {})
// Ref for the synchronous restore callback — set after restoreMessageSync is
// defined, read in the onQuery finally block for auto-restore on interrupt.
const restoreMessageSyncRef = useRef<(m: UserMessage) => void>(() => {})
// Ref to the fullscreen layout's scroll box for keyboard scrolling.
// Null when fullscreen mode is disabled (ref never attached).
const scrollRef = useRef<ScrollBoxHandle>(null)
// Separate ref for the modal slot's inner ScrollBox — passed through
// FullscreenLayout → ModalContext so Tabs can attach it to its own
// ScrollBox for tall content (e.g. /status's MCP-server list). NOT
// keyboard-driven — ScrollKeybindingHandler stays on the outer ref so
// PgUp/PgDn/wheel always scroll the transcript behind the modal.
// Plumbing kept for future modal-scroll wiring.
const modalScrollRef = useRef<ScrollBoxHandle>(null)
// Timestamp of the last user-initiated scroll (wheel, PgUp/PgDn, ctrl+u,
// End/Home, G, drag-to-scroll). Stamped in composedOnScroll — the single
// chokepoint ScrollKeybindingHandler calls for every user scroll action.
// Programmatic scrolls (repinScroll's scrollToBottom, sticky auto-follow)
// do NOT go through composedOnScroll, so they don't stamp this. Ref not
// state: no re-render on every wheel tick.
const lastUserScrollTsRef = useRef(0)
// Synchronous state machine for the query lifecycle. Replaces the
// error-prone dual-state pattern where isLoading (React state, async
// batched) and isQueryRunning (ref, sync) could desync. See QueryGuard.ts.
const queryGuard = React.useRef(new QueryGuard()).current
// Subscribe to the guard — true during dispatching or running.
// This is the single source of truth for "is a local query in flight".
const isQueryActive = React.useSyncExternalStore(
queryGuard.subscribe,
queryGuard.getSnapshot,
)
// /goal auto-continuation: enqueues meta prompts when a goal is active and
// the query guard transitions from active -> idle.
useGoalAutoContinue(queryGuard)
// Separate loading flag for operations outside the local query guard:
// remote sessions (useRemoteSession / useDirectConnect) and foregrounded
// background tasks (useSessionBackgrounding). These don't route through
// onQuery / queryGuard, so they need their own spinner-visibility state.
// Initialize true if remote mode with initial prompt (CCR processing it).
const [isExternalLoading, setIsExternalLoadingRaw] = React.useState(
remoteSessionConfig?.hasInitialPrompt ?? false,
)
// Derived: any loading source active. Read-only — no setter. Local query
// loading is driven by queryGuard (reserve/tryStart/end/cancelReservation),
// external loading by setIsExternalLoading.
const isLoading = isQueryActive || isExternalLoading
// Elapsed time is computed by SpinnerWithVerb from these refs on each
// animation frame, avoiding a useInterval that re-renders the entire REPL.
const [userInputOnProcessing, setUserInputOnProcessingRaw] = React.useState<
string | undefined
>(undefined)
// messagesRef.current.length at the moment userInputOnProcessing was set.
// The placeholder hides once displayedMessages grows past this — i.e. the
// real user message has landed in the visible transcript.
const userInputBaselineRef = React.useRef(0)
// True while the submitted prompt is being processed but its user message
// hasn't reached setMessages yet. setMessages uses this to keep the
// baseline in sync when unrelated async messages (bridge status, hook
// results, scheduled tasks) land during that window.
const userMessagePendingRef = React.useRef(false)
// Wall-clock time tracking refs for accurate elapsed time calculation
const loadingStartTimeRef = React.useRef<number>(0)
const totalPausedMsRef = React.useRef(0)
const pauseStartTimeRef = React.useRef<number | null>(null)
const resetTimingRefs = React.useCallback(() => {
loadingStartTimeRef.current = Date.now()
totalPausedMsRef.current = 0
pauseStartTimeRef.current = null
}, [])
// Reset timing refs inline when isQueryActive transitions false→true.
// queryGuard.reserve() (in executeUserInput) fires BEFORE processUserInput's
// first await, but the ref reset in onQuery's try block runs AFTER. During
// that gap, React renders the spinner with loadingStartTimeRef=0, computing
// elapsedTimeMs = Date.now() - 0 ≈ 56 years. This inline reset runs on the
// first render where isQueryActive is observed true — the same render that
// first shows the spinner — so the ref is correct by the time the spinner
// reads it. See INC-4549.
const wasQueryActiveRef = React.useRef(false)
if (isQueryActive && !wasQueryActiveRef.current) {
resetTimingRefs()
}
wasQueryActiveRef.current = isQueryActive
// Wrapper for setIsExternalLoading that resets timing refs on transition
// to true — SpinnerWithVerb reads these for elapsed time, so they must be
// reset for remote sessions / foregrounded tasks too (not just local
// queries, which reset them in onQuery). Without this, a remote-only
// session would show ~56 years elapsed (Date.now() - 0).
const setIsExternalLoading = React.useCallback(
(value: boolean) => {
setIsExternalLoadingRaw(value)
if (value) resetTimingRefs()
},
[resetTimingRefs],
)
// Start time of the first turn that had swarm teammates running
// Used to compute total elapsed time (including teammate execution) for the deferred message
const swarmStartTimeRef = React.useRef<number | null>(null)
const swarmBudgetInfoRef = React.useRef<
{ tokens: number; limit: number; nudges: number } | undefined
>(undefined)
// Ref to track current focusedInputDialog for use in callbacks
// This avoids stale closures when checking dialog state in timer callbacks
const focusedInputDialogRef =
React.useRef<ReturnType<typeof getFocusedInputDialog>>(undefined)
// How long after the last keystroke before deferred dialogs are shown
const PROMPT_SUPPRESSION_MS = 1500
// True when user is actively typing — defers interrupt dialogs so keystrokes
// don't accidentally dismiss or answer a permission prompt the user hasn't read yet.
const [isPromptInputActive, setIsPromptInputActive] = React.useState(false)
const [autoUpdaterResult, setAutoUpdaterResult] =
useState<AutoUpdaterResult | null>(null)
useEffect(() => {
if (autoUpdaterResult?.notifications) {
autoUpdaterResult.notifications.forEach(notification => {
addNotification({
key: 'auto-updater-notification',
text: notification,
priority: 'low',
})
})
}
}, [autoUpdaterResult, addNotification])
// tmux + fullscreen + `mouse off`: one-time hint that wheel won't scroll.
// We no longer mutate tmux's session-scoped mouse option (it poisoned
// sibling panes); tmux users already know this tradeoff from vim/less.
useEffect(() => {
if (isFullscreenEnvEnabled()) {
void maybeGetTmuxMouseHint().then(hint => {
if (hint) {
addNotification({
key: 'tmux-mouse-hint',
text: hint,
priority: 'low',
})
}
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const [showUndercoverCallout, setShowUndercoverCallout] = useState(false)
useEffect(() => {
if ("external" === 'ant') {
void (async () => {
// Wait for repo classification to settle (memoized, no-op if primed).
const { isInternalModelRepo } = await import(
'../utils/commitAttribution.js'
)
await isInternalModelRepo()
const { shouldShowUndercoverAutoNotice } = await import(
'../utils/undercover.js'
)
if (shouldShowUndercoverAutoNotice()) {
setShowUndercoverCallout(true)
}
})()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const [toolJSX, setToolJSXInternal] = useState<{
jsx: React.ReactNode | null
shouldHidePromptInput: boolean
shouldContinueAnimation?: true
showSpinner?: boolean
isLocalJSXCommand?: boolean
isImmediate?: boolean
} | null>(null)
// Track local JSX commands separately so tools can't overwrite them.
// This enables "immediate" commands (like /btw) to persist while Claude is processing.
const localJSXCommandRef = useRef<{
jsx: React.ReactNode | null
shouldHidePromptInput: boolean
shouldContinueAnimation?: true
showSpinner?: boolean
isLocalJSXCommand: true
} | null>(null)
// Wrapper for setToolJSX that preserves local JSX commands (like /btw).
// When a local JSX command is active, we ignore updates from tools
// unless they explicitly set clearLocalJSX: true (from onDone callbacks).
//
// TO ADD A NEW IMMEDIATE COMMAND:
// 1. Set `immediate: true` in the command definition
// 2. Set `isLocalJSXCommand: true` when calling setToolJSX in the command's JSX
// 3. In the onDone callback, use `setToolJSX({ jsx: null, shouldHidePromptInput: false, clearLocalJSX: true })`
// to explicitly clear the overlay when the user dismisses it
const setToolJSX = useCallback(
(
args: {
jsx: React.ReactNode | null
shouldHidePromptInput: boolean
shouldContinueAnimation?: true
showSpinner?: boolean
isLocalJSXCommand?: boolean
clearLocalJSX?: boolean
} | null,
) => {
// If setting a local JSX command, store it in the ref
if (args?.isLocalJSXCommand) {
const { clearLocalJSX: _, ...rest } = args
localJSXCommandRef.current = { ...rest, isLocalJSXCommand: true }
setToolJSXInternal(rest)
return
}
// If there's an active local JSX command in the ref
if (localJSXCommandRef.current) {
// Allow clearing only if explicitly requested (from onDone callbacks)
if (args?.clearLocalJSX) {
localJSXCommandRef.current = null
setToolJSXInternal(null)
return
}
// Otherwise, keep the local JSX command visible - ignore tool updates
return
}
// No active local JSX command, allow any update
if (args?.clearLocalJSX) {
setToolJSXInternal(null)
return
}
setToolJSXInternal(args)
},
[],
)
const [toolUseConfirmQueue, setToolUseConfirmQueue] = useState<
ToolUseConfirm[]
>([])
// Sticky footer JSX registered by permission request components (currently
// only ExitPlanModePermissionRequest). Renders in FullscreenLayout's `bottom`
// slot so response options stay visible while the user scrolls a long plan.
const [permissionStickyFooter, setPermissionStickyFooter] =
useState<React.ReactNode | null>(null)
const [sandboxPermissionRequestQueue, setSandboxPermissionRequestQueue] =
useState<
Array<{
hostPattern: NetworkHostPattern
resolvePromise: (allowConnection: boolean) => void
}>
>([])
const [promptQueue, setPromptQueue] = useState<
Array<{
request: PromptRequest
title: string
toolInputSummary?: string | null
resolve: (response: PromptResponse) => void
reject: (error: Error) => void
}>
>([])
const [questionRequest, setQuestionRequest] =
useState<import('../services/question/questionService.js').QuestionRequest | null>(null)
useEffect(() => {
const { questionService } = require('../services/question/questionService.js') as typeof import('../services/question/questionService.js')
// Bridge cleanup keyed by question request id, so a local reply/reject can
// cancel the remote prompt (and vice versa) whichever side answers first.
const bridgeCleanups = new Map<string, () => void>()
const onAsked = (
request: import('../services/question/questionService.js').QuestionRequest,
) => {
setQuestionRequest(request)
// When the REPL bridge is connected, forward the question to the remote
// user (e.g. on claude.ai) as a can_use_tool control_request, racing it
// against the local overlay. Mirrors the sandbox permission pattern.
if (!feature('BRIDGE_MODE')) return
const bridgeCallbacks = store.getState().replBridgePermissionCallbacks
if (!bridgeCallbacks) return
const bridgeRequestId = randomUUID()
bridgeCallbacks.sendRequest(
bridgeRequestId,
'AskUserQuestion',
{ questions: request.questions },
request.id,
request.questions.map(q => q.question).join(' | '),
)
const unsubscribe = bridgeCallbacks.onResponse(bridgeRequestId, response => {
bridgeCleanups.delete(request.id)
unsubscribe()
if (response.behavior === 'allow') {
// CCR returns per-question answers when it has a dedicated renderer;
// fall back to first option so a generic allow degrades gracefully.
const remote = response.updatedInput?.answers
const answers = request.questions.map((q, i) => {
const provided = Array.isArray(remote) ? remote[i] : undefined
if (Array.isArray(provided)) return provided.map(String)
if (typeof provided === 'string') return [provided]
const first = q.options[0]?.label
return first ? [first] : []
})
questionService.reply({ requestID: request.id, answers })
} else {
questionService.reject(request.id)
}
})
bridgeCleanups.set(request.id, () => {
unsubscribe()
bridgeCallbacks.cancelRequest(bridgeRequestId)
})
}
// Local (or remote) resolution: dismiss the overlay and tear down the
// matching remote prompt so it doesn't linger on the other side.
const onResolved = (payload: { requestID: string }) => {
setQuestionRequest(prev =>
prev && prev.id === payload.requestID ? null : prev,
)
const cleanup = bridgeCleanups.get(payload.requestID)
if (cleanup) {
bridgeCleanups.delete(payload.requestID)
cleanup()
}
}
questionService.events.on('asked', onAsked)
questionService.events.on('replied', onResolved)
questionService.events.on('rejected', onResolved)
return () => {
questionService.events.off('asked', onAsked)
questionService.events.off('replied', onResolved)
questionService.events.off('rejected', onResolved)
for (const cleanup of bridgeCleanups.values()) cleanup()
bridgeCleanups.clear()
}
}, [store])
// Track bridge cleanup functions for sandbox permission requests so the
// local dialog handler can cancel the remote prompt when the local user
// responds first. Keyed by host to support concurrent same-host requests.
const sandboxBridgeCleanupRef = useRef<Map<string, Array<() => void>>>(
new Map(),
)
// -- Terminal title management
// Session title (set via /rename or restored on resume) wins over
// the agent name, which wins over the Haiku-extracted topic;
// all fall back to the product name.
const terminalTitleFromRename =
useAppState(s => s.settings.terminalTitleFromRename) !== false
const sessionTitle = terminalTitleFromRename
? getCurrentSessionTitle(getSessionId())
: undefined
const [autoGeneratedTitle, setAutoGeneratedTitle] = useState<string>()
// Gates the one-shot title generation call. Seeded true on resume
// (initialMessages present) so we don't re-title a resumed session
// from mid-conversation context.
const titleGenerationAttemptedRef = useRef((initialMessages?.length ?? 0) > 0)
const agentTitle = mainThreadAgentDefinition?.agentType
const terminalTitle =
sessionTitle ?? agentTitle ?? autoGeneratedTitle ?? 'Codev'
const isWaitingForApproval =
toolUseConfirmQueue.length > 0 ||
promptQueue.length > 0 ||
pendingWorkerRequest ||
pendingSandboxRequest
// Local-jsx commands (like /plugin, /config) show user-facing dialogs that
// wait for input. Require jsx != null — if the flag is stuck true but jsx
// is null, treat as not-showing so TextInput focus and queue processor
// aren't deadlocked by a phantom overlay.
const isShowingLocalJSXCommand =
toolJSX?.isLocalJSXCommand === true && toolJSX?.jsx != null
const titleIsAnimating =
isLoading && !isWaitingForApproval && !isShowingLocalJSXCommand
// Title animation state lives in <AnimatedTerminalTitle> so the 960ms tick
// doesn't re-render REPL. titleDisabled/terminalTitle are still computed
// here because onQueryImpl reads them (background session description,
// haiku title extraction gate).
// Prevent macOS from sleeping while Claude is working
useEffect(() => {
if (isLoading && !isWaitingForApproval && !isShowingLocalJSXCommand) {
startPreventSleep()
return () => stopPreventSleep()
}
}, [isLoading, isWaitingForApproval, isShowingLocalJSXCommand])
const sessionStatus: TabStatusKind =
isWaitingForApproval || isShowingLocalJSXCommand
? 'waiting'
: isLoading
? 'busy'
: 'idle'
const waitingFor =
sessionStatus !== 'waiting'
? undefined
: toolUseConfirmQueue.length > 0
? `approve ${toolUseConfirmQueue[0]!.tool.name}`
: pendingWorkerRequest
? 'worker request'
: pendingSandboxRequest
? 'sandbox request'
: isShowingLocalJSXCommand
? 'dialog open'
: 'input needed'
// Push status to the PID file for `claude ps`. Fire-and-forget; ps falls
// back to transcript-tail derivation when this is missing/stale.
useEffect(() => {
if (feature('BG_SESSIONS')) {
void updateSessionActivity({ status: sessionStatus, waitingFor })
}
}, [sessionStatus, waitingFor])
// 3P default: off — OSC 21337 is ant-only while the spec stabilizes.
// Gated so we can roll back if the sidebar indicator conflicts with
// the title spinner in terminals that render both. When the flag is
// on, the user-facing config setting controls whether it's active.
const tabStatusGateEnabled = getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_terminal_sidebar',
false,
)
const showStatusInTerminalTab =
tabStatusGateEnabled && (getGlobalConfig().showStatusInTerminalTab ?? false)
useTabStatus(titleDisabled || !showStatusInTerminalTab ? null : sessionStatus)
// Register the leader's setToolUseConfirmQueue for in-process teammates
useEffect(() => {
registerLeaderToolUseConfirmQueue(setToolUseConfirmQueue)
return () => unregisterLeaderToolUseConfirmQueue()
}, [setToolUseConfirmQueue])
const [messages, rawSetMessages] = useState<MessageType[]>(
initialMessages ?? [],
)
const messagesRef = useRef(messages)
// Stores the willowMode variant that was shown (or false if no hint shown).
// Captured at hint_shown time so hint_converted telemetry reports the same
// variant — the GrowthBook value shouldn't change mid-session, but reading
// it once guarantees consistency between the paired events.
const idleHintShownRef = useRef<string | false>(false)
// Wrap setMessages so messagesRef is always current the instant the
// call returns — not when React later processes the batch. Apply the
// updater eagerly against the ref, then hand React the computed value
// (not the function). rawSetMessages batching becomes last-write-wins,
// and the last write is correct because each call composes against the
// already-updated ref. This is the Zustand pattern: ref is source of
// truth, React state is the render projection. Without this, paths
// that queue functional updaters then synchronously read the ref
// (e.g. handleSpeculationAccept → onQuery) see stale data.
const setMessages = useCallback(
(action: React.SetStateAction<MessageType[]>) => {
const prev = messagesRef.current
const next =
typeof action === 'function' ? action(messagesRef.current) : action
messagesRef.current = next
if (next.length < userInputBaselineRef.current) {
// Shrank (compact/rewind/clear) — clamp so placeholderText's length
// check can't go stale.
userInputBaselineRef.current = 0
} else if (next.length > prev.length && userMessagePendingRef.current) {
// Grew while the submitted user message hasn't landed yet. If the
// added messages don't include it (bridge status, hook results,
// scheduled tasks landing async during processUserInputBase), bump
// baseline so the placeholder stays visible. Once the user message
// lands, stop tracking — later additions (assistant stream) should
// not re-show the placeholder.
const delta = next.length - prev.length
const added =
prev.length === 0 || next[0] === prev[0]
? next.slice(-delta)
: next.slice(0, delta)
if (added.some(isHumanTurn)) {
userMessagePendingRef.current = false
} else {
userInputBaselineRef.current = next.length
}
}
rawSetMessages(next)
},
[],
)
// Capture the baseline message count alongside the placeholder text so
// the render can hide it once displayedMessages grows past the baseline.
const setUserInputOnProcessing = useCallback((input: string | undefined) => {
if (input !== undefined) {
userInputBaselineRef.current = messagesRef.current.length
userMessagePendingRef.current = true
} else {
userMessagePendingRef.current = false
}
setUserInputOnProcessingRaw(input)
}, [])
// Fullscreen: track the unseen-divider position. dividerIndex changes
// only ~twice/scroll-session (first scroll-away + repin). pillVisible
// and stickyPrompt now live in FullscreenLayout — they subscribe to
// ScrollBox directly so per-frame scroll never re-renders REPL.
const {
dividerIndex,
dividerYRef,
onScrollAway,
onRepin,
jumpToNew,
shiftDivider,
} = useUnseenDivider(messages.length)
if (feature('AWAY_SUMMARY')) {
// biome-ignore lint/correctness/useHookAtTopLevel: feature() is a compile-time constant
useAwaySummary(messages, setMessages, isLoading)
}
const [cursor, setCursor] = useState<MessageActionsState | null>(null)
const cursorNavRef = useRef<MessageActionsNav | null>(null)
// Memoized so Messages' React.memo holds.
const unseenDivider = useMemo(
() => computeUnseenDivider(messages, dividerIndex),
// eslint-disable-next-line react-hooks/exhaustive-deps -- length change covers appends; useUnseenDivider's count-drop guard clears dividerIndex on replace/rewind
[dividerIndex, messages.length],
)
// Re-pin scroll to bottom and clear the unseen-messages baseline. Called
// on any user-driven return-to-live action (submit, type-into-empty,
// overlay appear/dismiss).
const repinScroll = useCallback(() => {
scrollRef.current?.scrollToBottom()
onRepin()
setCursor(null)
}, [onRepin, setCursor])
// Backstop for the submit-handler repin at onSubmit. If a buffered stdin
// event (wheel/drag) races between handler-fire and state-commit, the
// handler's scrollToBottom can be undone. This effect fires on the render
// where the user's message actually lands — tied to React's commit cycle,
// so it can't race with stdin. Keyed on lastMsg identity (not messages.length)
// so useAssistantHistory's prepends don't spuriously repin.
const lastMsg = messages.at(-1)
const lastMsgIsHuman = lastMsg != null && isHumanTurn(lastMsg)
useEffect(() => {
if (lastMsgIsHuman) {
repinScroll()
}
}, [lastMsgIsHuman, lastMsg, repinScroll])
// Assistant-chat: lazy-load remote history on scroll-up. No-op unless
// KAIROS build + config.viewerOnly. feature() is build-time constant so
// the branch is dead-code-eliminated in non-KAIROS builds (same pattern
// as useUnseenDivider above).
const { maybeLoadOlder } = feature('KAIROS')
? // biome-ignore lint/correctness/useHookAtTopLevel: feature() is a compile-time constant
useAssistantHistory({
config: remoteSessionConfig,
setMessages,
scrollRef,
onPrepend: shiftDivider,
})
: HISTORY_STUB
// Compose useUnseenDivider's callbacks with the lazy-load trigger.
const composedOnScroll = useCallback(
(sticky: boolean, handle: ScrollBoxHandle) => {
lastUserScrollTsRef.current = Date.now()
if (sticky) {
onRepin()
} else {
onScrollAway(handle)
if (feature('KAIROS')) maybeLoadOlder(handle)
// Dismiss the companion bubble on scroll — it's absolute-positioned
// at bottom-right and covers transcript content. Scrolling = user is
// trying to read something under it.
if (feature('BUDDY')) {
setAppState(prev =>
prev.companionReaction === undefined
? prev
: { ...prev, companionReaction: undefined },
)
}
}
},
[onRepin, onScrollAway, maybeLoadOlder, setAppState],
)
// Deferred SessionStart hook messages — REPL renders immediately and
// hook messages are injected when they resolve. awaitPendingHooks()
// must be called before the first API call so the model sees hook context.
const awaitPendingHooks = useDeferredHookMessages(
pendingHookMessages,
setMessages,
)
// Deferred messages for the Messages component — renders at transition
// priority so the reconciler yields every 5ms, keeping input responsive
// while the expensive message processing pipeline runs.
const deferredMessages = useDeferredValue(messages)
const deferredBehind = messages.length - deferredMessages.length
if (deferredBehind > 0) {
logForDebugging(
`[useDeferredValue] Messages deferred by ${deferredBehind} (${deferredMessages.length}→${messages.length})`,
)
}
// Frozen state for transcript mode - stores lengths instead of cloning arrays for memory efficiency
const [frozenTranscriptState, setFrozenTranscriptState] = useState<{
messagesLength: number
streamingToolUsesLength: number
} | null>(null)
// Initialize input with any early input that was captured before REPL was ready.
// Using lazy initialization ensures cursor offset is set correctly in PromptInput.
const [inputValue, setInputValueRaw] = useState(() => consumeEarlyInput())
const inputValueRef = useRef(inputValue)
inputValueRef.current = inputValue
const insertTextRef = useRef<{
insert: (text: string) => void
setInputWithCursor: (value: string, cursor: number) => void
cursorOffset: number
} | null>(null)
// Wrap setInputValue to co-locate suppression state updates.
// Both setState calls happen in the same synchronous context so React
// batches them into a single render, eliminating the extra render that
// the previous useEffect → setState pattern caused.
const setInputValue = useCallback(
(value: string) => {
if (trySuggestBgPRIntercept(inputValueRef.current, value)) return
// In fullscreen mode, typing into an empty prompt re-pins scroll to
// bottom. Only fires on empty→non-empty so scrolling up to reference
// something while composing a message doesn't yank the view back on
// every keystroke. Restores the pre-fullscreen muscle memory of
// typing to snap back to the end of the conversation.
// Skipped if the user scrolled within the last 3s — they're actively
// reading, not lost. lastUserScrollTsRef starts at 0 so the first-
// ever keypress (no scroll yet) always repins.
if (
inputValueRef.current === '' &&
value !== '' &&
Date.now() - lastUserScrollTsRef.current >=
RECENT_SCROLL_REPIN_WINDOW_MS
) {
repinScroll()
}
// Sync ref immediately (like setMessages) so callers that read
// inputValueRef before React commits — e.g. the auto-restore finally
// block's `=== ''` guard — see the fresh value, not the stale render.
inputValueRef.current = value
setInputValueRaw(value)
setIsPromptInputActive(value.trim().length > 0)
},
[setIsPromptInputActive, repinScroll, trySuggestBgPRIntercept],
)
// Schedule a timeout to stop suppressing dialogs after the user stops typing.
// Only manages the timeout — the immediate activation is handled by setInputValue above.
useEffect(() => {
if (inputValue.trim().length === 0) return
const timer = setTimeout(
setIsPromptInputActive,
PROMPT_SUPPRESSION_MS,
false,
)
return () => clearTimeout(timer)
}, [inputValue])
const [inputMode, setInputMode] = useState<PromptInputMode>('prompt')
const [stashedPrompt, setStashedPrompt] = useState<
| {
text: string
cursorOffset: number
pastedContents: Record<number, PastedContent>
}
| undefined
>()
// Callback to filter commands based on CCR's available slash commands
const handleRemoteInit = useCallback(
(remoteSlashCommands: string[]) => {
const remoteCommandSet = new Set(remoteSlashCommands)
// Keep commands that CCR lists OR that are in the local-safe set
setLocalCommands(prev =>
prev.filter(
cmd =>
remoteCommandSet.has(cmd.name) || REMOTE_SAFE_COMMANDS.has(cmd),
),
)
},
[setLocalCommands],
)
const [inProgressToolUseIDs, setInProgressToolUseIDs] = useState<Set<string>>(
new Set(),
)
const hasInterruptibleToolInProgressRef = useRef(false)
// Remote session hook - manages WebSocket connection and message handling for --remote mode
const remoteSession = useRemoteSession({
config: remoteSessionConfig,
setMessages,
setIsLoading: setIsExternalLoading,
onInit: handleRemoteInit,
setToolUseConfirmQueue,
tools: combinedInitialTools,
setStreamingToolUses,
setStreamMode,
setInProgressToolUseIDs,
})
// Direct connect hook - manages WebSocket to a claude server for `claude connect` mode
const directConnect = useDirectConnect({
config: directConnectConfig,
setMessages,
setIsLoading: setIsExternalLoading,
setToolUseConfirmQueue,
tools: combinedInitialTools,
})
// SSH session hook - manages ssh child process for `claude ssh` mode.
// Same callback shape as useDirectConnect; only the transport under the
// hood differs (ChildProcess stdin/stdout vs WebSocket).
const sshRemote = useSSHSession({
session: sshSession,
setMessages,
setIsLoading: setIsExternalLoading,
setToolUseConfirmQueue,
tools: combinedInitialTools,
})
// Use whichever remote mode is active
const activeRemote = sshRemote.isRemoteMode
? sshRemote
: directConnect.isRemoteMode
? directConnect
: remoteSession
const [pastedContents, setPastedContents] = useState<
Record<number, PastedContent>
>({})
const [submitCount, setSubmitCount] = useState(0)
// Ref instead of state to avoid triggering React re-renders on every
// streaming text_delta. The spinner reads this via its animation timer.
const responseLengthRef = useRef(0)
// API performance metrics ref for ant-only spinner display (TTFT/OTPS).
// Accumulates metrics from all API requests in a turn for P50 aggregation.
const apiMetricsRef = useRef<
Array<{
ttftMs: number
firstTokenTime: number
lastTokenTime: number
responseLengthBaseline: number
// Tracks responseLengthRef at the time of the last content addition.
// Updated by both streaming deltas and subagent message content.
// lastTokenTime is also updated at the same time, so the OTPS
// denominator correctly includes subagent processing time.
endResponseLength: number
}>
>([])
const setResponseLength = useCallback((f: (prev: number) => number) => {
const prev = responseLengthRef.current
responseLengthRef.current = f(prev)
// When content is added (not a compaction reset), update the latest
// metrics entry so OTPS reflects all content generation activity.
// Updating lastTokenTime here ensures the denominator includes both
// streaming time AND subagent execution time, preventing inflation.
if (responseLengthRef.current > prev) {
const entries = apiMetricsRef.current
if (entries.length > 0) {
const lastEntry = entries.at(-1)!
lastEntry.lastTokenTime = Date.now()
lastEntry.endResponseLength = responseLengthRef.current
}
}
}, [])
// Streaming text display: set state directly per delta (Ink's 16ms render
// throttle batches rapid updates). Cleared on message arrival (messages.ts)
// so displayedMessages switches from deferredMessages to messages atomically.
const [streamingText, setStreamingText] = useState<string | null>(null)
const reducedMotion =
useAppState(s => s.settings.prefersReducedMotion) ?? false
const showStreamingText = !reducedMotion && !hasCursorUpViewportYankBug()
const onStreamingText = useCallback(
(f: (current: string | null) => string | null) => {
if (!showStreamingText) return
setStreamingText(f)
},
[showStreamingText],
)
// Hide the in-progress source line so text streams line-by-line, not
// char-by-char. lastIndexOf returns -1 when no newline, giving '' → null.
// Guard on showStreamingText so toggling reducedMotion mid-stream
// immediately hides the streaming preview.
const visibleStreamingText =
streamingText && showStreamingText
? streamingText.substring(0, streamingText.lastIndexOf('\n') + 1) || null
: null
const [lastQueryCompletionTime, setLastQueryCompletionTime] = useState(0)
const [spinnerMessage, setSpinnerMessage] = useState<string | null>(null)
const [spinnerColor, setSpinnerColor] = useState<keyof Theme | null>(null)
const [spinnerShimmerColor, setSpinnerShimmerColor] = useState<
keyof Theme | null
>(null)
const [isMessageSelectorVisible, setIsMessageSelectorVisible] =
useState(false)
const [messageSelectorPreselect, setMessageSelectorPreselect] = useState<
UserMessage | undefined
>(undefined)
const [showCostDialog, setShowCostDialog] = useState(false)
const [conversationId, setConversationId] = useState(randomUUID())
// Idle-return dialog: shown when user submits after a long idle gap
const [idleReturnPending, setIdleReturnPending] = useState<{
input: string
idleMinutes: number
} | null>(null)
const skipIdleCheckRef = useRef(false)
const lastQueryCompletionTimeRef = useRef(lastQueryCompletionTime)
lastQueryCompletionTimeRef.current = lastQueryCompletionTime
// Aggregate tool result budget: per-conversation decision tracking.
// When the GrowthBook flag is on, query.ts enforces the budget; when
// off (undefined), enforcement is skipped entirely. Stale entries after
// /clear, rewind, or compact are harmless (tool_use_ids are UUIDs, stale
// keys are never looked up). Memory is bounded by total replacement count
// × ~2KB preview over the REPL lifetime — negligible.
//
// Lazy init via useState initializer — useRef(expr) evaluates expr on every
// render (React ignores it after first, but the computation still runs).
// For large resumed sessions, reconstruction does O(messages × blocks)
// work; we only want that once.
const [contentReplacementStateRef] = useState(() => ({
current: provisionContentReplacementState(
initialMessages,
initialContentReplacements,
),
}))
const [haveShownCostDialog, setHaveShownCostDialog] = useState(
getGlobalConfig().hasAcknowledgedCostThreshold,
)
const [vimMode, setVimMode] = useState<VimMode>('INSERT')
const [showBashesDialog, setShowBashesDialog] = useState<string | boolean>(
false,
)
const [isSearchingHistory, setIsSearchingHistory] = useState(false)
const [isHelpOpen, setIsHelpOpen] = useState(false)
// showBashesDialog is REPL-level so it survives PromptInput unmounting.
// When ultraplan approval fires while the pill dialog is open, PromptInput
// unmounts (focusedInputDialog → 'ultraplan-choice') but this stays true;
// after accepting, PromptInput remounts into an empty "No tasks" dialog
// (the completed ultraplan task has been filtered out). Close it here.
useEffect(() => {
if (ultraplanPendingChoice && showBashesDialog) {
setShowBashesDialog(false)
}
}, [ultraplanPendingChoice, showBashesDialog])
const isTerminalFocused = useTerminalFocus()
const terminalFocusRef = useRef(isTerminalFocused)
terminalFocusRef.current = isTerminalFocused
const [theme] = useTheme()
// resetLoadingState runs twice per turn (onQueryImpl tail + onQuery finally).
// Without this guard, both calls pick a tip → two recordShownTip → two
// saveGlobalConfig writes back-to-back. Reset at submit in onSubmit.
const tipPickedThisTurnRef = React.useRef(false)
const pickNewSpinnerTip = useCallback(() => {
if (tipPickedThisTurnRef.current) return
tipPickedThisTurnRef.current = true
const newMessages = messagesRef.current.slice(bashToolsProcessedIdx.current)
for (const tool of extractBashToolsFromMessages(newMessages)) {
bashTools.current.add(tool)
}
bashToolsProcessedIdx.current = messagesRef.current.length
void getTipToShowOnSpinner({
theme,
readFileState: readFileState.current,
bashTools: bashTools.current,
}).then(async tip => {
if (tip) {
const content = await tip.content({ theme })
setAppState(prev => ({
...prev,
spinnerTip: content,
}))
recordShownTip(tip)
} else {
setAppState(prev => {
if (prev.spinnerTip === undefined) return prev
return { ...prev, spinnerTip: undefined }
})
}
})
}, [setAppState, theme])
// Resets UI loading state. Does NOT call onTurnComplete - that should be
// called explicitly only when a query turn actually completes.
const resetLoadingState = useCallback(() => {
// isLoading is now derived from queryGuard — no setter call needed.
// queryGuard.end() (onQuery finally) or cancelReservation() (executeUserInput
// finally) have already transitioned the guard to idle by the time this runs.
// External loading (remote/backgrounding) is reset separately by those hooks.
setIsExternalLoading(false)
setUserInputOnProcessing(undefined)
responseLengthRef.current = 0
apiMetricsRef.current = []
setStreamingText(null)
setStreamingToolUses([])
setSpinnerMessage(null)
setSpinnerColor(null)
setSpinnerShimmerColor(null)
pickNewSpinnerTip()
endInteractionSpan()
// Speculative bash classifier checks are only valid for the current
// turn's commands — clear after each turn to avoid accumulating
// Promise chains for unconsumed checks (denied/aborted paths).
clearSpeculativeChecks()
}, [pickNewSpinnerTip])
// Session backgrounding — hook is below, after getToolUseContext
const hasRunningTeammates = useMemo(
() => getAllInProcessTeammateTasks(tasks).some(t => t.status === 'running'),
[tasks],
)
// Show deferred turn duration message once all swarm teammates finish
useEffect(() => {
if (!hasRunningTeammates && swarmStartTimeRef.current !== null) {
const totalMs = Date.now() - swarmStartTimeRef.current
const deferredBudget = swarmBudgetInfoRef.current
swarmStartTimeRef.current = null
swarmBudgetInfoRef.current = undefined
setMessages(prev => [
...prev,
createTurnDurationMessage(
totalMs,
deferredBudget,
// Count only what recordTranscript will persist — ephemeral
// progress ticks and non-ant attachments are filtered by
// isLoggableMessage and never reach disk. Using raw prev.length
// would make checkResumeConsistency report false delta<0 for
// every turn that ran a progress-emitting tool.
count(prev, isLoggableMessage),
),
])
}
}, [hasRunningTeammates, setMessages])
// Show auto permissions warning when entering auto mode
// (either via Shift+Tab toggle or on startup). Debounced to avoid
// flashing when the user is cycling through modes quickly.
// Only shown 3 times total across sessions.
const safeYoloMessageShownRef = useRef(false)
useEffect(() => {
if (feature('TRANSCRIPT_CLASSIFIER')) {
if (toolPermissionContext.mode !== 'auto') {
safeYoloMessageShownRef.current = false
return
}
if (safeYoloMessageShownRef.current) return
const config = getGlobalConfig()
const count = config.autoPermissionsNotificationCount ?? 0
if (count >= 3) return
const timer = setTimeout(
(ref, setMessages) => {
ref.current = true
saveGlobalConfig(prev => {
const prevCount = prev.autoPermissionsNotificationCount ?? 0
if (prevCount >= 3) return prev
return {
...prev,
autoPermissionsNotificationCount: prevCount + 1,
}
})
setMessages(prev => [
...prev,
createSystemMessage(AUTO_MODE_DESCRIPTION, 'warning'),
])
},
800,
safeYoloMessageShownRef,
setMessages,
)
return () => clearTimeout(timer)
}
}, [toolPermissionContext.mode, setMessages])
// If worktree creation was slow and sparse-checkout isn't configured,
// nudge the user toward settings.worktree.sparsePaths.
const worktreeTipShownRef = useRef(false)
useEffect(() => {
if (worktreeTipShownRef.current) return
const wt = getCurrentWorktreeSession()
if (!wt?.creationDurationMs || wt.usedSparsePaths) return
if (wt.creationDurationMs < 15_000) return
worktreeTipShownRef.current = true
const secs = Math.round(wt.creationDurationMs / 1000)
setMessages(prev => [
...prev,
createSystemMessage(
`Worktree creation took ${secs}s. For large repos, set \`worktree.sparsePaths\` in .claude/settings.json to check out only the directories you need — e.g. \`{"worktree": {"sparsePaths": ["src", "packages/foo"]}}\`.`,
'info',
),
])
}, [setMessages])
// Hide spinner when the only in-progress tool is Sleep
const onlySleepToolActive = useMemo(() => {
const lastAssistant = messages.findLast(m => m.type === 'assistant')
if (lastAssistant?.type !== 'assistant') return false
const inProgressToolUses = lastAssistant.message.content.filter(
b => b.type === 'tool_use' && inProgressToolUseIDs.has(b.id),
)
return (
inProgressToolUses.length > 0 &&
inProgressToolUses.every(
b => b.type === 'tool_use' && b.name === SLEEP_TOOL_NAME,
)
)
}, [messages, inProgressToolUseIDs])
const {
onBeforeQuery: mrOnBeforeQuery,
onTurnComplete: mrOnTurnComplete,
render: mrRender,
} = useMoreRight({
enabled: moreRightEnabled,
setMessages,
inputValue,
setInputValue,
setToolJSX,
})
const showSpinner =
(!toolJSX || toolJSX.showSpinner === true) &&
toolUseConfirmQueue.length === 0 &&
promptQueue.length === 0 &&
// Show spinner during input processing, API call, while teammates are running,
// or while pending task notifications are queued (prevents spinner bounce between consecutive notifications)
(isLoading ||
userInputOnProcessing ||
hasRunningTeammates ||
// Keep spinner visible while task notifications are queued for processing.
// Without this, the spinner briefly disappears between consecutive notifications
// (e.g., multiple background agents completing in rapid succession) because
// isLoading goes false momentarily between processing each one.
getCommandQueueLength() > 0) &&
// Hide spinner when waiting for leader to approve permission request
!pendingWorkerRequest &&
!onlySleepToolActive &&
// Hide spinner when streaming text is visible (the text IS the feedback),
// but keep it when isBriefOnly suppresses the streaming text display
(!visibleStreamingText || isBriefOnly)
// Check if any permission or ask question prompt is currently visible
// This is used to prevent the survey from opening while prompts are active
const hasActivePrompt =
toolUseConfirmQueue.length > 0 ||
promptQueue.length > 0 ||
sandboxPermissionRequestQueue.length > 0 ||
elicitation.queue.length > 0 ||
workerSandboxPermissions.queue.length > 0
const feedbackSurveyOriginal = useFeedbackSurvey(
messages,
isLoading,
submitCount,
'session',
hasActivePrompt,
)
const skillImprovementSurvey = useSkillImprovementSurvey(setMessages)
const showIssueFlagBanner = useIssueFlagBanner(messages, submitCount)
// Wrap feedback survey handler to trigger auto-run /issue
const feedbackSurvey = useMemo(
() => ({
...feedbackSurveyOriginal,
handleSelect: (selected: 'dismissed' | 'bad' | 'fine' | 'good') => {
// Reset the ref when a new survey response comes in
didAutoRunIssueRef.current = false
const showedTranscriptPrompt =
feedbackSurveyOriginal.handleSelect(selected)
// Auto-run /issue for "bad" if transcript prompt wasn't shown
if (
selected === 'bad' &&
!showedTranscriptPrompt &&
shouldAutoRunIssue('feedback_survey_bad')
) {
setAutoRunIssueReason('feedback_survey_bad')
didAutoRunIssueRef.current = true
}
},
}),
[feedbackSurveyOriginal],
)
// Post-compact survey: shown after compaction if feature gate is enabled
const postCompactSurvey = usePostCompactSurvey(
messages,
isLoading,
hasActivePrompt,
{ enabled: !isRemoteSession },
)
// Memory survey: shown when the assistant mentions memory and a memory file
// was read this conversation
const memorySurvey = useMemorySurvey(messages, isLoading, hasActivePrompt, {
enabled: !isRemoteSession,
})
// Frustration detection: show transcript sharing prompt after detecting frustrated messages
const frustrationDetection = useFrustrationDetection(
messages,
isLoading,
hasActivePrompt,
feedbackSurvey.state !== 'closed' ||
postCompactSurvey.state !== 'closed' ||
memorySurvey.state !== 'closed',
)
// Initialize IDE integration
useIDEIntegration({
autoConnectIdeFlag,
ideToInstallExtension,
setDynamicMcpConfig,
setShowIdeOnboarding,
setIDEInstallationState: setIDEInstallationStatus,
})
useFileHistorySnapshotInit(
initialFileHistorySnapshots,
fileHistory,
fileHistoryState =>
setAppState(prev => ({
...prev,
fileHistory: fileHistoryState,
})),
)
const resume = useCallback(
async (sessionId: UUID, log: LogOption, entrypoint: ResumeEntrypoint) => {
const resumeStart = performance.now()
try {
// Deserialize messages to properly clean up the conversation
// This filters unresolved tool uses and adds a synthetic assistant message if needed
const messages = deserializeMessages(log.messages)
// Match coordinator/normal mode to the resumed session
if (feature('COORDINATOR_MODE')) {
/* eslint-disable @typescript-eslint/no-require-imports */
const coordinatorModule =
require('../coordinator/coordinatorMode.js') as typeof import('../coordinator/coordinatorMode.js')
/* eslint-enable @typescript-eslint/no-require-imports */
const warning = coordinatorModule.matchSessionMode(log.mode)
if (warning) {
// Re-derive agent definitions after mode switch so built-in agents
// reflect the new coordinator/normal mode
/* eslint-disable @typescript-eslint/no-require-imports */
const {
getAgentDefinitionsWithOverrides,
getActiveAgentsFromList,
} =
require('../tools/AgentTool/loadAgentsDir.js') as typeof import('../tools/AgentTool/loadAgentsDir.js')
/* eslint-enable @typescript-eslint/no-require-imports */
getAgentDefinitionsWithOverrides.cache.clear?.()
const freshAgentDefs = await getAgentDefinitionsWithOverrides(
getOriginalCwd(),
)
setAppState(prev => ({
...prev,
agentDefinitions: {
...freshAgentDefs,
allAgents: freshAgentDefs.allAgents,
activeAgents: getActiveAgentsFromList(freshAgentDefs.allAgents),
},
}))
messages.push(createSystemMessage(warning, 'warning'))
}
}
// Fire SessionEnd hooks for the current session before starting the
// resumed one, mirroring the /clear flow in conversation.ts.
const sessionEndTimeoutMs = getSessionEndHookTimeoutMs()
await executeSessionEndHooks('resume', {
getAppState: () => store.getState(),
setAppState,
signal: AbortSignal.timeout(sessionEndTimeoutMs),
timeoutMs: sessionEndTimeoutMs,
})
// Process session start hooks for resume
const hookMessages = await processSessionStartHooks('resume', {
sessionId,
agentType: mainThreadAgentDefinition?.agentType,
model: mainLoopModel,
})
// Append hook messages to the conversation
messages.push(...hookMessages)
// For forks, generate a new plan slug and copy the plan content so the
// original and forked sessions don't clobber each other's plan files.
// For regular resumes, reuse the original session's plan slug.
if (entrypoint === 'fork') {
void copyPlanForFork(log, asSessionId(sessionId))
} else {
void copyPlanForResume(log, asSessionId(sessionId))
}
// Restore file history and attribution state from the resumed conversation
restoreSessionStateFromLog(log, setAppState)
if (log.fileHistorySnapshots) {
void copyFileHistoryForResume(log)
}
// Restore agent setting from the resumed conversation
// Always reset to the new session's values (or clear if none),
// matching the standaloneAgentContext pattern below
const { agentDefinition: restoredAgent } = restoreAgentFromSession(
log.agentSetting,
initialMainThreadAgentDefinition,
agentDefinitions,
)
setMainThreadAgentDefinition(restoredAgent)
setAppState(prev => ({ ...prev, agent: restoredAgent?.agentType }))
// Restore standalone agent context from the resumed conversation
// Always reset to the new session's values (or clear if none)
setAppState(prev => ({
...prev,
standaloneAgentContext: computeStandaloneAgentContext(
log.agentName,
log.agentColor,
),
}))
void updateSessionName(log.agentName)
// Restore read file state from the message history
restoreReadFileState(messages, log.projectPath ?? getOriginalCwd())
// Clear any active loading state (no queryId since we're not in a query)
resetLoadingState()
setAbortController(null)
setConversationId(sessionId)
// Get target session's costs BEFORE saving current session
// (saveCurrentSessionCosts overwrites the config, so we need to read first)
const targetSessionCosts = getStoredSessionCosts(sessionId)
// Save current session's costs before switching to avoid losing accumulated costs
saveCurrentSessionCosts()
// Reset cost state for clean slate before restoring target session
resetCostState()
// Switch session (id + project dir atomically). fullPath may point to
// a different project (cross-worktree, /branch); null derives from
// current originalCwd.
switchSession(
asSessionId(sessionId),
log.fullPath ? dirname(log.fullPath) : null,
)
// Rename asciicast recording to match the resumed session ID
const { renameRecordingForSession } = await import(
'../utils/asciicast.js'
)
await renameRecordingForSession()
await resetSessionFilePointer()
// Clear then restore session metadata so it's re-appended on exit via
// reAppendSessionMetadata. clearSessionMetadata must be called first:
// restoreSessionMetadata only sets-if-truthy, so without the clear,
// a session without an agent name would inherit the previous session's
// cached name and write it to the wrong transcript on first message.
clearSessionMetadata()
restoreSessionMetadata(log)
// Resumed sessions shouldn't re-title from mid-conversation context
// (same reasoning as the useRef seed), and the previous session's
// auto-generated title shouldn't carry over.
titleGenerationAttemptedRef.current = true
setAutoGeneratedTitle(undefined)
// Exit any worktree a prior /resume entered, then cd into the one
// this session was in. Without the exit, resuming from worktree B
// to non-worktree C leaves cwd/currentWorktreeSession stale;
// resuming B→C where C is also a worktree fails entirely
// (getCurrentWorktreeSession guard blocks the switch).
//
// Skipped for /branch: forkLog doesn't carry worktreeSession, so
// this would kick the user out of a worktree they're still working
// in. Same fork skip as processResumedConversation for the adopt —
// fork materializes its own file via recordTranscript on REPL mount.
if (entrypoint !== 'fork') {
exitRestoredWorktree()
restoreWorktreeForResume(log.worktreeSession)
adoptResumedSessionFile()
void restoreRemoteAgentTasks({
abortController: new AbortController(),
getAppState: () => store.getState(),
setAppState,
})
} else {
// Fork: same re-persist as /clear (conversation.ts). The clear
// above wiped currentSessionWorktree, forkLog doesn't carry it,
// and the process is still in the same worktree.
const ws = getCurrentWorktreeSession()
if (ws) saveWorktreeState(ws)
}
// Persist the current mode so future resumes know what mode this session was in
if (feature('COORDINATOR_MODE')) {
/* eslint-disable @typescript-eslint/no-require-imports */
const { saveMode } = require('../utils/sessionStorage.js')
const { isCoordinatorMode } =
require('../coordinator/coordinatorMode.js') as typeof import('../coordinator/coordinatorMode.js')
/* eslint-enable @typescript-eslint/no-require-imports */
saveMode(isCoordinatorMode() ? 'coordinator' : 'normal')
}
// Restore target session's costs from the data we read earlier
if (targetSessionCosts) {
setCostStateForRestore(targetSessionCosts)
}
// Reconstruct replacement state for the resumed session. Runs after
// setSessionId so any NEW replacements post-resume write to the
// resumed session's tool-results dir. Gated on ref.current: the
// initial mount already read the feature flag, so we don't re-read
// it here (mid-session flag flips stay unobservable in both
// directions).
//
// Skipped for in-session /branch: the existing ref is already correct
// (branch preserves tool_use_ids), so there's no need to reconstruct.
// createFork() does write content-replacement entries to the forked
// JSONL with the fork's sessionId, so `claude -r {forkId}` also works.
if (contentReplacementStateRef.current && entrypoint !== 'fork') {
contentReplacementStateRef.current =
reconstructContentReplacementState(
messages,
log.contentReplacements ?? [],
)
}
// Reset messages to the provided initial messages
// Use a callback to ensure we're not dependent on stale state
setMessages(() => messages)
// Clear any active tool JSX
setToolJSX(null)
// Clear input to ensure no residual state
setInputValue('')
logEvent('tengu_session_resumed', {
entrypoint:
entrypoint as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
success: true,
resume_duration_ms: Math.round(performance.now() - resumeStart),
})
} catch (error) {
logEvent('tengu_session_resumed', {
entrypoint:
entrypoint as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
success: false,
})
throw error
}
},
[resetLoadingState, setAppState],
)
// Lazy init: useRef(createX()) would call createX on every render and
// discard the result. LRUCache construction inside FileStateCache is
// expensive (~170ms), so we use useState's lazy initializer to create
// it exactly once, then feed that stable reference into useRef.
const [initialReadFileState] = useState(() =>
createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE),
)
const readFileState = useRef(initialReadFileState)
const bashTools = useRef(new Set<string>())
const bashToolsProcessedIdx = useRef(0)
// Session-scoped skill discovery tracking (feeds was_discovered on
// tengu_skill_tool_invocation). Must persist across getToolUseContext
// rebuilds within a session: turn-0 discovery writes via processUserInput
// before onQuery builds its own context, and discovery on turn N must
// still attribute a SkillTool call on turn N+k. Cleared in clearConversation.
const discoveredSkillNamesRef = useRef(new Set<string>())
// Session-level dedup for nested_memory CLAUDE.md attachments.
// readFileState is a 100-entry LRU; once it evicts a CLAUDE.md path,
// the next discovery cycle re-injects it. Cleared in clearConversation.
const loadedNestedMemoryPathsRef = useRef(new Set<string>())
// Helper to restore read file state from messages (used for resume flows)
// This allows Claude to edit files that were read in previous sessions
const restoreReadFileState = useCallback(
(messages: MessageType[], cwd: string) => {
const extracted = extractReadFilesFromMessages(
messages,
cwd,
READ_FILE_STATE_CACHE_SIZE,
)
readFileState.current = mergeFileStateCaches(
readFileState.current,
extracted,
)
for (const tool of extractBashToolsFromMessages(messages)) {
bashTools.current.add(tool)
}
},
[],
)
// Extract read file state from initialMessages on mount
// This handles CLI flag resume (--resume-session) and ResumeConversation screen
// where messages are passed as props rather than through the resume callback
useEffect(() => {
if (initialMessages && initialMessages.length > 0) {
restoreReadFileState(initialMessages, getOriginalCwd())
void restoreRemoteAgentTasks({
abortController: new AbortController(),
getAppState: () => store.getState(),
setAppState,
})
}
// Only run on mount - initialMessages shouldn't change during component lifetime
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const { status: apiKeyStatus, reverify } = useApiKeyVerification()
// Auto-run /issue state
const [autoRunIssueReason, setAutoRunIssueReason] =
useState<AutoRunIssueReason | null>(null)
// Ref to track if autoRunIssue was triggered this survey cycle,
// so we can suppress the [1] follow-up prompt even after
// autoRunIssueReason is cleared.
const didAutoRunIssueRef = useRef(false)
// State for exit feedback flow
const [exitFlow, setExitFlow] = useState<React.ReactNode>(null)
const [isExiting, setIsExiting] = useState(false)
// Calculate if cost dialog should be shown
const showingCostDialog = !isLoading && showCostDialog
// Determine which dialog should have focus (if any)
// Permission and interactive dialogs can show even when toolJSX is set,
// as long as shouldContinueAnimation is true. This prevents deadlocks when
// agents set background hints while waiting for user interaction.
function getFocusedInputDialog():
| 'message-selector'
| 'sandbox-permission'
| 'tool-permission'
| 'prompt'
| 'question'
| 'worker-sandbox-permission'
| 'elicitation'
| 'cost'
| 'idle-return'
| 'init-onboarding'
| 'ide-onboarding'
| 'model-switch'
| 'undercover-callout'
| 'effort-callout'
| 'remote-callout'
| 'lsp-recommendation'
| 'plugin-hint'
| 'desktop-upsell'
| 'ultraplan-choice'
| 'ultraplan-launch'
| undefined {
// Exit states always take precedence
if (isExiting || exitFlow) return undefined
// High priority dialogs (always show regardless of typing)
if (isMessageSelectorVisible) return 'message-selector'
// Suppress interrupt dialogs while user is actively typing
if (isPromptInputActive) return undefined
if (sandboxPermissionRequestQueue[0]) return 'sandbox-permission'
// Permission/interactive dialogs (show unless blocked by toolJSX)
const allowDialogsWithAnimation =
!toolJSX || toolJSX.shouldContinueAnimation
if (allowDialogsWithAnimation && toolUseConfirmQueue[0])
return 'tool-permission'
if (allowDialogsWithAnimation && promptQueue[0]) return 'prompt'
if (allowDialogsWithAnimation && questionRequest) return 'question'
// Worker sandbox permission prompts (network access) from swarm workers
if (allowDialogsWithAnimation && workerSandboxPermissions.queue[0])
return 'worker-sandbox-permission'
if (allowDialogsWithAnimation && elicitation.queue[0]) return 'elicitation'
if (allowDialogsWithAnimation && showingCostDialog) return 'cost'
if (allowDialogsWithAnimation && idleReturnPending) return 'idle-return'
if (
feature('ULTRAPLAN') &&
allowDialogsWithAnimation &&
!isLoading &&
ultraplanPendingChoice
)
return 'ultraplan-choice'
if (
feature('ULTRAPLAN') &&
allowDialogsWithAnimation &&
!isLoading &&
ultraplanLaunchPending
)
return 'ultraplan-launch'
// Onboarding dialogs (special conditions)
if (allowDialogsWithAnimation && showIdeOnboarding) return 'ide-onboarding'
// Model switch callout (ant-only, eliminated from external builds)
if (
"external" === 'ant' &&
allowDialogsWithAnimation &&
showModelSwitchCallout
)
return 'model-switch'
// Undercover auto-enable explainer (ant-only, eliminated from external builds)
if (
"external" === 'ant' &&
allowDialogsWithAnimation &&
showUndercoverCallout
)
return 'undercover-callout'
// Effort callout (shown once for Opus 4.6 users when effort is enabled)
if (allowDialogsWithAnimation && showEffortCallout) return 'effort-callout'
// Remote callout (shown once before first bridge enable)
if (allowDialogsWithAnimation && showRemoteCallout) return 'remote-callout'
// LSP plugin recommendation (lowest priority - non-blocking suggestion)
if (allowDialogsWithAnimation && lspRecommendation)
return 'lsp-recommendation'
// Plugin hint from CLI/SDK stderr (same priority band as LSP rec)
if (allowDialogsWithAnimation && hintRecommendation) return 'plugin-hint'
// Desktop app upsell (max 3 launches, lowest priority)
if (allowDialogsWithAnimation && showDesktopUpsellStartup)
return 'desktop-upsell'
return undefined
}
const focusedInputDialog = getFocusedInputDialog()
// True when permission prompts exist but are hidden because the user is typing
const hasSuppressedDialogs =
isPromptInputActive &&
(sandboxPermissionRequestQueue[0] ||
toolUseConfirmQueue[0] ||
promptQueue[0] ||
workerSandboxPermissions.queue[0] ||
elicitation.queue[0] ||
showingCostDialog)
// Keep ref in sync so timer callbacks can read the current value
focusedInputDialogRef.current = focusedInputDialog
// Immediately capture pause/resume when focusedInputDialog changes
// This ensures accurate timing even under high system load, rather than
// relying on the 100ms polling interval to detect state changes
useEffect(() => {
if (!isLoading) return
const isPaused =
focusedInputDialog === 'tool-permission' || focusedInputDialog === 'question'
const now = Date.now()
if (isPaused && pauseStartTimeRef.current === null) {
// Just entered pause state - record the exact moment
pauseStartTimeRef.current = now
} else if (!isPaused && pauseStartTimeRef.current !== null) {
// Just exited pause state - accumulate paused time immediately
totalPausedMsRef.current += now - pauseStartTimeRef.current
pauseStartTimeRef.current = null
}
}, [focusedInputDialog, isLoading])
// Re-pin scroll to bottom whenever the permission overlay appears or
// dismisses. Overlay now renders below messages inside the same
// ScrollBox (no remount), so we need an explicit scrollToBottom for:
// - appear: user may have been scrolled up (sticky broken) — the
// dialog is blocking and must be visible
// - dismiss: user may have scrolled up to read context during the
// overlay, and onScroll was suppressed so the pill state is stale
// useLayoutEffect so the re-pin commits before the Ink frame renders —
// no 1-frame flash of the wrong scroll position.
const prevDialogRef = useRef(focusedInputDialog)
useLayoutEffect(() => {
const was =
prevDialogRef.current === 'tool-permission' ||
prevDialogRef.current === 'question'
const now =
focusedInputDialog === 'tool-permission' ||
focusedInputDialog === 'question'
if (was !== now) repinScroll()
prevDialogRef.current = focusedInputDialog
}, [focusedInputDialog, repinScroll])
function onCancel() {
if (focusedInputDialog === 'elicitation') {
// Elicitation dialog handles its own Escape, and closing it shouldn't affect any loading state.
return
}
logForDebugging(
`[onCancel] focusedInputDialog=${focusedInputDialog} streamMode=${streamMode}`,
)
// Pause proactive mode so the user gets control back.
// It will resume when they submit their next input (see onSubmit).
if (feature('PROACTIVE') || feature('KAIROS')) {
proactiveModule?.pauseProactive()
}
queryGuard.forceEnd()
skipIdleCheckRef.current = false
// Preserve partially-streamed text so the user can read what was
// generated before pressing Esc. Pushed before resetLoadingState clears
// streamingText, and before query.ts yields the async interrupt marker,
// giving final order [user, partial-assistant, [Request interrupted by user]].
if (streamingText?.trim()) {
setMessages(prev => [
...prev,
createAssistantMessage({ content: streamingText }),
])
}
resetLoadingState()
// Clear any active token budget so the backstop doesn't fire on
// a stale budget if the query generator hasn't exited yet.
if (feature('TOKEN_BUDGET')) {
snapshotOutputTokensForTurn(null)
}
if (focusedInputDialog === 'tool-permission') {
// Tool use confirm handles the abort signal itself
toolUseConfirmQueue[0]?.onAbort()
setToolUseConfirmQueue([])
} else if (focusedInputDialog === 'prompt') {
// Reject all pending prompts and clear the queue
for (const item of promptQueue) {
item.reject(new Error('Prompt cancelled by user'))
}
setPromptQueue([])
abortController?.abort('user-cancel')
} else if (activeRemote.isRemoteMode) {
// Remote mode: send interrupt signal to CCR
activeRemote.cancelRequest()
} else {
abortController?.abort('user-cancel')
}
// Clear the controller so subsequent Escape presses don't see a stale
// aborted signal. Without this, canCancelRunningTask is false (signal
// defined but .aborted === true), so isActive becomes false if no other
// activating conditions hold — leaving the Escape keybinding inactive.
setAbortController(null)
// forceEnd() skips the finally path — fire directly (aborted=true).
void mrOnTurnComplete(messagesRef.current, true)
}
// Function to handle queued command when canceling a permission request
const handleQueuedCommandOnCancel = useCallback(() => {
const result = popAllEditable(inputValue, 0)
if (!result) return
setInputValue(result.text)
setInputMode('prompt')
// Restore images from queued commands to pastedContents
if (result.images.length > 0) {
setPastedContents(prev => {
const newContents = { ...prev }
for (const image of result.images) {
newContents[image.id] = image
}
return newContents
})
}
}, [setInputValue, setInputMode, inputValue, setPastedContents])
// CancelRequestHandler props - rendered inside KeybindingSetup
const cancelRequestProps = {
setToolUseConfirmQueue,
onCancel,
onAgentsKilled: () =>
setMessages(prev => [...prev, createAgentsKilledMessage()]),
isMessageSelectorVisible: isMessageSelectorVisible || !!showBashesDialog,
screen,
abortSignal: abortController?.signal,
popCommandFromQueue: handleQueuedCommandOnCancel,
vimMode,
isLocalJSXCommand: toolJSX?.isLocalJSXCommand,
isSearchingHistory,
isHelpOpen,
inputMode,
inputValue,
streamMode,
}
useEffect(() => {
const totalCost = getTotalCost()
if (totalCost >= 5 /* $5 */ && !showCostDialog && !haveShownCostDialog) {
logEvent('tengu_cost_threshold_reached', {})
// Mark as shown even if the dialog won't render (no console billing
// access). Otherwise this effect re-fires on every message change for
// the rest of the session — 200k+ spurious events observed.
setHaveShownCostDialog(true)
if (hasConsoleBillingAccess()) {
setShowCostDialog(true)
}
}
}, [messages, showCostDialog, haveShownCostDialog])
const sandboxAskCallback: SandboxAskCallback = useCallback(
async (hostPattern: NetworkHostPattern) => {
// If running as a swarm worker, forward the request to the leader via mailbox
if (isAgentSwarmsEnabled() && isSwarmWorker()) {
const requestId = generateSandboxRequestId()
// Send the request to the leader via mailbox
const sent = await sendSandboxPermissionRequestViaMailbox(
hostPattern.host,
requestId,
)
return new Promise(resolveShouldAllowHost => {
if (!sent) {
// If we couldn't send via mailbox, fall back to local handling
setSandboxPermissionRequestQueue(prev => [
...prev,
{
hostPattern,
resolvePromise: resolveShouldAllowHost,
},
])
return
}
// Register the callback for when the leader responds
registerSandboxPermissionCallback({
requestId,
host: hostPattern.host,
resolve: resolveShouldAllowHost,
})
// Update AppState to show pending indicator
setAppState(prev => ({
...prev,
pendingSandboxRequest: {
requestId,
host: hostPattern.host,
},
}))
})
}
// Normal flow for non-workers: show local UI and optionally race
// against the REPL bridge (Remote Control) if connected.
return new Promise(resolveShouldAllowHost => {
let resolved = false
function resolveOnce(allow: boolean): void {
if (resolved) return
resolved = true
resolveShouldAllowHost(allow)
}
// Queue the local sandbox permission dialog
setSandboxPermissionRequestQueue(prev => [
...prev,
{
hostPattern,
resolvePromise: resolveOnce,
},
])
// When the REPL bridge is connected, also forward the sandbox
// permission request as a can_use_tool control_request so the
// remote user (e.g. on claude.ai) can approve it too.
if (feature('BRIDGE_MODE')) {
const bridgeCallbacks = store.getState().replBridgePermissionCallbacks
if (bridgeCallbacks) {
const bridgeRequestId = randomUUID()
bridgeCallbacks.sendRequest(
bridgeRequestId,
SANDBOX_NETWORK_ACCESS_TOOL_NAME,
{ host: hostPattern.host },
randomUUID(),
`Allow network connection to ${hostPattern.host}?`,
)
const unsubscribe = bridgeCallbacks.onResponse(
bridgeRequestId,
response => {
unsubscribe()
const allow = response.behavior === 'allow'
// Resolve ALL pending requests for the same host, not just
// this one — mirrors the local dialog handler pattern.
setSandboxPermissionRequestQueue(queue => {
queue
.filter(item => item.hostPattern.host === hostPattern.host)
.forEach(item => item.resolvePromise(allow))
return queue.filter(
item => item.hostPattern.host !== hostPattern.host,
)
})
// Clean up all sibling bridge subscriptions for this host
// (other concurrent same-host requests) before deleting.
const siblingCleanups = sandboxBridgeCleanupRef.current.get(
hostPattern.host,
)
if (siblingCleanups) {
for (const fn of siblingCleanups) {
fn()
}
sandboxBridgeCleanupRef.current.delete(hostPattern.host)
}
},
)
// Register cleanup so the local dialog handler can cancel
// the remote prompt and unsubscribe when the local user
// responds first.
const cleanup = () => {
unsubscribe()
bridgeCallbacks.cancelRequest(bridgeRequestId)
}
const existing =
sandboxBridgeCleanupRef.current.get(hostPattern.host) ?? []
existing.push(cleanup)
sandboxBridgeCleanupRef.current.set(hostPattern.host, existing)
}
}
})
},
[setAppState, store],
)
// #34044: if user explicitly set sandbox.enabled=true but deps are missing,
// isSandboxingEnabled() returns false silently. Surface the reason once at
// mount so users know their security config isn't being enforced. Full
// reason goes to debug log; notification points to /sandbox for details.
// addNotification is stable (useCallback) so the effect fires once.
useEffect(() => {
const reason = SandboxManager.getSandboxUnavailableReason()
if (!reason) return
if (SandboxManager.isSandboxRequired()) {
process.stderr.write(
`\nError: sandbox required but unavailable: ${reason}\n` +
` sandbox.failIfUnavailable is set — refusing to start without a working sandbox.\n\n`,
)
gracefulShutdownSync(1, 'other')
return
}
logForDebugging(`sandbox disabled: ${reason}`, { level: 'warn' })
addNotification({
key: 'sandbox-unavailable',
jsx: (
<>
<Text color="warning">sandbox disabled</Text>
<Text dimColor> · /sandbox</Text>
</>
),
priority: 'medium',
})
}, [addNotification])
if (SandboxManager.isSandboxingEnabled()) {
// If sandboxing is enabled (setting.sandbox is defined, initialise the manager)
SandboxManager.initialize(sandboxAskCallback).catch(err => {
// Initialization/validation failed - display error and exit
process.stderr.write(`\n❌ Sandbox Error: ${errorMessage(err)}\n`)
gracefulShutdownSync(1, 'other')
})
}
const setToolPermissionContext = useCallback(
(context: ToolPermissionContext, options?: { preserveMode?: boolean }) => {
setAppState(prev => ({
...prev,
toolPermissionContext: {
...context,
// Preserve the coordinator's mode only when explicitly requested.
// Workers' getAppState() returns a transformed context with mode
// 'acceptEdits' that must not leak into the coordinator's actual
// state via permission-rule updates — those call sites pass
// { preserveMode: true }. User-initiated mode changes (e.g.,
// selecting "allow all edits") must NOT be overridden.
mode: options?.preserveMode
? prev.toolPermissionContext.mode
: context.mode,
},
}))
// When permission context changes, recheck all queued items
// This handles the case where approving item1 with "don't ask again"
// should auto-approve other queued items that now match the updated rules
setImmediate(setToolUseConfirmQueue => {
// Use setToolUseConfirmQueue callback to get current queue state
// instead of capturing it in the closure, to avoid stale closure issues
setToolUseConfirmQueue(currentQueue => {
currentQueue.forEach(item => {
void item.recheckPermission()
})
return currentQueue
})
}, setToolUseConfirmQueue)
},
[setAppState, setToolUseConfirmQueue],
)
// Register the leader's setToolPermissionContext for in-process teammates
useEffect(() => {
registerLeaderSetToolPermissionContext(setToolPermissionContext)
return () => unregisterLeaderSetToolPermissionContext()
}, [setToolPermissionContext])
const canUseTool = useCanUseTool(
setToolUseConfirmQueue,
setToolPermissionContext,
)
const requestPrompt = useCallback(
(title: string, toolInputSummary?: string | null) =>
(request: PromptRequest): Promise<PromptResponse> =>
new Promise<PromptResponse>((resolve, reject) => {
setPromptQueue(prev => [
...prev,
{ request, title, toolInputSummary, resolve, reject },
])
}),
[],
)
const getToolUseContext = useCallback(
(
messages: MessageType[],
newMessages: MessageType[],
abortController: AbortController,
mainLoopModel: string,
): ProcessUserInputContext => {
// Read mutable values fresh from the store rather than closure-capturing
// useAppState() snapshots. Same values today (closure is refreshed by the
// render between turns); decouples freshness from React's render cycle for
// a future headless conversation loop. Same pattern refreshTools() uses.
const s = store.getState()
// Compute tools fresh from store.getState() rather than the closure-
// captured `tools`. useManageMCPConnections populates appState.mcp
// async as servers connect — the store may have newer MCP state than
// the closure captured at render time. Also doubles as refreshTools()
// for mid-query tool list updates.
const computeTools = () => {
const state = store.getState()
const assembled = assembleToolPool(
state.toolPermissionContext,
state.mcp.tools,
)
const merged = mergeAndFilterTools(
combinedInitialTools,
assembled,
state.toolPermissionContext.mode,
)
if (!mainThreadAgentDefinition) return merged
return resolveAgentTools(mainThreadAgentDefinition, merged, false, true)
.resolvedTools
}
return {
abortController,
options: {
commands,
tools: computeTools(),
debug,
verbose: s.verbose,
mainLoopModel,
thinkingConfig:
s.thinkingEnabled !== false ? thinkingConfig : { type: 'disabled' },
// Merge fresh from store rather than closing over useMergedClients'
// memoized output. initialMcpClients is a prop (session-constant).
mcpClients: mergeClients(initialMcpClients, s.mcp.clients),
mcpResources: s.mcp.resources,
ideInstallationStatus: ideInstallationStatus,
isNonInteractiveSession: false,
dynamicMcpConfig,
theme,
agentDefinitions: allowedAgentTypes
? { ...s.agentDefinitions, allowedAgentTypes }
: s.agentDefinitions,
customSystemPrompt,
appendSystemPrompt,
refreshTools: computeTools,
},
getAppState: () => store.getState(),
setAppState,
messages,
setMessages,
updateFileHistoryState(
updater: (prev: FileHistoryState) => FileHistoryState,
) {
// Perf: skip the setState when the updater returns the same reference
// (e.g. fileHistoryTrackEdit returns `state` when the file is already
// tracked). Otherwise every no-op call would notify all store listeners.
setAppState(prev => {
const updated = updater(prev.fileHistory)
if (updated === prev.fileHistory) return prev
return { ...prev, fileHistory: updated }
})
},
updateAttributionState(
updater: (prev: AttributionState) => AttributionState,
) {
setAppState(prev => {
const updated = updater(prev.attribution)
if (updated === prev.attribution) return prev
return { ...prev, attribution: updated }
})
},
openMessageSelector: () => {
if (!disabled) {
setIsMessageSelectorVisible(true)
}
},
onChangeAPIKey: reverify,
readFileState: readFileState.current,
setToolJSX,
addNotification,
appendSystemMessage: msg => setMessages(prev => [...prev, msg]),
sendOSNotification: opts => {
void sendNotification(opts, terminal)
},
onChangeDynamicMcpConfig,
onInstallIDEExtension: setIDEToInstallExtension,
nestedMemoryAttachmentTriggers: new Set<string>(),
loadedNestedMemoryPaths: loadedNestedMemoryPathsRef.current,
dynamicSkillDirTriggers: new Set<string>(),
discoveredSkillNames: discoveredSkillNamesRef.current,
setResponseLength,
pushApiMetricsEntry:
"external" === 'ant'
? (ttftMs: number) => {
const now = Date.now()
const baseline = responseLengthRef.current
apiMetricsRef.current.push({
ttftMs,
firstTokenTime: now,
lastTokenTime: now,
responseLengthBaseline: baseline,
endResponseLength: baseline,
})
}
: undefined,
setStreamMode,
onCompactProgress: event => {
switch (event.type) {
case 'hooks_start':
setSpinnerColor('claudeBlue_FOR_SYSTEM_SPINNER')
setSpinnerShimmerColor('claudeBlueShimmer_FOR_SYSTEM_SPINNER')
setSpinnerMessage(
event.hookType === 'pre_compact'
? 'Running PreCompact hooks\u2026'
: event.hookType === 'post_compact'
? 'Running PostCompact hooks\u2026'
: 'Running SessionStart hooks\u2026',
)
break
case 'compact_start':
setSpinnerMessage('Compacting conversation')
break
case 'compact_end':
setSpinnerMessage(null)
setSpinnerColor(null)
setSpinnerShimmerColor(null)
break
}
},
setInProgressToolUseIDs,
setHasInterruptibleToolInProgress: (v: boolean) => {
hasInterruptibleToolInProgressRef.current = v
},
resume,
setConversationId,
requestPrompt: feature('HOOK_PROMPTS') ? requestPrompt : undefined,
contentReplacementState: contentReplacementStateRef.current,
}
},
[
commands,
combinedInitialTools,
mainThreadAgentDefinition,
debug,
initialMcpClients,
ideInstallationStatus,
dynamicMcpConfig,
theme,
allowedAgentTypes,
store,
setAppState,
reverify,
addNotification,
setMessages,
onChangeDynamicMcpConfig,
resume,
requestPrompt,
disabled,
customSystemPrompt,
appendSystemPrompt,
setConversationId,
],
)
// Session backgrounding (Ctrl+B to background/foreground)
const handleBackgroundQuery = useCallback(() => {
// Stop the foreground query so the background one takes over
abortController?.abort('background')
// Aborting subagents may produce task-completed notifications.
// Clear task notifications so the queue processor doesn't immediately
// start a new foreground query; forward them to the background session.
const removedNotifications = removeByFilter(
cmd => cmd.mode === 'task-notification',
)
void (async () => {
const toolUseContext = getToolUseContext(
messagesRef.current,
[],
new AbortController(),
mainLoopModel,
)
const [defaultSystemPrompt, userContext, systemContext] =
await Promise.all([
getSystemPrompt(
toolUseContext.options.tools,
mainLoopModel,
Array.from(
toolPermissionContext.additionalWorkingDirectories.keys(),
),
toolUseContext.options.mcpClients,
),
getUserContext(),
getSystemContext(),
])
const systemPrompt = buildEffectiveSystemPrompt({
mainThreadAgentDefinition,
toolUseContext,
customSystemPrompt,
defaultSystemPrompt,
appendSystemPrompt,
})
toolUseContext.renderedSystemPrompt = systemPrompt
const notificationAttachments = await getQueuedCommandAttachments(
removedNotifications,
).catch(() => [])
const notificationMessages = notificationAttachments.map(
createAttachmentMessage,
)
// Deduplicate: if the query loop already yielded a notification into
// messagesRef before we removed it from the queue, skip duplicates.
// We use prompt text for dedup because source_uuid is not set on
// task-notification QueuedCommands (enqueuePendingNotification callers
// don't pass uuid), so it would always be undefined.
const existingPrompts = new Set<string>()
for (const m of messagesRef.current) {
if (
m.type === 'attachment' &&
m.attachment.type === 'queued_command' &&
m.attachment.commandMode === 'task-notification' &&
typeof m.attachment.prompt === 'string'
) {
existingPrompts.add(m.attachment.prompt)
}
}
const uniqueNotifications = notificationMessages.filter(
m =>
m.attachment.type === 'queued_command' &&
(typeof m.attachment.prompt !== 'string' ||
!existingPrompts.has(m.attachment.prompt)),
)
startBackgroundSession({
messages: [...messagesRef.current, ...uniqueNotifications],
queryParams: {
systemPrompt,
userContext,
systemContext,
canUseTool,
toolUseContext,
querySource: getQuerySourceForREPL(),
},
description: terminalTitle,
setAppState,
agentDefinition: mainThreadAgentDefinition,
})
})()
}, [
abortController,
mainLoopModel,
toolPermissionContext,
mainThreadAgentDefinition,
getToolUseContext,
customSystemPrompt,
appendSystemPrompt,
canUseTool,
setAppState,
])
const { handleBackgroundSession } = useSessionBackgrounding({
setMessages,
setIsLoading: setIsExternalLoading,
resetLoadingState,
setAbortController,
onBackgroundQuery: handleBackgroundQuery,
})
const onQueryEvent = useCallback(
(event: Parameters<typeof handleMessageFromStream>[0]) => {
handleMessageFromStream(
event,
newMessage => {
if (isCompactBoundaryMessage(newMessage)) {
// Fullscreen: keep pre-compact messages for scrollback. query.ts
// slices at the boundary for API calls, Messages.tsx skips the
// boundary filter in fullscreen, and useLogMessages treats this
// as an incremental append (first uuid unchanged). Cap at one
// compact-interval of scrollback — normalizeMessages/applyGrouping
// are O(n) per render, so drop everything before the previous
// boundary to keep n bounded across multi-day sessions.
if (isFullscreenEnvEnabled()) {
setMessages(old => [
...getMessagesAfterCompactBoundary(old, {
includeSnipped: true,
}),
newMessage,
])
} else {
setMessages(() => [newMessage])
}
// Bump conversationId so Messages.tsx row keys change and
// stale memoized rows remount with post-compact content.
setConversationId(randomUUID())
// Compaction succeeded — clear the context-blocked flag so ticks resume
if (feature('PROACTIVE') || feature('KAIROS')) {
proactiveModule?.setContextBlocked(false)
}
} else if (
newMessage.type === 'progress' &&
isEphemeralToolProgress(newMessage.data.type)
) {
// Replace the previous ephemeral progress tick for the same tool
// call instead of appending. Sleep/Bash emit a tick per second and
// only the last one is rendered; appending blows up the messages
// array (13k+ observed) and the transcript (120MB of sleep_progress
// lines). useLogMessages tracks length, so same-length replacement
// also skips the transcript write.
// agent_progress / hook_progress / skill_progress are NOT ephemeral
// — each carries distinct state the UI needs (e.g. subagent tool
// history). Replacing those leaves the AgentTool UI stuck at
// "Initializing…" because it renders the full progress trail.
setMessages(oldMessages => {
const last = oldMessages.at(-1)
if (
last?.type === 'progress' &&
last.parentToolUseID === newMessage.parentToolUseID &&
last.data.type === newMessage.data.type
) {
const copy = oldMessages.slice()
copy[copy.length - 1] = newMessage
return copy
}
return [...oldMessages, newMessage]
})
} else {
setMessages(oldMessages => [...oldMessages, newMessage])
}
// Block ticks on API errors to prevent tick → error → tick
// runaway loops (e.g., auth failure, rate limit, blocking limit).
// Cleared on compact boundary (above) or successful response (below).
if (feature('PROACTIVE') || feature('KAIROS')) {
if (
newMessage.type === 'assistant' &&
'isApiErrorMessage' in newMessage &&
newMessage.isApiErrorMessage
) {
proactiveModule?.setContextBlocked(true)
} else if (newMessage.type === 'assistant') {
proactiveModule?.setContextBlocked(false)
}
}
},
newContent => {
// setResponseLength handles updating both responseLengthRef (for
// spinner animation) and apiMetricsRef (endResponseLength/lastTokenTime
// for OTPS). No separate metrics update needed here.
setResponseLength(length => length + newContent.length)
},
setStreamMode,
setStreamingToolUses,
tombstonedMessage => {
setMessages(oldMessages =>
oldMessages.filter(m => m !== tombstonedMessage),
)
void removeTranscriptMessage(tombstonedMessage.uuid)
},
setStreamingThinking,
metrics => {
const now = Date.now()
const baseline = responseLengthRef.current
apiMetricsRef.current.push({
...metrics,
firstTokenTime: now,
lastTokenTime: now,
responseLengthBaseline: baseline,
endResponseLength: baseline,
})
},
onStreamingText,
)
},
[
setMessages,
setResponseLength,
setStreamMode,
setStreamingToolUses,
setStreamingThinking,
onStreamingText,
],
)
const onQueryImpl = useCallback(
async (
messagesIncludingNewMessages: MessageType[],
newMessages: MessageType[],
abortController: AbortController,
shouldQuery: boolean,
additionalAllowedTools: string[],
mainLoopModelParam: string,
effort?: EffortValue,
overrideSystemPrompt?: string,
) => {
// Prepare IDE integration for new prompt. Read mcpClients fresh from
// store — useManageMCPConnections may have populated it since the
// render that captured this closure (same pattern as computeTools).
if (shouldQuery) {
const freshClients = mergeClients(
initialMcpClients,
store.getState().mcp.clients,
)
void diagnosticTracker.handleQueryStart(freshClients)
const ideClient = getConnectedIdeClient(freshClients)
if (ideClient) {
void closeOpenDiffs(ideClient)
}
}
// Mark onboarding as complete when any user message is sent to Claude
void maybeMarkProjectOnboardingComplete()
// Extract a session title from the first real user message. One-shot
// via ref (was tengu_birch_mist experiment: first-message-only to save
// Haiku calls). The ref replaces the old `messages.length <= 1` check,
// which was broken by SessionStart hook messages (prepended via
// useDeferredHookMessages) and attachment messages (appended by
// processTextPrompt) — both pushed length past 1 on turn one, so the
// title silently fell through to the "Claude Code" default.
if (
!titleDisabled &&
!sessionTitle &&
!agentTitle &&
!titleGenerationAttemptedRef.current
) {
const firstUserMessage = newMessages.find(
m => m.type === 'user' && !m.isMeta,
)
const text =
firstUserMessage?.type === 'user'
? getContentText(firstUserMessage.message.content)
: null
// Skip synthetic breadcrumbs — slash-command output, prompt-skill
// expansions (/commit → <command-message>), local-command headers
// (/help → <command-name>), and bash-mode (!cmd → <bash-input>).
// None of these are the user's topic; wait for real prose.
if (
text &&
!text.startsWith(`<${LOCAL_COMMAND_STDOUT_TAG}>`) &&
!text.startsWith(`<${COMMAND_MESSAGE_TAG}>`) &&
!text.startsWith(`<${COMMAND_NAME_TAG}>`) &&
!text.startsWith(`<${BASH_INPUT_TAG}>`)
) {
titleGenerationAttemptedRef.current = true
void generateSessionTitle(text, new AbortController().signal).then(
title => {
if (title) setAutoGeneratedTitle(title)
else titleGenerationAttemptedRef.current = false
},
() => {
titleGenerationAttemptedRef.current = false
},
)
}
}
// Apply slash-command-scoped allowedTools (from skill frontmatter) to the
// store once per turn. This also covers the reset: the next non-skill turn
// passes [] and clears it. Must run before the !shouldQuery gate: forked
// commands (executeForkedSlashCommand) return shouldQuery=false, and
// createGetAppStateWithAllowedTools in forkedAgent.ts reads this field, so
// stale skill tools would otherwise leak into forked agent permissions.
// Previously this write was hidden inside getToolUseContext's getAppState
// (~85 calls/turn); hoisting it here makes getAppState a pure read and stops
// ephemeral contexts (permission dialog, BackgroundTasksDialog) from
// accidentally clearing it mid-turn.
store.setState(prev => {
const cur = prev.toolPermissionContext.alwaysAllowRules.command
if (
cur === additionalAllowedTools ||
(cur?.length === additionalAllowedTools.length &&
cur.every((v, i) => v === additionalAllowedTools[i]))
) {
return prev
}
return {
...prev,
toolPermissionContext: {
...prev.toolPermissionContext,
alwaysAllowRules: {
...prev.toolPermissionContext.alwaysAllowRules,
command: additionalAllowedTools,
},
},
}
})
// The last message is an assistant message if the user input was a bash command,
// or if the user input was an invalid slash command.
if (!shouldQuery) {
// Manual /compact sets messages directly (shouldQuery=false) bypassing
// handleMessageFromStream. Clear context-blocked if a compact boundary
// is present so proactive ticks resume after compaction.
if (newMessages.some(isCompactBoundaryMessage)) {
// Bump conversationId so Messages.tsx row keys change and
// stale memoized rows remount with post-compact content.
setConversationId(randomUUID())
if (feature('PROACTIVE') || feature('KAIROS')) {
proactiveModule?.setContextBlocked(false)
}
}
resetLoadingState()
setAbortController(null)
return
}
const toolUseContext = getToolUseContext(
messagesIncludingNewMessages,
newMessages,
abortController,
mainLoopModelParam,
)
// getToolUseContext reads tools/mcpClients fresh from store.getState()
// (via computeTools/mergeClients). Use those rather than the closure-
// captured `tools`/`mcpClients` — useManageMCPConnections may have
// flushed new MCP state between the render that captured this closure
// and now. Turn 1 via processInitialMessage is the main beneficiary.
const { tools: freshTools, mcpClients: freshMcpClients } =
toolUseContext.options
// Scope the skill's effort override to this turn's context only —
// wrapping getAppState keeps the override out of the global store so
// background agents and UI subscribers (Spinner, LogoV2) never see it.
if (effort !== undefined) {
const previousGetAppState = toolUseContext.getAppState
toolUseContext.getAppState = () => ({
...previousGetAppState(),
effortValue: effort,
})
}
queryCheckpoint('query_context_loading_start')
const [, , defaultSystemPrompt, baseUserContext, systemContext] =
await Promise.all([
// IMPORTANT: do this after setMessages() above, to avoid UI jank
checkAndDisableBypassPermissionsIfNeeded(
toolPermissionContext,
setAppState,
),
// Gated on TRANSCRIPT_CLASSIFIER so GrowthBook kill switch runs wherever auto mode is built in
feature('TRANSCRIPT_CLASSIFIER')
? checkAndDisableAutoModeIfNeeded(
toolPermissionContext,
setAppState,
store.getState().fastMode,
)
: undefined,
getSystemPrompt(
freshTools,
mainLoopModelParam,
Array.from(
toolPermissionContext.additionalWorkingDirectories.keys(),
),
freshMcpClients,
),
getUserContext(),
getSystemContext(),
])
const userContext = {
...baseUserContext,
...getCoordinatorUserContext(
freshMcpClients,
isScratchpadEnabled() ? getScratchpadDir() : undefined,
),
...((feature('PROACTIVE') || feature('KAIROS')) &&
proactiveModule?.isProactiveActive() &&
!terminalFocusRef.current
? {
terminalFocus:
'The terminal is unfocused \u2014 the user is not actively watching.',
}
: {}),
}
queryCheckpoint('query_context_loading_end')
const systemPrompt = buildEffectiveSystemPrompt({
mainThreadAgentDefinition,
toolUseContext,
customSystemPrompt,
defaultSystemPrompt,
appendSystemPrompt,
overrideSystemPrompt,
})
toolUseContext.renderedSystemPrompt = systemPrompt
queryCheckpoint('query_query_start')
resetTurnHookDuration()
resetTurnToolDuration()
resetTurnClassifierDuration()
for await (const event of query({
messages: messagesIncludingNewMessages,
systemPrompt,
userContext,
systemContext,
canUseTool,
toolUseContext,
querySource: getQuerySourceForREPL(),
})) {
onQueryEvent(event)
}
if (feature('BUDDY')) {
void fireCompanionObserver(messagesRef.current, reaction =>
setAppState(prev =>
prev.companionReaction === reaction
? prev
: { ...prev, companionReaction: reaction },
),
)
}
queryCheckpoint('query_end')
// Capture ant-only API metrics before resetLoadingState clears the ref.
// For multi-request turns (tool use loops), compute P50 across all requests.
if ("external" === 'ant' && apiMetricsRef.current.length > 0) {
const entries = apiMetricsRef.current
const ttfts = entries.map(e => e.ttftMs)
// Compute per-request OTPS using only active streaming time and
// streaming-only content. endResponseLength tracks content added by
// streaming deltas only, excluding subagent/compaction inflation.
const otpsValues = entries.map(e => {
const delta = Math.round(
(e.endResponseLength - e.responseLengthBaseline) / 4,
)
const samplingMs = e.lastTokenTime - e.firstTokenTime
return samplingMs > 0 ? Math.round(delta / (samplingMs / 1000)) : 0
})
const isMultiRequest = entries.length > 1
const hookMs = getTurnHookDurationMs()
const hookCount = getTurnHookCount()
const toolMs = getTurnToolDurationMs()
const toolCount = getTurnToolCount()
const classifierMs = getTurnClassifierDurationMs()
const classifierCount = getTurnClassifierCount()
const turnMs = Date.now() - loadingStartTimeRef.current
setMessages(prev => [
...prev,
createApiMetricsMessage({
ttftMs: isMultiRequest ? median(ttfts) : ttfts[0]!,
otps: isMultiRequest ? median(otpsValues) : otpsValues[0]!,
isP50: isMultiRequest,
hookDurationMs: hookMs > 0 ? hookMs : undefined,
hookCount: hookCount > 0 ? hookCount : undefined,
turnDurationMs: turnMs > 0 ? turnMs : undefined,
toolDurationMs: toolMs > 0 ? toolMs : undefined,
toolCount: toolCount > 0 ? toolCount : undefined,
classifierDurationMs: classifierMs > 0 ? classifierMs : undefined,
classifierCount: classifierCount > 0 ? classifierCount : undefined,
configWriteCount: getGlobalConfigWriteCount(),
}),
])
}
resetLoadingState()
// Log query profiling report if enabled
logQueryProfileReport()
// Signal that a query turn has completed successfully
await onTurnComplete?.(messagesRef.current)
},
[
initialMcpClients,
resetLoadingState,
getToolUseContext,
toolPermissionContext,
setAppState,
customSystemPrompt,
onTurnComplete,
appendSystemPrompt,
canUseTool,
mainThreadAgentDefinition,
onQueryEvent,
sessionTitle,
titleDisabled,
],
)
const onQuery = useCallback(
async (
newMessages: MessageType[],
abortController: AbortController,
shouldQuery: boolean,
additionalAllowedTools: string[],
mainLoopModelParam: string,
onBeforeQueryCallback?: (
input: string,
newMessages: MessageType[],
) => Promise<boolean>,
input?: string,
effort?: EffortValue,
overrideSystemPrompt?: string,
): Promise<void> => {
// If this is a teammate, mark them as active when starting a turn
if (isAgentSwarmsEnabled()) {
const teamName = getTeamName()
const agentName = getAgentName()
if (teamName && agentName) {
// Fire and forget - turn starts immediately, write happens in background
void setMemberActive(teamName, agentName, true)
}
}
// Concurrent guard via state machine. tryStart() atomically checks
// and transitions idle→running, returning the generation number.
// Returns null if already running — no separate check-then-set.
const thisGeneration = queryGuard.tryStart()
if (thisGeneration === null) {
logEvent('tengu_concurrent_onquery_detected', {})
// Extract and enqueue user message text, skipping meta messages
// (e.g. expanded skill content, tick prompts) that should not be
// replayed as user-visible text.
newMessages
.filter((m): m is UserMessage => m.type === 'user' && !m.isMeta)
.map(_ => getContentText(_.message.content))
.filter(_ => _ !== null)
.forEach((msg, i) => {
enqueue({ value: msg, mode: 'prompt' })
if (i === 0) {
logEvent('tengu_concurrent_onquery_enqueued', {})
}
})
return
}
try {
// isLoading is derived from queryGuard — tryStart() above already
// transitioned dispatching→running, so no setter call needed here.
resetTimingRefs()
setMessages(oldMessages => [...oldMessages, ...newMessages])
responseLengthRef.current = 0
if (feature('TOKEN_BUDGET')) {
const parsedBudget = input ? parseTokenBudget(input) : null
snapshotOutputTokensForTurn(
parsedBudget ?? getCurrentTurnTokenBudget(),
)
}
apiMetricsRef.current = []
setStreamingToolUses([])
setStreamingText(null)
// messagesRef is updated synchronously by the setMessages wrapper
// above, so it already includes newMessages from the append at the
// top of this try block. No reconstruction needed, no waiting for
// React's scheduler (previously cost 20-56ms per prompt; the 56ms
// case was a GC pause caught during the await).
const latestMessages = messagesRef.current
if (input) {
await mrOnBeforeQuery(input, latestMessages, newMessages.length)
}
// Pass full conversation history to callback
if (onBeforeQueryCallback && input) {
const shouldProceed = await onBeforeQueryCallback(
input,
latestMessages,
)
if (!shouldProceed) {
return
}
}
await onQueryImpl(
latestMessages,
newMessages,
abortController,
shouldQuery,
additionalAllowedTools,
mainLoopModelParam,
effort,
overrideSystemPrompt,
)
} finally {
// queryGuard.end() atomically checks generation and transitions
// running→idle. Returns false if a newer query owns the guard
// (cancel+resubmit race where the stale finally fires as a microtask).
if (queryGuard.end(thisGeneration)) {
setLastQueryCompletionTime(Date.now())
skipIdleCheckRef.current = false
// Always reset loading state in finally - this ensures cleanup even
// if onQueryImpl throws. onTurnComplete is called separately in
// onQueryImpl only on successful completion.
resetLoadingState()
await mrOnTurnComplete(
messagesRef.current,
abortController.signal.aborted,
)
// Notify bridge clients that the turn is complete so mobile apps
// can stop the spark animation and show post-turn UI.
sendBridgeResultRef.current()
// Auto-hide tungsten panel content at turn end (ant-only), but keep
// tungstenActiveSession set so the pill stays in the footer and the user
// can reopen the panel. Background tmux tasks (e.g. /hunter) run for
// minutes — wiping the session made the pill disappear entirely, forcing
// the user to re-invoke Tmux just to peek. Skip on abort so the panel
// stays open for inspection (matches the turn-duration guard below).
if (
"external" === 'ant' &&
!abortController.signal.aborted
) {
setAppState(prev => {
if (prev.tungstenActiveSession === undefined) return prev
if (prev.tungstenPanelAutoHidden === true) return prev
return { ...prev, tungstenPanelAutoHidden: true }
})
}
// Capture budget info before clearing (ant-only)
let budgetInfo:
| { tokens: number; limit: number; nudges: number }
| undefined
if (feature('TOKEN_BUDGET')) {
if (
getCurrentTurnTokenBudget() !== null &&
getCurrentTurnTokenBudget()! > 0 &&
!abortController.signal.aborted
) {
budgetInfo = {
tokens: getTurnOutputTokens(),
limit: getCurrentTurnTokenBudget()!,
nudges: getBudgetContinuationCount(),
}
}
snapshotOutputTokensForTurn(null)
}
// Add turn duration message for turns longer than 30s or with a budget
// Skip if user aborted or if in loop mode (too noisy between ticks)
// Defer if swarm teammates are still running (show when they finish)
const turnDurationMs =
Date.now() - loadingStartTimeRef.current - totalPausedMsRef.current
if (
(turnDurationMs > 30000 || budgetInfo !== undefined) &&
!abortController.signal.aborted &&
!proactiveActive
) {
const hasRunningSwarmAgents = getAllInProcessTeammateTasks(
store.getState().tasks,
).some(t => t.status === 'running')
if (hasRunningSwarmAgents) {
// Only record start time on the first deferred turn
if (swarmStartTimeRef.current === null) {
swarmStartTimeRef.current = loadingStartTimeRef.current
}
// Always update budget — later turns may carry the actual budget
if (budgetInfo) {
swarmBudgetInfoRef.current = budgetInfo
}
} else {
setMessages(prev => [
...prev,
createTurnDurationMessage(
turnDurationMs,
budgetInfo,
count(prev, isLoggableMessage),
),
])
}
}
// Clear the controller so CancelRequestHandler's canCancelRunningTask
// reads false at the idle prompt. Without this, the stale non-aborted
// controller makes ctrl+c fire onCancel() (aborting nothing) instead of
// propagating to the double-press exit flow.
setAbortController(null)
}
// Auto-restore: if the user interrupted before any meaningful response
// arrived, rewind the conversation and restore their prompt — same as
// opening the message selector and picking the last message.
// This runs OUTSIDE the queryGuard.end() check because onCancel calls
// forceEnd(), which bumps the generation so end() returns false above.
// Guards: reason === 'user-cancel' (onCancel/Esc; programmatic aborts
// use 'background'/'interrupt' and must not rewind — note abort() with
// no args sets reason to a DOMException, not undefined), !isActive (no
// newer query started — cancel+resubmit race), empty input (don't
// clobber text typed during loading), no queued commands (user queued
// B while A was loading → they've moved on, don't restore A; also
// avoids removeLastFromHistory removing B's entry instead of A's),
// not viewing a teammate (messagesRef is the main conversation — the
// old Up-arrow quick-restore had this guard, preserve it).
if (
abortController.signal.reason === 'user-cancel' &&
!queryGuard.isActive &&
inputValueRef.current === '' &&
getCommandQueueLength() === 0 &&
!store.getState().viewingAgentTaskId
) {
const msgs = messagesRef.current
const lastUserMsg = msgs.findLast(selectableUserMessagesFilter)
if (lastUserMsg) {
const idx = msgs.lastIndexOf(lastUserMsg)
if (messagesAfterAreOnlySynthetic(msgs, idx)) {
// The submit is being undone — undo its history entry too,
// otherwise Up-arrow shows the restored text twice.
removeLastFromHistory()
restoreMessageSyncRef.current(lastUserMsg)
}
}
}
}
},
[
onQueryImpl,
setAppState,
resetLoadingState,
queryGuard,
mrOnBeforeQuery,
mrOnTurnComplete,
],
)
// Handle initial message (from CLI args or plan mode exit with context clear)
// This effect runs when isLoading becomes false and there's a pending message
const initialMessageRef = useRef(false)
useEffect(() => {
const pending = initialMessage
if (!pending || isLoading || initialMessageRef.current) return
// Mark as processing to prevent re-entry
initialMessageRef.current = true
async function processInitialMessage(
initialMsg: NonNullable<typeof pending>,
) {
// Clear context if requested (plan mode exit)
if (initialMsg.clearContext) {
// Preserve the plan slug before clearing context, so the new session
// can access the same plan file after regenerateSessionId()
const oldPlanSlug = initialMsg.message.planContent
? getPlanSlug()
: undefined
const { clearConversation } = await import(
'../commands/clear/conversation.js'
)
await clearConversation({
setMessages,
readFileState: readFileState.current,
discoveredSkillNames: discoveredSkillNamesRef.current,
loadedNestedMemoryPaths: loadedNestedMemoryPathsRef.current,
getAppState: () => store.getState(),
setAppState,
setConversationId,
})
titleGenerationAttemptedRef.current = false
setAutoGeneratedTitle(undefined)
bashTools.current.clear()
bashToolsProcessedIdx.current = 0
// Restore the plan slug for the new session so getPlan() finds the file
if (oldPlanSlug) {
setPlanSlug(getSessionId(), oldPlanSlug)
}
}
// Atomically: clear initial message, set permission mode and rules, and store plan for verification
const shouldStorePlanForVerification =
initialMsg.message.planContent &&
"external" === 'ant' &&
isEnvTruthy(undefined)
setAppState(prev => {
// Build and apply permission updates (mode + allowedPrompts rules)
let updatedToolPermissionContext = initialMsg.mode
? applyPermissionUpdates(
prev.toolPermissionContext,
buildPermissionUpdates(
initialMsg.mode,
initialMsg.allowedPrompts,
),
)
: prev.toolPermissionContext
// For auto, override the mode (buildPermissionUpdates maps
// it to 'default' via toExternalPermissionMode) and strip dangerous rules
if (feature('TRANSCRIPT_CLASSIFIER') && initialMsg.mode === 'auto') {
updatedToolPermissionContext = stripDangerousPermissionsForAutoMode({
...updatedToolPermissionContext,
mode: 'auto',
prePlanMode: undefined,
})
}
return {
...prev,
initialMessage: null,
toolPermissionContext: updatedToolPermissionContext,
...(shouldStorePlanForVerification && {
pendingPlanVerification: {
plan: initialMsg.message.planContent!,
verificationStarted: false,
verificationCompleted: false,
},
}),
}
})
// Create file history snapshot for code rewind
if (fileHistoryEnabled()) {
void fileHistoryMakeSnapshot(
(updater: (prev: FileHistoryState) => FileHistoryState) => {
setAppState(prev => ({
...prev,
fileHistory: updater(prev.fileHistory),
}))
},
initialMsg.message.uuid,
)
}
// Ensure SessionStart hook context is available before the first API
// call. onSubmit calls this internally but the onQuery path below
// bypasses onSubmit — hoist here so both paths see hook messages.
await awaitPendingHooks()
// Route all initial prompts through onSubmit to ensure UserPromptSubmit hooks fire
// TODO: Simplify by always routing through onSubmit once it supports
// ContentBlockParam arrays (images) as input
const content = initialMsg.message.message.content
// Route all string content through onSubmit to ensure hooks fire
// For complex content (images, etc.), fall back to direct onQuery
// Plan messages bypass onSubmit to preserve planContent metadata for rendering
if (typeof content === 'string' && !initialMsg.message.planContent) {
// Route through onSubmit for proper processing including UserPromptSubmit hooks
void onSubmit(content, {
setCursorOffset: () => {},
clearBuffer: () => {},
resetHistory: () => {},
})
} else {
// Plan messages or complex content (images, etc.) - send directly to model
// Plan messages use onQuery to preserve planContent metadata for rendering
// TODO: Once onSubmit supports ContentBlockParam arrays, remove this branch
const newAbortController = createAbortController()
setAbortController(newAbortController)
void onQuery(
[initialMsg.message],
newAbortController,
true, // shouldQuery
[], // additionalAllowedTools
mainLoopModel,
)
}
// Reset ref after a delay to allow new initial messages
setTimeout(
ref => {
ref.current = false
},
100,
initialMessageRef,
)
}
void processInitialMessage(pending)
}, [
initialMessage,
isLoading,
setMessages,
setAppState,
onQuery,
mainLoopModel,
tools,
])
const onSubmit = useCallback(
async (
input: string,
helpers: PromptInputHelpers,
speculationAccept?: {
state: ActiveSpeculationState
speculationSessionTimeSavedMs: number
setAppState: SetAppState
},
options?: { fromKeybinding?: boolean },
) => {
// Re-pin scroll to bottom on submit so the user always sees the new
// exchange (matches OpenCode's auto-scroll behavior).
repinScroll()
// Resume loop mode if paused
if (feature('PROACTIVE') || feature('KAIROS')) {
proactiveModule?.resumeProactive()
}
// Handle immediate commands - these bypass the queue and execute right away
// even while Claude is processing. Commands opt-in via `immediate: true`.
// Commands triggered via keybindings are always treated as immediate.
if (!speculationAccept && input.trim().startsWith('/')) {
// Expand [Pasted text #N] refs so immediate commands (e.g. /btw) receive
// the pasted content, not the placeholder. The non-immediate path gets
// this expansion later in handlePromptSubmit.
const trimmedInput = expandPastedTextRefs(input, pastedContents).trim()
const spaceIndex = trimmedInput.indexOf(' ')
const commandName =
spaceIndex === -1
? trimmedInput.slice(1)
: trimmedInput.slice(1, spaceIndex)
const commandArgs =
spaceIndex === -1 ? '' : trimmedInput.slice(spaceIndex + 1).trim()
// Find matching command - treat as immediate if:
// 1. Command has `immediate: true`, OR
// 2. Command was triggered via keybinding (fromKeybinding option)
const matchingCommand = commands.find(
cmd =>
isCommandEnabled(cmd) &&
(cmd.name === commandName ||
cmd.aliases?.includes(commandName) ||
getCommandName(cmd) === commandName),
)
if (matchingCommand?.name === 'clear' && idleHintShownRef.current) {
logEvent('tengu_idle_return_action', {
action:
'hint_converted' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
variant:
idleHintShownRef.current as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
idleMinutes: Math.round(
(Date.now() - lastQueryCompletionTimeRef.current) / 60_000,
),
messageCount: messagesRef.current.length,
totalInputTokens: getTotalInputTokens(),
})
idleHintShownRef.current = false
}
const shouldTreatAsImmediate =
queryGuard.isActive &&
(matchingCommand?.immediate || options?.fromKeybinding)
if (
matchingCommand &&
shouldTreatAsImmediate &&
matchingCommand.type === 'local-jsx'
) {
// Only clear input if the submitted text matches what's in the prompt.
// When a command keybinding fires, input is "/<command>" but the actual
// input value is the user's existing text - don't clear it in that case.
if (input.trim() === inputValueRef.current.trim()) {
setInputValue('')
helpers.setCursorOffset(0)
helpers.clearBuffer()
setPastedContents({})
}
const pastedTextRefs = parseReferences(input).filter(
r => pastedContents[r.id]?.type === 'text',
)
const pastedTextCount = pastedTextRefs.length
const pastedTextBytes = pastedTextRefs.reduce(
(sum, r) => sum + (pastedContents[r.id]?.content.length ?? 0),
0,
)
logEvent('tengu_paste_text', { pastedTextCount, pastedTextBytes })
logEvent('tengu_immediate_command_executed', {
commandName:
matchingCommand.name as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
fromKeybinding: options?.fromKeybinding ?? false,
})
// Execute the command directly
const executeImmediateCommand = async (): Promise<void> => {
let doneWasCalled = false
const onDone = (
result?: string,
doneOptions?: {
display?: CommandResultDisplay
metaMessages?: string[]
},
): void => {
doneWasCalled = true
setToolJSX({
jsx: null,
shouldHidePromptInput: false,
clearLocalJSX: true,
})
const newMessages: MessageType[] = []
if (result && doneOptions?.display !== 'skip') {
addNotification({
key: `immediate-${matchingCommand.name}`,
text: result,
priority: 'immediate',
})
// In fullscreen the command just showed as a centered modal
// pane — the notification above is enough feedback. Adding
// "❯ /config" + "⎿ dismissed" to the transcript is clutter
// (those messages are type:system subtype:local_command —
// user-visible but NOT sent to the model, so skipping them
// doesn't change model context). Outside fullscreen the
// transcript entry stays so scrollback shows what ran.
if (!isFullscreenEnvEnabled()) {
newMessages.push(
createCommandInputMessage(
formatCommandInputTags(
getCommandName(matchingCommand),
commandArgs,
),
),
createCommandInputMessage(
`<${LOCAL_COMMAND_STDOUT_TAG}>${escapeXml(result)}</${LOCAL_COMMAND_STDOUT_TAG}>`,
),
)
}
}
// Inject meta messages (model-visible, user-hidden) into the transcript
if (doneOptions?.metaMessages?.length) {
newMessages.push(
...doneOptions.metaMessages.map(content =>
createUserMessage({ content, isMeta: true }),
),
)
}
if (newMessages.length) {
setMessages(prev => [...prev, ...newMessages])
}
// Restore stashed prompt after local-jsx command completes.
// The normal stash restoration path (below) is skipped because
// local-jsx commands return early from onSubmit.
if (stashedPrompt !== undefined) {
setInputValue(stashedPrompt.text)
helpers.setCursorOffset(stashedPrompt.cursorOffset)
setPastedContents(stashedPrompt.pastedContents)
setStashedPrompt(undefined)
}
}
// Build context for the command (reuses existing getToolUseContext).
// Read messages via ref to keep onSubmit stable across message
// updates — matches the pattern at L2384/L2400/L2662 and avoids
// pinning stale REPL render scopes in downstream closures.
const context = getToolUseContext(
messagesRef.current,
[],
createAbortController(),
mainLoopModel,
)
const mod = await matchingCommand.load()
const jsx = await mod.call(onDone, context, commandArgs)
// Skip if onDone already fired — prevents stuck isLocalJSXCommand
// (see processSlashCommand.tsx local-jsx case for full mechanism).
if (jsx && !doneWasCalled) {
// shouldHidePromptInput: false keeps Notifications mounted
// so the onDone result isn't lost
setToolJSX({
jsx,
shouldHidePromptInput: false,
isLocalJSXCommand: true,
})
}
}
void executeImmediateCommand()
return // Always return early - don't add to history or queue
}
}
// Remote mode: skip empty input early before any state mutations
if (activeRemote.isRemoteMode && !input.trim()) {
return
}
// Idle-return: prompt returning users to start fresh when the
// conversation is large and the cache is cold. tengu_willow_mode
// controls treatment: "dialog" (blocking), "hint" (notification), "off".
{
const willowMode = getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_willow_mode',
'off',
)
const idleThresholdMin = Number(
process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES ?? 75,
)
const tokenThreshold = Number(
process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD ?? 100_000,
)
if (
willowMode !== 'off' &&
!getGlobalConfig().idleReturnDismissed &&
!skipIdleCheckRef.current &&
!speculationAccept &&
!input.trim().startsWith('/') &&
lastQueryCompletionTimeRef.current > 0 &&
getTotalInputTokens() >= tokenThreshold
) {
const idleMs = Date.now() - lastQueryCompletionTimeRef.current
const idleMinutes = idleMs / 60_000
if (idleMinutes >= idleThresholdMin && willowMode === 'dialog') {
setIdleReturnPending({ input, idleMinutes })
setInputValue('')
helpers.setCursorOffset(0)
helpers.clearBuffer()
return
}
}
}
// Add to history for direct user submissions.
// Queued command processing (executeQueuedInput) doesn't call onSubmit,
// so notifications and already-queued user input won't be added to history here.
// Skip history for keybinding-triggered commands (user didn't type the command).
if (!options?.fromKeybinding) {
addToHistory({
display: speculationAccept
? input
: prependModeCharacterToInput(input, inputMode),
pastedContents: speculationAccept ? {} : pastedContents,
})
// Add the just-submitted command to the front of the ghost-text
// cache so it's suggested immediately (not after the 60s TTL).
if (inputMode === 'bash') {
prependToShellHistoryCache(input.trim())
}
}
// Restore stash if present, but NOT for slash commands or when loading.
// - Slash commands (especially interactive ones like /model, /context) hide
// the prompt and show a picker UI. Restoring the stash during a command would
// place the text in a hidden input, and the user would lose it by typing the
// next command. Instead, preserve the stash so it survives across command runs.
// - When loading, the submitted input will be queued and handlePromptSubmit
// will clear the input field (onInputChange('')), which would clobber the
// restored stash. Defer restoration to after handlePromptSubmit (below).
// Remote mode is exempt: it sends via WebSocket and returns early without
// calling handlePromptSubmit, so there's no clobbering risk — restore eagerly.
// In both deferred cases, the stash is restored after await handlePromptSubmit.
const isSlashCommand = !speculationAccept && input.trim().startsWith('/')
// Submit runs "now" (not queued) when not already loading, or when
// accepting speculation, or in remote mode (which sends via WS and
// returns early without calling handlePromptSubmit).
const submitsNow =
!isLoading || speculationAccept || activeRemote.isRemoteMode
if (stashedPrompt !== undefined && !isSlashCommand && submitsNow) {
setInputValue(stashedPrompt.text)
helpers.setCursorOffset(stashedPrompt.cursorOffset)
setPastedContents(stashedPrompt.pastedContents)
setStashedPrompt(undefined)
} else if (submitsNow) {
if (!options?.fromKeybinding) {
// Clear input when not loading or accepting speculation.
// Preserve input for keybinding-triggered commands.
setInputValue('')
helpers.setCursorOffset(0)
}
setPastedContents({})
}
if (submitsNow) {
setInputMode('prompt')
setIDESelection(undefined)
setSubmitCount(_ => _ + 1)
helpers.clearBuffer()
tipPickedThisTurnRef.current = false
// Show the placeholder in the same React batch as setInputValue('').
// Skip for slash/bash (they have their own echo), speculation and remote
// mode (both setMessages directly with no gap to bridge).
if (
!isSlashCommand &&
inputMode === 'prompt' &&
!speculationAccept &&
!activeRemote.isRemoteMode
) {
setUserInputOnProcessing(input)
// showSpinner includes userInputOnProcessing, so the spinner appears
// on this render. Reset timing refs now (before queryGuard.reserve()
// would) so elapsed time doesn't read as Date.now() - 0. The
// isQueryActive transition above does the same reset — idempotent.
resetTimingRefs()
}
// Increment prompt count for attribution tracking and save snapshot
// The snapshot persists promptCount so it survives compaction
if (feature('COMMIT_ATTRIBUTION')) {
setAppState(prev => ({
...prev,
attribution: incrementPromptCount(prev.attribution, snapshot => {
void recordAttributionSnapshot(snapshot).catch(error => {
logForDebugging(
`Attribution: Failed to save snapshot: ${error}`,
)
})
}),
}))
}
}
// Handle speculation acceptance
if (speculationAccept) {
const { queryRequired } = await handleSpeculationAccept(
speculationAccept.state,
speculationAccept.speculationSessionTimeSavedMs,
speculationAccept.setAppState,
input,
{
setMessages,
readFileState,
cwd: getOriginalCwd(),
},
)
if (queryRequired) {
const newAbortController = createAbortController()
setAbortController(newAbortController)
void onQuery([], newAbortController, true, [], mainLoopModel)
}
return
}
// Remote mode: send input via stream-json instead of local query.
// Permission requests from the remote are bridged into toolUseConfirmQueue
// and rendered using the standard PermissionRequest component.
//
// local-jsx slash commands (e.g. /agents, /config) render UI in THIS
// process — they have no remote equivalent. Let those fall through to
// handlePromptSubmit so they execute locally. Prompt commands and
// plain text go to the remote.
if (
activeRemote.isRemoteMode &&
!(
isSlashCommand &&
commands.find(c => {
const name = input.trim().slice(1).split(/\s/)[0]
return (
isCommandEnabled(c) &&
(c.name === name ||
c.aliases?.includes(name!) ||
getCommandName(c) === name)
)
})?.type === 'local-jsx'
)
) {
// Build content blocks when there are pasted attachments (images)
const pastedValues = Object.values(pastedContents)
const imageContents = pastedValues.filter(c => c.type === 'image')
const imagePasteIds =
imageContents.length > 0 ? imageContents.map(c => c.id) : undefined
let messageContent: string | ContentBlockParam[] = input.trim()
let remoteContent: RemoteMessageContent = input.trim()
if (pastedValues.length > 0) {
const contentBlocks: ContentBlockParam[] = []
const remoteBlocks: Array<{ type: string; [key: string]: unknown }> =
[]
const trimmedInput = input.trim()
if (trimmedInput) {
contentBlocks.push({ type: 'text', text: trimmedInput })
remoteBlocks.push({ type: 'text', text: trimmedInput })
}
for (const pasted of pastedValues) {
if (pasted.type === 'image') {
const source = {
type: 'base64' as const,
media_type: (pasted.mediaType ?? 'image/png') as
| 'image/jpeg'
| 'image/png'
| 'image/gif'
| 'image/webp',
data: pasted.content,
}
contentBlocks.push({ type: 'image', source })
remoteBlocks.push({ type: 'image', source })
} else {
contentBlocks.push({ type: 'text', text: pasted.content })
remoteBlocks.push({ type: 'text', text: pasted.content })
}
}
messageContent = contentBlocks
remoteContent = remoteBlocks
}
// Create and add user message to UI
// Note: empty input already handled by early return above
const userMessage = createUserMessage({
content: messageContent,
imagePasteIds,
})
setMessages(prev => [...prev, userMessage])
// Send to remote session
await activeRemote.sendMessage(remoteContent, {
uuid: userMessage.uuid,
})
return
}
// Ensure SessionStart hook context is available before the first API call.
await awaitPendingHooks()
await handlePromptSubmit({
input,
helpers,
queryGuard,
isExternalLoading,
mode: inputMode,
commands,
onInputChange: setInputValue,
setPastedContents,
setToolJSX,
getToolUseContext,
messages: messagesRef.current,
mainLoopModel,
pastedContents,
ideSelection,
setUserInputOnProcessing,
setAbortController,
abortController,
onQuery,
setAppState,
querySource: getQuerySourceForREPL(),
onBeforeQuery,
canUseTool,
addNotification,
setMessages,
// Read via ref so streamMode can be dropped from onSubmit deps —
// handlePromptSubmit only uses it for debug log + telemetry event.
streamMode: streamModeRef.current,
hasInterruptibleToolInProgress:
hasInterruptibleToolInProgressRef.current,
})
// Restore stash that was deferred above. Two cases:
// - Slash command: handlePromptSubmit awaited the full command execution
// (including interactive pickers). Restoring now places the stash back in
// the visible input.
// - Loading (queued): handlePromptSubmit enqueued + cleared input, then
// returned quickly. Restoring now places the stash back after the clear.
if ((isSlashCommand || isLoading) && stashedPrompt !== undefined) {
setInputValue(stashedPrompt.text)
helpers.setCursorOffset(stashedPrompt.cursorOffset)
setPastedContents(stashedPrompt.pastedContents)
setStashedPrompt(undefined)
}
},
[
queryGuard,
// isLoading is read at the !isLoading checks above for input-clearing
// and submitCount gating. It's derived from isQueryActive || isExternalLoading,
// so including it here ensures the closure captures the fresh value.
isLoading,
isExternalLoading,
inputMode,
commands,
setInputValue,
setInputMode,
setPastedContents,
setSubmitCount,
setIDESelection,
setToolJSX,
getToolUseContext,
// messages is read via messagesRef.current inside the callback to
// keep onSubmit stable across message updates (see L2384/L2400/L2662).
// Without this, each setMessages call (~30× per turn) recreates
// onSubmit, pinning the REPL render scope (1776B) + that render's
// messages array in downstream closures (PromptInput, handleAutoRunIssue).
// Heap analysis showed ~9 REPL scopes and ~15 messages array versions
// accumulating after #20174/#20175, all traced to this dep.
mainLoopModel,
pastedContents,
ideSelection,
setUserInputOnProcessing,
setAbortController,
addNotification,
onQuery,
stashedPrompt,
setStashedPrompt,
setAppState,
onBeforeQuery,
canUseTool,
remoteSession,
setMessages,
awaitPendingHooks,
repinScroll,
],
)
// Callback for when user submits input while viewing a teammate's transcript
const onAgentSubmit = useCallback(
async (
input: string,
task: InProcessTeammateTaskState | LocalAgentTaskState,
helpers: PromptInputHelpers,
) => {
if (isLocalAgentTask(task)) {
appendMessageToLocalAgent(
task.id,
createUserMessage({ content: input }),
setAppState,
)
if (task.status === 'running') {
queuePendingMessage(task.id, input, setAppState)
} else {
void resumeAgentBackground({
agentId: task.id,
prompt: input,
toolUseContext: getToolUseContext(
messagesRef.current,
[],
new AbortController(),
mainLoopModel,
),
canUseTool,
}).catch(err => {
logForDebugging(
`resumeAgentBackground failed: ${errorMessage(err)}`,
)
addNotification({
key: `resume-agent-failed-${task.id}`,
jsx: (
<Text color="error">
Failed to resume agent: {errorMessage(err)}
</Text>
),
priority: 'low',
})
})
}
} else {
injectUserMessageToTeammate(task.id, input, setAppState)
}
setInputValue('')
helpers.setCursorOffset(0)
helpers.clearBuffer()
},
[
setAppState,
setInputValue,
getToolUseContext,
canUseTool,
mainLoopModel,
addNotification,
],
)
// Handlers for auto-run /issue or /good-claude (defined after onSubmit)
const handleAutoRunIssue = useCallback(() => {
const command = autoRunIssueReason
? getAutoRunCommand(autoRunIssueReason)
: '/issue'
setAutoRunIssueReason(null) // Clear the state
onSubmit(command, {
setCursorOffset: () => {},
clearBuffer: () => {},
resetHistory: () => {},
}).catch(err => {
logForDebugging(`Auto-run ${command} failed: ${errorMessage(err)}`)
})
}, [onSubmit, autoRunIssueReason])
const handleCancelAutoRunIssue = useCallback(() => {
setAutoRunIssueReason(null)
}, [])
// Handler for when user presses 1 on survey thanks screen to share details
const handleSurveyRequestFeedback = useCallback(() => {
const command = "external" === 'ant' ? '/issue' : '/feedback'
onSubmit(command, {
setCursorOffset: () => {},
clearBuffer: () => {},
resetHistory: () => {},
}).catch(err => {
logForDebugging(
`Survey feedback request failed: ${err instanceof Error ? err.message : String(err)}`,
)
})
}, [onSubmit])
// onSubmit is unstable (deps include `messages` which changes every turn).
// `handleOpenRateLimitOptions` is prop-drilled to every MessageRow, and each
// MessageRow fiber pins the closure (and transitively the entire REPL render
// scope, ~1.8KB) at mount time. Using a ref keeps this callback stable so
// old REPL scopes can be GC'd — saves ~35MB over a 1000-turn session.
const onSubmitRef = useRef(onSubmit)
onSubmitRef.current = onSubmit
const handleOpenRateLimitOptions = useCallback(() => {
void onSubmitRef.current('/rate-limit-options', {
setCursorOffset: () => {},
clearBuffer: () => {},
resetHistory: () => {},
})
}, [])
const handleExit = useCallback(async () => {
setIsExiting(true)
// In bg sessions, always detach instead of kill — even when a worktree is
// active. Without this guard, the worktree branch below short-circuits into
// ExitFlow (which calls gracefulShutdown) before exit.tsx is ever loaded.
if (feature('BG_SESSIONS') && isBgSession()) {
spawnSync('tmux', ['detach-client'], { stdio: 'ignore' })
setIsExiting(false)
return
}
const showWorktree = getCurrentWorktreeSession() !== null
if (showWorktree) {
setExitFlow(
<ExitFlow
showWorktree
onDone={() => {}}
onCancel={() => {
setExitFlow(null)
setIsExiting(false)
}}
/>,
)
return
}
const exitMod = await exit.load()
const exitFlowResult = await exitMod.call(() => {})
setExitFlow(exitFlowResult)
// If call() returned without killing the process (bg session detach),
// clear isExiting so the UI is usable on reattach. No-op on the normal
// path — gracefulShutdown's process.exit() means we never get here.
if (exitFlowResult === null) {
setIsExiting(false)
}
}, [])
const handleShowMessageSelector = useCallback(() => {
setIsMessageSelectorVisible(prev => !prev)
}, [])
// Rewind conversation state to just before `message`: slice messages,
// reset conversation ID, microcompact state, permission mode, prompt suggestion.
// Does NOT touch the prompt input. Index is computed from messagesRef (always
// fresh via the setMessages wrapper) so callers don't need to worry about
// stale closures.
const rewindConversationTo = useCallback(
(message: UserMessage) => {
const prev = messagesRef.current
const messageIndex = prev.lastIndexOf(message)
if (messageIndex === -1) return
logEvent('tengu_conversation_rewind', {
preRewindMessageCount: prev.length,
postRewindMessageCount: messageIndex,
messagesRemoved: prev.length - messageIndex,
rewindToMessageIndex: messageIndex,
})
setMessages(prev.slice(0, messageIndex))
// Careful, this has to happen after setMessages
setConversationId(randomUUID())
// Reset cached microcompact state so stale pinned cache edits
// don't reference tool_use_ids from truncated messages
resetMicrocompactState()
if (feature('CONTEXT_COLLAPSE')) {
// Rewind truncates the REPL array. Commits whose archived span
// was past the rewind point can't be projected anymore
// (projectView silently skips them) but the staged queue and ID
// maps reference stale uuids. Simplest safe reset: drop
// everything. The ctx-agent will re-stage on the next
// threshold crossing.
/* eslint-disable @typescript-eslint/no-require-imports */
;(
require('../services/contextCollapse/index.js') as typeof import('../services/contextCollapse/index.js')
).resetContextCollapse()
/* eslint-enable @typescript-eslint/no-require-imports */
}
// Restore state from the message we're rewinding to
setAppState(prev => ({
...prev,
// Restore permission mode from the message
toolPermissionContext:
message.permissionMode &&
prev.toolPermissionContext.mode !== message.permissionMode
? {
...prev.toolPermissionContext,
mode: message.permissionMode,
}
: prev.toolPermissionContext,
// Clear stale prompt suggestion from previous conversation state
promptSuggestion: {
text: null,
promptId: null,
shownAt: 0,
acceptedAt: 0,
generationRequestId: null,
},
}))
},
[setMessages, setAppState],
)
// Synchronous rewind + input population. Used directly by auto-restore on
// interrupt (so React batches with the abort's setMessages → single render,
// no flicker). MessageSelector wraps this in setImmediate via handleRestoreMessage.
const restoreMessageSync = useCallback(
(message: UserMessage) => {
rewindConversationTo(message)
const r = textForResubmit(message)
if (r) {
setInputValue(r.text)
setInputMode(r.mode)
}
// Restore pasted images
if (
Array.isArray(message.message.content) &&
message.message.content.some(block => block.type === 'image')
) {
const imageBlocks: Array<ImageBlockParam> =
message.message.content.filter(block => block.type === 'image')
if (imageBlocks.length > 0) {
const newPastedContents: Record<number, PastedContent> = {}
imageBlocks.forEach((block, index) => {
if (block.source.type === 'base64') {
const id = message.imagePasteIds?.[index] ?? index + 1
newPastedContents[id] = {
id,
type: 'image',
content: block.source.data,
mediaType: block.source.media_type,
}
}
})
setPastedContents(newPastedContents)
}
}
},
[rewindConversationTo, setInputValue],
)
restoreMessageSyncRef.current = restoreMessageSync
// MessageSelector path: defer via setImmediate so the "Interrupted" message
// renders to static output before rewind — otherwise it remains vestigial
// at the top of the screen.
const handleRestoreMessage = useCallback(
async (message: UserMessage) => {
setImmediate(
(restore, message) => restore(message),
restoreMessageSync,
message,
)
},
[restoreMessageSync],
)
// Not memoized — hook stores caps via ref, reads latest closure at dispatch.
// 24-char prefix: deriveUUID preserves first 24, renderable uuid prefix-matches raw source.
const findRawIndex = (uuid: string) => {
const prefix = uuid.slice(0, 24)
return messages.findIndex(m => m.uuid.slice(0, 24) === prefix)
}
const messageActionCaps: MessageActionCaps = {
copy: text =>
// setClipboard RETURNS OSC 52 — caller must stdout.write (tmux side-effects load-buffer, but that's tmux-only).
void setClipboard(text).then(raw => {
if (raw) process.stdout.write(raw)
addNotification({
// Same key as text-selection copy — repeated copies replace toast, don't queue.
key: 'selection-copied',
text: 'copied',
color: 'success',
priority: 'immediate',
timeoutMs: 2000,
})
}),
edit: async msg => {
// Same skip-confirm check as /rewind: lossless → direct, else confirm dialog.
const rawIdx = findRawIndex(msg.uuid)
const raw = rawIdx >= 0 ? messages[rawIdx] : undefined
if (!raw || !selectableUserMessagesFilter(raw)) return
const noFileChanges = !(await fileHistoryHasAnyChanges(
fileHistory,
raw.uuid,
))
const onlySynthetic = messagesAfterAreOnlySynthetic(messages, rawIdx)
if (noFileChanges && onlySynthetic) {
// rewindConversationTo's setMessages races stream appends — cancel first (idempotent).
onCancel()
// handleRestoreMessage also restores pasted images.
void handleRestoreMessage(raw)
} else {
// Dialog path: onPreRestore (= onCancel) fires when user CONFIRMS, not on nevermind.
setMessageSelectorPreselect(raw)
setIsMessageSelectorVisible(true)
}
},
}
const { enter: enterMessageActions, handlers: messageActionHandlers } =
useMessageActions(cursor, setCursor, cursorNavRef, messageActionCaps)
async function onInit() {
// Always verify API key on startup, so we can show the user an error in the
// bottom right corner of the screen if the API key is invalid.
void reverify()
// Populate readFileState with CLAUDE.md files at startup
const memoryFiles = await getMemoryFiles()
if (memoryFiles.length > 0) {
const fileList = memoryFiles
.map(
f =>
` [${f.type}] ${f.path} (${f.content.length} chars)${f.parent ? ` (included by ${f.parent})` : ''}`,
)
.join('\n')
logForDebugging(
`Loaded ${memoryFiles.length} CLAUDE.md/rules files:\n${fileList}`,
)
} else {
logForDebugging('No CLAUDE.md/rules files found')
}
for (const file of memoryFiles) {
// When the injected content doesn't match disk (stripped HTML comments,
// stripped frontmatter, MEMORY.md truncation), cache the RAW disk bytes
// with isPartialView so Edit/Write require a real Read first while
// getChangedFiles + nested_memory dedup still work.
readFileState.current.set(file.path, {
content: file.contentDiffersFromDisk
? (file.rawContent ?? file.content)
: file.content,
timestamp: Date.now(),
offset: undefined,
limit: undefined,
isPartialView: file.contentDiffersFromDisk,
})
}
// Initial message handling is done via the initialMessage effect
}
// Register cost summary tracker
useCostSummary(useFpsMetrics())
// Record transcripts locally, for debugging and conversation recovery
// Don't record conversation if we only have initial messages; optimizes
// the case where user resumes a conversation then quites before doing
// anything else
useLogMessages(messages, messages.length === initialMessages?.length)
// REPL Bridge: replicate user/assistant messages to the bridge session
// for remote access via claude.ai. No-op in external builds or when not enabled.
const { sendBridgeResult } = useReplBridge(
messages,
setMessages,
abortControllerRef,
commands,
mainLoopModel,
)
sendBridgeResultRef.current = sendBridgeResult
useAfterFirstRender()
// Track prompt queue usage for analytics. Fire once per transition from
// empty to non-empty, not on every length change -- otherwise a render loop
// (concurrent onQuery thrashing, etc.) spams saveGlobalConfig, which hits
// ELOCKED under concurrent sessions and falls back to unlocked writes.
// That write storm is the primary trigger for ~/.claude.json corruption
// (GH #3117).
const hasCountedQueueUseRef = useRef(false)
useEffect(() => {
if (queuedCommands.length < 1) {
hasCountedQueueUseRef.current = false
return
}
if (hasCountedQueueUseRef.current) return
hasCountedQueueUseRef.current = true
saveGlobalConfig(current => ({
...current,
promptQueueUseCount: (current.promptQueueUseCount ?? 0) + 1,
}))
}, [queuedCommands.length])
// Process queued commands when query completes and queue has items
const executeQueuedInput = useCallback(
async (queuedCommands: QueuedCommand[]) => {
await handlePromptSubmit({
helpers: {
setCursorOffset: () => {},
clearBuffer: () => {},
resetHistory: () => {},
},
queryGuard,
commands,
onInputChange: () => {},
setPastedContents: () => {},
setToolJSX,
getToolUseContext,
messages,
mainLoopModel,
ideSelection,
setUserInputOnProcessing,
setAbortController,
onQuery,
setAppState,
querySource: getQuerySourceForREPL(),
onBeforeQuery,
canUseTool,
addNotification,
setMessages,
queuedCommands,
})
},
[
queryGuard,
commands,
setToolJSX,
getToolUseContext,
messages,
mainLoopModel,
ideSelection,
setUserInputOnProcessing,
canUseTool,
setAbortController,
onQuery,
addNotification,
setAppState,
onBeforeQuery,
],
)
useQueueProcessor({
executeQueuedInput,
hasActiveLocalJsxUI: isShowingLocalJSXCommand,
queryGuard,
})
// We'll use the global lastInteractionTime from state.ts
// Update last interaction time when input changes.
// Must be immediate because useEffect runs after the Ink render cycle flush.
useEffect(() => {
activityManager.recordUserActivity()
updateLastInteractionTime(true)
}, [inputValue, submitCount])
useEffect(() => {
if (submitCount === 1) {
startBackgroundHousekeeping()
}
}, [submitCount])
// Show notification when Claude is done responding and user is idle
useEffect(() => {
// Don't set up notification if Claude is busy
if (isLoading) return
// Only enable notifications after the first new interaction in this session
if (submitCount === 0) return
// No query has completed yet
if (lastQueryCompletionTime === 0) return
// Set timeout to check idle state
const timer = setTimeout(
(
lastQueryCompletionTime,
isLoading,
toolJSX,
focusedInputDialogRef,
terminal,
) => {
// Check if user has interacted since the response ended
const lastUserInteraction = getLastInteractionTime()
if (lastUserInteraction > lastQueryCompletionTime) {
// User has interacted since Claude finished - they're not idle, don't notify
return
}
// User hasn't interacted since response ended, check other conditions
const idleTimeSinceResponse = Date.now() - lastQueryCompletionTime
if (
!isLoading &&
!toolJSX &&
// Use ref to get current dialog state, avoiding stale closure
focusedInputDialogRef.current === undefined &&
idleTimeSinceResponse >= getGlobalConfig().messageIdleNotifThresholdMs
) {
void sendNotification(
{
message: 'Claude is waiting for your input',
notificationType: 'idle_prompt',
},
terminal,
)
}
},
getGlobalConfig().messageIdleNotifThresholdMs,
lastQueryCompletionTime,
isLoading,
toolJSX,
focusedInputDialogRef,
terminal,
)
return () => clearTimeout(timer)
}, [isLoading, toolJSX, submitCount, lastQueryCompletionTime, terminal])
// Idle-return hint: show notification when idle threshold is exceeded.
// Timer fires after the configured idle period; notification persists until
// dismissed or the user submits.
useEffect(() => {
if (lastQueryCompletionTime === 0) return
if (isLoading) return
const willowMode: string = getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_willow_mode',
'off',
)
if (willowMode !== 'hint' && willowMode !== 'hint_v2') return
if (getGlobalConfig().idleReturnDismissed) return
const tokenThreshold = Number(
process.env.CLAUDE_CODE_IDLE_TOKEN_THRESHOLD ?? 100_000,
)
if (getTotalInputTokens() < tokenThreshold) return
const idleThresholdMs =
Number(process.env.CLAUDE_CODE_IDLE_THRESHOLD_MINUTES ?? 75) * 60_000
const elapsed = Date.now() - lastQueryCompletionTime
const remaining = idleThresholdMs - elapsed
const timer = setTimeout(
(lqct, addNotif, msgsRef, mode, hintRef) => {
if (msgsRef.current.length === 0) return
const totalTokens = getTotalInputTokens()
const formattedTokens = formatTokens(totalTokens)
const idleMinutes = (Date.now() - lqct) / 60_000
addNotif({
key: 'idle-return-hint',
jsx:
mode === 'hint_v2' ? (
<>
<Text dimColor>new task? </Text>
<Text color="suggestion">/clear</Text>
<Text dimColor> to save </Text>
<Text color="suggestion">{formattedTokens} tokens</Text>
</>
) : (
<Text color="warning">
new task? /clear to save {formattedTokens} tokens
</Text>
),
priority: 'medium',
// Persist until submit — the hint fires at T+75min idle, user may
// not return for hours. removeNotification in useEffect cleanup
// handles dismissal. 0x7FFFFFFF = setTimeout max (~24.8 days).
timeoutMs: 0x7fffffff,
})
hintRef.current = mode
logEvent('tengu_idle_return_action', {
action:
'hint_shown' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
variant:
mode as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
idleMinutes: Math.round(idleMinutes),
messageCount: msgsRef.current.length,
totalInputTokens: totalTokens,
})
},
Math.max(0, remaining),
lastQueryCompletionTime,
addNotification,
messagesRef,
willowMode,
idleHintShownRef,
)
return () => {
clearTimeout(timer)
removeNotification('idle-return-hint')
idleHintShownRef.current = false
}
}, [lastQueryCompletionTime, isLoading, addNotification, removeNotification])
// Submits incoming prompts from teammate messages or tasks mode as new turns
// Returns true if submission succeeded, false if a query is already running
const handleIncomingPrompt = useCallback(
(content: string, options?: { isMeta?: boolean }): boolean => {
if (queryGuard.isActive) return false
// Defer to user-queued commands — user input always takes priority
// over system messages (teammate messages, task list items, etc.)
// Read from the module-level store at call time (not the render-time
// snapshot) to avoid a stale closure — this callback's deps don't
// include the queue.
if (
getCommandQueue().some(
cmd => cmd.mode === 'prompt' || cmd.mode === 'bash',
)
) {
return false
}
const newAbortController = createAbortController()
setAbortController(newAbortController)
// Create a user message with the formatted content (includes XML wrapper)
const userMessage = createUserMessage({
content,
isMeta: options?.isMeta ? true : undefined,
})
void onQuery([userMessage], newAbortController, true, [], mainLoopModel)
return true
},
[onQuery, mainLoopModel, store],
)
// Voice input integration (VOICE_MODE builds only)
const voice = feature('VOICE_MODE')
? // biome-ignore lint/correctness/useHookAtTopLevel: feature() is a compile-time constant
useVoiceIntegration({ setInputValueRaw, inputValueRef, insertTextRef })
: {
stripTrailing: () => 0,
handleKeyEvent: () => {},
resetAnchor: () => {},
interimRange: null,
}
useInboxPoller({
enabled: isAgentSwarmsEnabled(),
isLoading,
focusedInputDialog,
onSubmitMessage: handleIncomingPrompt,
})
useMailboxBridge({ isLoading, onSubmitMessage: handleIncomingPrompt })
useFeishuBridge({ messages, isLoading })
// Scheduled tasks from .claude/scheduled_tasks.json (CronCreate/Delete/List)
if (feature('AGENT_TRIGGERS')) {
// Assistant mode bypasses the isLoading gate (the proactive tick →
// Sleep → tick loop would otherwise starve the scheduler).
// kairosEnabled is set once in initialState (main.tsx) and never mutated — no
// subscription needed. The tengu_kairos_cron runtime gate is checked inside
// useScheduledTasks's effect (not here) since wrapping a hook call in a dynamic
// condition would break rules-of-hooks.
const assistantMode = store.getState().kairosEnabled
// biome-ignore lint/correctness/useHookAtTopLevel: feature() is a compile-time constant
useScheduledTasks!({ isLoading, assistantMode, setMessages })
}
// Note: Permission polling is now handled by useInboxPoller
// - Workers receive permission responses via mailbox messages
// - Leaders receive permission requests via mailbox messages
if ("external" === 'ant') {
// Tasks mode: watch for tasks and auto-process them
// eslint-disable-next-line react-hooks/rules-of-hooks
// biome-ignore lint/correctness/useHookAtTopLevel: conditional for dead code elimination in external builds
useTaskListWatcher({
taskListId,
isLoading,
onSubmitTask: handleIncomingPrompt,
})
// Loop mode: auto-tick when enabled (via /job command)
// eslint-disable-next-line react-hooks/rules-of-hooks
// biome-ignore lint/correctness/useHookAtTopLevel: conditional for dead code elimination in external builds
useProactive?.({
// Suppress ticks while an initial message is pending — the initial
// message will be processed asynchronously and a premature tick would
// race with it, causing concurrent-query enqueue of expanded skill text.
isLoading: isLoading || initialMessage !== null,
queuedCommandsLength: queuedCommands.length,
hasActiveLocalJsxUI: isShowingLocalJSXCommand,
isInPlanMode: toolPermissionContext.mode === 'plan',
onSubmitTick: (prompt: string) =>
handleIncomingPrompt(prompt, { isMeta: true }),
onQueueTick: (prompt: string) =>
enqueue({ mode: 'prompt', value: prompt, isMeta: true }),
})
}
// Abort the current operation when a 'now' priority message arrives
// (e.g. from a chat UI client via UDS).
useEffect(() => {
if (queuedCommands.some(cmd => cmd.priority === 'now')) {
abortControllerRef.current?.abort('interrupt')
}
}, [queuedCommands])
// Initial load
useEffect(() => {
void onInit()
// Cleanup on unmount
return () => {
void diagnosticTracker.shutdown()
}
// TODO: fix this
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// Listen for suspend/resume events
const { internal_eventEmitter } = useStdin()
const [remountKey, setRemountKey] = useState(0)
useEffect(() => {
const handleSuspend = () => {
// Print suspension instructions
process.stdout.write(
`\nClaude Code has been suspended. Run \`fg\` to bring Claude Code back.\nNote: ctrl + z now suspends Claude Code, ctrl + _ undoes input.\n`,
)
}
const handleResume = () => {
// Force complete component tree replacement instead of terminal clear
// Ink now handles line count reset internally on SIGCONT
setRemountKey(prev => prev + 1)
}
internal_eventEmitter?.on('suspend', handleSuspend)
internal_eventEmitter?.on('resume', handleResume)
return () => {
internal_eventEmitter?.off('suspend', handleSuspend)
internal_eventEmitter?.off('resume', handleResume)
}
}, [internal_eventEmitter])
// Derive stop hook spinner suffix from messages state
const stopHookSpinnerSuffix = useMemo(() => {
if (!isLoading) return null
// Find stop hook progress messages
const progressMsgs = messages.filter(
(m): m is ProgressMessage<HookProgress> =>
m.type === 'progress' &&
m.data.type === 'hook_progress' &&
(m.data.hookEvent === 'Stop' || m.data.hookEvent === 'SubagentStop'),
)
if (progressMsgs.length === 0) return null
// Get the most recent stop hook execution
const currentToolUseID = progressMsgs.at(-1)?.toolUseID
if (!currentToolUseID) return null
// Check if there's already a summary message for this execution (hooks completed)
const hasSummaryForCurrentExecution = messages.some(
m =>
m.type === 'system' &&
m.subtype === 'stop_hook_summary' &&
m.toolUseID === currentToolUseID,
)
if (hasSummaryForCurrentExecution) return null
const currentHooks = progressMsgs.filter(
p => p.toolUseID === currentToolUseID,
)
const total = currentHooks.length
// Count completed hooks
const completedCount = count(messages, m => {
if (m.type !== 'attachment') return false
const attachment = m.attachment
return (
'hookEvent' in attachment &&
(attachment.hookEvent === 'Stop' ||
attachment.hookEvent === 'SubagentStop') &&
'toolUseID' in attachment &&
attachment.toolUseID === currentToolUseID
)
})
// Check if any hook has a custom status message
const customMessage = currentHooks.find(p => p.data.statusMessage)?.data
.statusMessage
if (customMessage) {
// Use custom message with progress counter if multiple hooks
return total === 1
? `${customMessage}…`
: `${customMessage}… ${completedCount}/${total}`
}
// Fall back to default behavior
const hookType =
currentHooks[0]?.data.hookEvent === 'SubagentStop'
? 'subagent stop'
: 'stop'
if ("external" === 'ant') {
const cmd = currentHooks[completedCount]?.data.command
const label = cmd ? ` '${truncateToWidth(cmd, 40)}'` : ''
return total === 1
? `running ${hookType} hook${label}`
: `running ${hookType} hook${label}\u2026 ${completedCount}/${total}`
}
return total === 1
? `running ${hookType} hook`
: `running stop hooks… ${completedCount}/${total}`
}, [messages, isLoading])
// Callback to capture frozen state when entering transcript mode
const handleEnterTranscript = useCallback(() => {
setFrozenTranscriptState({
messagesLength: messages.length,
streamingToolUsesLength: streamingToolUses.length,
})
}, [messages.length, streamingToolUses.length])
// Callback to clear frozen state when exiting transcript mode
const handleExitTranscript = useCallback(() => {
setFrozenTranscriptState(null)
}, [])
// Props for GlobalKeybindingHandlers component (rendered inside KeybindingSetup)
const virtualScrollActive = isFullscreenEnvEnabled() && !disableVirtualScroll
// Transcript search state. Hooks must be unconditional so they live here
// (not inside the `if (screen === 'transcript')` branch below); isActive
// gates the useInput. Query persists across bar open/close so n/N keep
// working after Enter dismisses the bar (less semantics).
const jumpRef = useRef<JumpHandle | null>(null)
const [searchOpen, setSearchOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
const [searchCount, setSearchCount] = useState(0)
const [searchCurrent, setSearchCurrent] = useState(0)
const onSearchMatchesChange = useCallback(
(count: number, current: number) => {
setSearchCount(count)
setSearchCurrent(current)
},
[],
)
useInput(
(input, key, event) => {
if (key.ctrl || key.meta) return
// No Esc handling here — less has no navigating mode. Search state
// (highlights, n/N) is just state. Esc/q/ctrl+c → transcript:exit
// (ungated). Highlights clear on exit via the screen-change effect.
if (input === '/') {
// Capture scrollTop NOW — typing is a preview, 0-matches snaps
// back here. Synchronous ref write, fires before the bar's
// mount-effect calls setSearchQuery.
jumpRef.current?.setAnchor()
setSearchOpen(true)
event.stopImmediatePropagation()
return
}
// Held-key batching: tokenizer coalesces to 'nnn'. Same uniform-batch
// pattern as modalPagerAction in ScrollKeybindingHandler.tsx. Each
// repeat is a step (n isn't idempotent like g).
const c = input[0]
if (
(c === 'n' || c === 'N') &&
input === c.repeat(input.length) &&
searchCount > 0
) {
const fn =
c === 'n' ? jumpRef.current?.nextMatch : jumpRef.current?.prevMatch
if (fn) for (let i = 0; i < input.length; i++) fn()
event.stopImmediatePropagation()
}
},
// Search needs virtual scroll (jumpRef drives VirtualMessageList). [
// kills it, so !dumpMode — after [ there's nothing to jump in.
{
isActive:
screen === 'transcript' &&
virtualScrollActive &&
!searchOpen &&
!dumpMode,
},
)
const {
setQuery: setHighlight,
scanElement,
setPositions,
} = useSearchHighlight()
// Resize → abort search. Positions are (msg, query, WIDTH)-keyed —
// cached positions are stale after a width change (new layout, new
// wrapping). Clearing searchQuery triggers VML's setSearchQuery('')
// which clears positionsCache + setPositions(null). Bar closes.
// User hits / again → fresh everything.
const transcriptCols = useTerminalSize().columns
const prevColsRef = React.useRef(transcriptCols)
React.useEffect(() => {
if (prevColsRef.current !== transcriptCols) {
prevColsRef.current = transcriptCols
if (searchQuery || searchOpen) {
setSearchOpen(false)
setSearchQuery('')
setSearchCount(0)
setSearchCurrent(0)
jumpRef.current?.disarmSearch()
setHighlight('')
}
}
}, [transcriptCols, searchQuery, searchOpen, setHighlight])
// Transcript escape hatches. Bare letters in modal context (no prompt
// competing for input) — same class as g/G/j/k in ScrollKeybindingHandler.
useInput(
(input, key, event) => {
if (key.ctrl || key.meta) return
if (input === 'q') {
// less: q quits the pager. ctrl+o toggles; q is the lineage exit.
handleExitTranscript()
event.stopImmediatePropagation()
return
}
if (input === '[' && !dumpMode) {
// Force dump-to-scrollback. Also expand + uncap — no point dumping
// a subset. Terminal/tmux cmd-F can now find anything. Guard here
// (not in isActive) so v still works post-[ — dump-mode footer at
// ~4898 wires editorStatus, confirming v is meant to stay live.
setDumpMode(true)
setShowAllInTranscript(true)
event.stopImmediatePropagation()
} else if (input === 'v') {
// less-style: v opens the file in $VISUAL/$EDITOR. Render the full
// transcript (same path /export uses), write to tmp, hand off.
// openFileInExternalEditor handles alt-screen suspend/resume for
// terminal editors; GUI editors spawn detached.
event.stopImmediatePropagation()
// Drop double-taps: the render is async and a second press before it
// completes would run a second parallel render (double memory, two
// tempfiles, two editor spawns). editorGenRef only guards
// transcript-exit staleness, not same-session concurrency.
if (editorRenderingRef.current) return
editorRenderingRef.current = true
// Capture generation + make a staleness-aware setter. Each write
// checks gen (transcript exit bumps it → late writes from the
// async render go silent).
const gen = editorGenRef.current
const setStatus = (s: string): void => {
if (gen !== editorGenRef.current) return
clearTimeout(editorTimerRef.current)
setEditorStatus(s)
}
setStatus(`rendering ${deferredMessages.length} messages…`)
void (async () => {
try {
// Width = terminal minus vim's line-number gutter (4 digits +
// space + slack). Floor at 80. PassThrough has no .columns so
// without this Ink defaults to 80. Trailing-space strip: right-
// aligned timestamps still leave a flexbox spacer run at EOL.
// eslint-disable-next-line custom-rules/prefer-use-terminal-size -- one-shot at keypress time, not a reactive render dep
const w = Math.max(80, (process.stdout.columns ?? 80) - 6)
const raw = await renderMessagesToPlainText(
deferredMessages,
tools,
w,
)
const text = raw.replace(/[ \t]+$/gm, '')
const path = join(tmpdir(), `cc-transcript-${Date.now()}.txt`)
await writeFile(path, text)
const opened = openFileInExternalEditor(path)
setStatus(
opened
? `opening ${path}`
: `wrote ${path} · no $VISUAL/$EDITOR set`,
)
} catch (e) {
setStatus(
`render failed: ${e instanceof Error ? e.message : String(e)}`,
)
}
editorRenderingRef.current = false
if (gen !== editorGenRef.current) return
editorTimerRef.current = setTimeout(s => s(''), 4000, setEditorStatus)
})()
}
},
// !searchOpen: typing 'v' or '[' in the search bar is search input, not
// a command. No !dumpMode here — v should work after [ (the [ handler
// guards itself inline).
{ isActive: screen === 'transcript' && virtualScrollActive && !searchOpen },
)
// Fresh `less` per transcript entry. Prevents stale highlights matching
// unrelated normal-mode text (overlay is alt-screen-global) and avoids
// surprise n/N on re-entry. Same exit resets [ dump mode — each ctrl+o
// entry is a fresh instance.
const inTranscript = screen === 'transcript' && virtualScrollActive
useEffect(() => {
if (!inTranscript) {
setSearchQuery('')
setSearchCount(0)
setSearchCurrent(0)
setSearchOpen(false)
editorGenRef.current++
clearTimeout(editorTimerRef.current)
setDumpMode(false)
setEditorStatus('')
}
}, [inTranscript])
useEffect(() => {
setHighlight(inTranscript ? searchQuery : '')
// Clear the position-based CURRENT (yellow) overlay too. setHighlight
// only clears the scan-based inverse. Without this, the yellow box
// persists at its last screen coords after ctrl-c exits transcript.
if (!inTranscript) setPositions(null)
}, [inTranscript, searchQuery, setHighlight, setPositions])
const globalKeybindingProps = {
screen,
setScreen,
showAllInTranscript,
setShowAllInTranscript,
messageCount: messages.length,
onEnterTranscript: handleEnterTranscript,
onExitTranscript: handleExitTranscript,
virtualScrollActive,
// Bar-open is a mode (owns keystrokes — j/k type, Esc cancels).
// Navigating (query set, bar closed) is NOT — Esc exits transcript,
// same as less q with highlights still visible. useSearchInput
// doesn't stopPropagation, so without this gate transcript:exit
// would fire on the same Esc that cancels the bar (child registers
// first, fires first, bubbles).
searchBarOpen: searchOpen,
}
// Use frozen lengths to slice arrays, avoiding memory overhead of cloning
const transcriptMessages = frozenTranscriptState
? deferredMessages.slice(0, frozenTranscriptState.messagesLength)
: deferredMessages
const transcriptStreamingToolUses = frozenTranscriptState
? streamingToolUses.slice(0, frozenTranscriptState.streamingToolUsesLength)
: streamingToolUses
// Handle shift+down for teammate navigation and background task management.
// Guard onOpenBackgroundTasks when a local-jsx dialog (e.g. /mcp) is open —
// otherwise Shift+Down stacks BackgroundTasksDialog on top and deadlocks input.
useBackgroundTaskNavigation({
onOpenBackgroundTasks: isShowingLocalJSXCommand
? undefined
: () => setShowBashesDialog(true),
})
// Auto-exit viewing mode when teammate completes or errors
useTeammateViewAutoExit()
if (screen === 'transcript') {
// Virtual scroll replaces the 30-message cap: everything is scrollable
// and memory is bounded by the viewport. Without it, wrapping transcript
// in a ScrollBox would mount all messages (~250 MB on long sessions —
// the exact problem), so the kill switch and non-fullscreen paths must
// fall through to the legacy render: no alt screen, dump to terminal
// scrollback, 30-cap + Ctrl+E. Reusing scrollRef is safe — normal-mode
// and transcript-mode are mutually exclusive (this early return), so
// only one ScrollBox is ever mounted at a time.
const transcriptScrollRef =
isFullscreenEnvEnabled() && !disableVirtualScroll && !dumpMode
? scrollRef
: undefined
const transcriptMessagesElement = (
<Messages
messages={transcriptMessages}
tools={tools}
commands={commands}
verbose={true}
toolJSX={null}
toolUseConfirmQueue={[]}
inProgressToolUseIDs={inProgressToolUseIDs}
isMessageSelectorVisible={false}
conversationId={conversationId}
screen={screen}
agentDefinitions={agentDefinitions}
streamingToolUses={transcriptStreamingToolUses}
showAllInTranscript={showAllInTranscript}
onOpenRateLimitOptions={handleOpenRateLimitOptions}
isLoading={isLoading}
hidePastThinking={true}
streamingThinking={streamingThinking}
scrollRef={transcriptScrollRef}
jumpRef={jumpRef}
onSearchMatchesChange={onSearchMatchesChange}
scanElement={scanElement}
setPositions={setPositions}
disableRenderCap={dumpMode}
/>
)
const transcriptToolJSX = toolJSX && (
<Box flexDirection="column" width="100%">
{toolJSX.jsx}
</Box>
)
const transcriptReturn = (
<KeybindingSetup>
<AnimatedTerminalTitle
isAnimating={titleIsAnimating}
title={terminalTitle}
disabled={titleDisabled}
noPrefix={showStatusInTerminalTab}
/>
<GlobalKeybindingHandlers {...globalKeybindingProps} />
{feature('VOICE_MODE') ? (
<VoiceKeybindingHandler
voiceHandleKeyEvent={voice.handleKeyEvent}
stripTrailing={voice.stripTrailing}
resetAnchor={voice.resetAnchor}
isActive={!toolJSX?.isLocalJSXCommand}
/>
) : null}
<CommandKeybindingHandlers
onSubmit={onSubmit}
isActive={!toolJSX?.isLocalJSXCommand}
/>
{transcriptScrollRef ? (
// ScrollKeybindingHandler must mount before CancelRequestHandler so
// ctrl+c-with-selection copies instead of cancelling the active task.
// Its raw useInput handler only stops propagation when a selection
// exists — without one, ctrl+c falls through to CancelRequestHandler.
<ScrollKeybindingHandler
scrollRef={scrollRef}
// Yield wheel/ctrl+u/d to UltraplanChoiceDialog's own scroll
// handler while the modal is showing.
isActive={focusedInputDialog !== 'ultraplan-choice'}
// g/G/j/k/ctrl+u/ctrl+d would eat keystrokes the search bar
// wants. Off while searching.
isModal={!searchOpen}
// Manual scroll exits the search context — clear the yellow
// current-match marker. Positions are (msg, rowOffset)-keyed;
// j/k changes scrollTop so rowOffset is stale → wrong row
// gets yellow. Next n/N re-establishes via step()→jump().
onScroll={() => jumpRef.current?.disarmSearch()}
/>
) : null}
<CancelRequestHandler {...cancelRequestProps} />
{transcriptScrollRef ? (
<FullscreenLayout
scrollRef={scrollRef}
scrollable={
<>
{transcriptMessagesElement}
{transcriptToolJSX}
<SandboxViolationExpandedView />
</>
}
bottom={
searchOpen ? (
<TranscriptSearchBar
jumpRef={jumpRef}
// Seed was tried (c01578c8) — broke /hello muscle
// memory (cursor lands after 'foo', /hello → foohello).
// Cancel-restore handles the 'don't lose prior search'
// concern differently (onCancel re-applies searchQuery).
initialQuery=""
count={searchCount}
current={searchCurrent}
onClose={q => {
// Enter — commit. 0-match guard: junk query shouldn't
// persist (badge hidden, n/N dead anyway).
setSearchQuery(searchCount > 0 ? q : '')
setSearchOpen(false)
// onCancel path: bar unmounts before its useEffect([query])
// can fire with ''. Without this, searchCount stays stale
// (n guard at :4956 passes) and VML's matches[] too
// (nextMatch walks the old array). Phantom nav, no
// highlight. onExit (Enter, q non-empty) still commits.
if (!q) {
setSearchCount(0)
setSearchCurrent(0)
jumpRef.current?.setSearchQuery('')
}
}}
onCancel={() => {
// Esc/ctrl+c/ctrl+g — undo. Bar's effect last fired
// with whatever was typed. searchQuery (REPL state)
// is unchanged since / (onClose = commit, didn't run).
// Two VML calls: '' restores anchor (0-match else-
// branch), then searchQuery re-scans from anchor's
// nearest. Both synchronous — one React batch.
// setHighlight explicit: REPL's sync-effect dep is
// searchQuery (unchanged), wouldn't re-fire.
setSearchOpen(false)
jumpRef.current?.setSearchQuery('')
jumpRef.current?.setSearchQuery(searchQuery)
setHighlight(searchQuery)
}}
setHighlight={setHighlight}
/>
) : (
<TranscriptModeFooter
showAllInTranscript={showAllInTranscript}
virtualScroll={true}
status={editorStatus || undefined}
searchBadge={
searchQuery && searchCount > 0
? { current: searchCurrent, count: searchCount }
: undefined
}
/>
)
}
/>
) : (
<>
{transcriptMessagesElement}
{transcriptToolJSX}
<SandboxViolationExpandedView />
<TranscriptModeFooter
showAllInTranscript={showAllInTranscript}
virtualScroll={false}
suppressShowAll={dumpMode}
status={editorStatus || undefined}
/>
</>
)}
</KeybindingSetup>
)
// The virtual-scroll branch (FullscreenLayout above) needs
// <AlternateScreen>'s <Box height={rows}> constraint — without it,
// ScrollBox's flexGrow has no ceiling, viewport = content height,
// scrollTop pins at 0, and Ink's screen buffer sizes to the full
// spacer (200×5k+ rows on long sessions). Same root type + props as
// normal mode's wrap below so React reconciles and the alt buffer
// stays entered across toggle. The 30-cap dump branch stays
// unwrapped — it wants native terminal scrollback.
if (transcriptScrollRef) {
return (
<AlternateScreen mouseTracking={isMouseTrackingEnabled()}>
{transcriptReturn}
</AlternateScreen>
)
}
return transcriptReturn
}
// Get viewed agent task (inlined from selectors for explicit data flow).
// viewedAgentTask: teammate OR local_agent — drives the boolean checks
// below. viewedTeammateTask: teammate-only narrowed, for teammate-specific
// field access (inProgressToolUseIDs).
const viewedTask = viewingAgentTaskId ? tasks[viewingAgentTaskId] : undefined
const viewedTeammateTask =
viewedTask && isInProcessTeammateTask(viewedTask) ? viewedTask : undefined
const viewedAgentTask =
viewedTeammateTask ??
(viewedTask && isLocalAgentTask(viewedTask) ? viewedTask : undefined)
// Bypass useDeferredValue when streaming text is showing so Messages renders
// the final message in the same frame streaming text clears. Also bypass when
// not loading — deferredMessages only matters during streaming (keeps input
// responsive); after the turn ends, showing messages immediately prevents a
// jitter gap where the spinner is gone but the answer hasn't appeared yet.
// Only reducedMotion users keep the deferred path during loading.
const usesSyncMessages = showStreamingText || !isLoading
// When viewing an agent, never fall through to leader — empty until
// bootstrap/stream fills. Closes the see-leader-type-agent footgun.
const displayedMessages = viewedAgentTask
? (viewedAgentTask.messages ?? [])
: usesSyncMessages
? messages
: deferredMessages
// Show the placeholder until the real user message appears in
// displayedMessages. userInputOnProcessing stays set for the whole turn
// (cleared in resetLoadingState); this length check hides it once
// displayedMessages grows past the baseline captured at submit time.
// Covers both gaps: before setMessages is called (processUserInput), and
// while deferredMessages lags behind messages. Suppressed when viewing an
// agent — displayedMessages is a different array there, and onAgentSubmit
// doesn't use the placeholder anyway.
const placeholderText =
userInputOnProcessing &&
!viewedAgentTask &&
displayedMessages.length <= userInputBaselineRef.current
? userInputOnProcessing
: undefined
const toolPermissionOverlay =
focusedInputDialog === 'tool-permission' ? (
<PermissionRequest
key={toolUseConfirmQueue[0]?.toolUseID}
onDone={() => setToolUseConfirmQueue(([_, ...tail]) => tail)}
onReject={handleQueuedCommandOnCancel}
toolUseConfirm={toolUseConfirmQueue[0]!}
toolUseContext={getToolUseContext(
messages,
messages,
abortController ?? createAbortController(),
mainLoopModel,
)}
verbose={verbose}
workerBadge={toolUseConfirmQueue[0]?.workerBadge}
setStickyFooter={
isFullscreenEnvEnabled() ? setPermissionStickyFooter : undefined
}
/>
) : null
// Standalone question overlay (decoupled from the permission system).
// Reuses the AskUserQuestion choice UI but resolves questionService.
const QuestionPromptBox = require('../components/question/QuestionPrompt.js').QuestionPrompt
const questionOverlay =
focusedInputDialog === 'question' && questionRequest ? (
<QuestionPromptBox
key={questionRequest.id}
request={questionRequest}
onResolved={() => setQuestionRequest(null)}
/>
) : null
// Narrow terminals: companion collapses to a one-liner that REPL stacks
// on its own row (above input in fullscreen, below in scrollback) instead
// of row-beside. Wide terminals keep the row layout with sprite on the right.
const companionNarrow = transcriptCols < MIN_COLS_FOR_FULL_SPRITE
// Hide the sprite when PromptInput early-returns BackgroundTasksDialog.
// The sprite sits as a row sibling of PromptInput, so the dialog's Pane
// divider draws at useTerminalSize() width but only gets terminalWidth -
// spriteWidth — divider stops short and dialog text wraps early. Don't
// check footerSelection: pill FOCUS (arrow-down to tasks pill) must keep
// the sprite visible so arrow-right can navigate to it.
const companionVisible =
!toolJSX?.shouldHidePromptInput && !focusedInputDialog && !showBashesDialog
// In fullscreen, ALL local-jsx slash commands float in the modal slot —
// FullscreenLayout wraps them in an absolute-positioned bottom-anchored
// pane (▔ divider, ModalContext). Pane/Dialog inside detect the context
// and skip their own top-level frame. Non-fullscreen keeps the inline
// render paths below. Commands that used to route through bottom
// (immediate: /model, /mcp, /btw, ...) and scrollable (non-immediate:
// /config, /theme, /diff, ...) both go here now.
const toolJsxCentered =
isFullscreenEnvEnabled() && toolJSX?.isLocalJSXCommand === true
const centeredModal: React.ReactNode = toolJsxCentered ? toolJSX!.jsx : null
// <AlternateScreen> at the root: everything below is inside its
// <Box height={rows}>. Handlers/contexts are zero-height so ScrollBox's
// flexGrow in FullscreenLayout resolves against this Box. The transcript
// early return above wraps its virtual-scroll branch the same way; only
// the 30-cap dump branch stays unwrapped for native terminal scrollback.
const mainReturn = (
<KeybindingSetup>
<AnimatedTerminalTitle
isAnimating={titleIsAnimating}
title={terminalTitle}
disabled={titleDisabled}
noPrefix={showStatusInTerminalTab}
/>
<GlobalKeybindingHandlers {...globalKeybindingProps} />
{feature('VOICE_MODE') ? (
<VoiceKeybindingHandler
voiceHandleKeyEvent={voice.handleKeyEvent}
stripTrailing={voice.stripTrailing}
resetAnchor={voice.resetAnchor}
isActive={!toolJSX?.isLocalJSXCommand}
/>
) : null}
<CommandKeybindingHandlers
onSubmit={onSubmit}
isActive={!toolJSX?.isLocalJSXCommand}
/>
{/* ScrollKeybindingHandler must mount before CancelRequestHandler so
ctrl+c-with-selection copies instead of cancelling the active task.
Its raw useInput handler only stops propagation when a selection
exists — without one, ctrl+c falls through to CancelRequestHandler.
PgUp/PgDn/wheel always scroll the transcript behind the modal —
the modal's inner ScrollBox is not keyboard-driven. onScroll
stays suppressed while a modal is showing so scroll doesn't
stamp divider/pill state. */}
<ScrollKeybindingHandler
scrollRef={scrollRef}
isActive={
isFullscreenEnvEnabled() &&
(centeredModal != null ||
!focusedInputDialog ||
focusedInputDialog === 'tool-permission')
}
onScroll={
centeredModal || toolPermissionOverlay || viewedAgentTask
? undefined
: composedOnScroll
}
/>
{feature('MESSAGE_ACTIONS') &&
isFullscreenEnvEnabled() &&
!disableMessageActions ? (
<MessageActionsKeybindings
handlers={messageActionHandlers}
isActive={cursor !== null}
/>
) : null}
<CancelRequestHandler {...cancelRequestProps} />
<MCPConnectionManager
key={remountKey}
dynamicMcpConfig={dynamicMcpConfig}
isStrictMcpConfig={strictMcpConfig}
>
<FullscreenLayout
scrollRef={scrollRef}
overlay={toolPermissionOverlay || questionOverlay}
bottomFloat={
feature('BUDDY') && companionVisible && !companionNarrow ? (
<CompanionFloatingBubble />
) : undefined
}
modal={centeredModal}
modalScrollRef={modalScrollRef}
dividerYRef={dividerYRef}
hidePill={!!viewedAgentTask}
hideSticky={!!viewedTeammateTask}
newMessageCount={unseenDivider?.count ?? 0}
onPillClick={() => {
setCursor(null)
jumpToNew(scrollRef.current)
}}
scrollable={
<>
<TeammateViewHeader />
<Messages
messages={displayedMessages}
tools={tools}
commands={commands}
verbose={verbose}
toolJSX={toolJSX}
toolUseConfirmQueue={toolUseConfirmQueue}
inProgressToolUseIDs={
viewedTeammateTask
? (viewedTeammateTask.inProgressToolUseIDs ?? new Set())
: inProgressToolUseIDs
}
isMessageSelectorVisible={isMessageSelectorVisible}
conversationId={conversationId}
screen={screen}
streamingToolUses={streamingToolUses}
showAllInTranscript={showAllInTranscript}
agentDefinitions={agentDefinitions}
onOpenRateLimitOptions={handleOpenRateLimitOptions}
isLoading={isLoading}
streamingText={
isLoading && !viewedAgentTask ? visibleStreamingText : null
}
isBriefOnly={viewedAgentTask ? false : isBriefOnly}
unseenDivider={viewedAgentTask ? undefined : unseenDivider}
scrollRef={isFullscreenEnvEnabled() ? scrollRef : undefined}
trackStickyPrompt={isFullscreenEnvEnabled() ? true : undefined}
cursor={cursor}
setCursor={setCursor}
cursorNavRef={cursorNavRef}
/>
<AwsAuthStatusBox />
{/* Hide the processing placeholder while a modal is showing —
it would sit at the last visible transcript row right above
the ▔ divider, showing "❯ /config" as redundant clutter
(the modal IS the /config UI). Outside modals it stays so
the user sees their input echoed while Claude processes. */}
{!disabled && placeholderText && !centeredModal && (
<UserTextMessage
param={{ text: placeholderText, type: 'text' }}
addMargin={true}
verbose={verbose}
/>
)}
{toolJSX &&
!(toolJSX.isLocalJSXCommand && toolJSX.isImmediate) &&
!toolJsxCentered && (
<Box flexDirection="column" width="100%">
{toolJSX.jsx}
</Box>
)}
{"external" === 'ant' && <TungstenLiveMonitor />}
{feature('WEB_BROWSER_TOOL')
? WebBrowserPanelModule && (
<WebBrowserPanelModule.WebBrowserPanel />
)
: null}
<Box flexGrow={1} />
{showSpinner && (
<SpinnerWithVerb
mode={streamMode}
spinnerTip={spinnerTip}
responseLengthRef={responseLengthRef}
apiMetricsRef={apiMetricsRef}
overrideMessage={spinnerMessage}
spinnerSuffix={stopHookSpinnerSuffix}
verbose={verbose}
loadingStartTimeRef={loadingStartTimeRef}
totalPausedMsRef={totalPausedMsRef}
pauseStartTimeRef={pauseStartTimeRef}
overrideColor={spinnerColor}
overrideShimmerColor={spinnerShimmerColor}
hasActiveTools={inProgressToolUseIDs.size > 0}
leaderIsIdle={!isLoading}
/>
)}
{!showSpinner &&
!isLoading &&
!userInputOnProcessing &&
!hasRunningTeammates &&
isBriefOnly &&
!viewedAgentTask && <BriefIdleStatus />}
{isFullscreenEnvEnabled() && <PromptInputQueuedCommands />}
</>
}
bottom={
<Box
flexDirection={
feature('BUDDY') && companionNarrow ? 'column' : 'row'
}
width="100%"
alignItems={
feature('BUDDY') && companionNarrow ? undefined : 'flex-end'
}
>
{feature('BUDDY') &&
companionNarrow &&
isFullscreenEnvEnabled() &&
companionVisible ? (
<CompanionSprite />
) : null}
<Box flexDirection="column" flexGrow={1}>
{permissionStickyFooter}
{/* Immediate local-jsx commands (/btw, /sandbox, /assistant,
/issue) render here, NOT inside scrollable. They stay mounted
while the main conversation streams behind them, so ScrollBox
relayouts on each new message would drag them around. bottom
is flexShrink={0} outside the ScrollBox — it never moves.
Non-immediate local-jsx (/diff, /status, /theme, ~40 others)
stays in scrollable: the main loop is paused so no jiggle,
and their tall content (DiffDetailView renders up to 400
lines with no internal scroll) needs the outer ScrollBox. */}
{toolJSX?.isLocalJSXCommand &&
toolJSX.isImmediate &&
!toolJsxCentered && (
<Box flexDirection="column" width="100%">
{toolJSX.jsx}
</Box>
)}
{!showSpinner &&
!toolJSX?.isLocalJSXCommand &&
showExpandedTodos &&
tasksV2 &&
tasksV2.length > 0 && (
<Box width="100%" flexDirection="column">
<TaskListV2 tasks={tasksV2} isStandalone={true} />
</Box>
)}
{focusedInputDialog === 'sandbox-permission' && (
<SandboxPermissionRequest
key={sandboxPermissionRequestQueue[0]!.hostPattern.host}
hostPattern={sandboxPermissionRequestQueue[0]!.hostPattern}
onUserResponse={(response: {
allow: boolean
persistToSettings: boolean
}) => {
const { allow, persistToSettings } = response
const currentRequest = sandboxPermissionRequestQueue[0]
if (!currentRequest) return
const approvedHost = currentRequest.hostPattern.host
if (persistToSettings) {
const update = {
type: 'addRules' as const,
rules: [
{
toolName: WEB_FETCH_TOOL_NAME,
ruleContent: `domain:${approvedHost}`,
},
],
behavior: (allow ? 'allow' : 'deny') as
| 'allow'
| 'deny',
destination: 'localSettings' as const,
}
setAppState(prev => ({
...prev,
toolPermissionContext: applyPermissionUpdate(
prev.toolPermissionContext,
update,
),
}))
persistPermissionUpdate(update)
// Immediately update sandbox in-memory config to prevent race conditions
// where pending requests slip through before settings change is detected
SandboxManager.refreshConfig()
}
// Resolve ALL pending requests for the same host (not just the first one)
// This handles the case where multiple parallel requests came in for the same domain
setSandboxPermissionRequestQueue(queue => {
queue
.filter(
item => item.hostPattern.host === approvedHost,
)
.forEach(item => item.resolvePromise(allow))
return queue.filter(
item => item.hostPattern.host !== approvedHost,
)
})
// Clean up bridge subscriptions and cancel remote prompts
// for this host since the local user already responded.
const cleanups =
sandboxBridgeCleanupRef.current.get(approvedHost)
if (cleanups) {
for (const fn of cleanups) {
fn()
}
sandboxBridgeCleanupRef.current.delete(approvedHost)
}
}}
/>
)}
{focusedInputDialog === 'prompt' && (
<PromptDialog
key={promptQueue[0]!.request.prompt}
title={promptQueue[0]!.title}
toolInputSummary={promptQueue[0]!.toolInputSummary}
request={promptQueue[0]!.request}
onRespond={selectedKey => {
const item = promptQueue[0]
if (!item) return
item.resolve({
prompt_response: item.request.prompt,
selected: selectedKey,
})
setPromptQueue(([, ...tail]) => tail)
}}
onAbort={() => {
const item = promptQueue[0]
if (!item) return
item.reject(new Error('Prompt cancelled by user'))
setPromptQueue(([, ...tail]) => tail)
}}
/>
)}
{/* Show pending indicator on worker while waiting for leader approval */}
{pendingWorkerRequest && (
<WorkerPendingPermission
toolName={pendingWorkerRequest.toolName}
description={pendingWorkerRequest.description}
/>
)}
{/* Show pending indicator for sandbox permission on worker side */}
{pendingSandboxRequest && (
<WorkerPendingPermission
toolName="Network Access"
description={`Waiting for leader to approve network access to ${pendingSandboxRequest.host}`}
/>
)}
{/* Worker sandbox permission requests from swarm workers */}
{focusedInputDialog === 'worker-sandbox-permission' && (
<SandboxPermissionRequest
key={workerSandboxPermissions.queue[0]!.requestId}
hostPattern={
{
host: workerSandboxPermissions.queue[0]!.host,
port: undefined,
} as NetworkHostPattern
}
onUserResponse={(response: {
allow: boolean
persistToSettings: boolean
}) => {
const { allow, persistToSettings } = response
const currentRequest = workerSandboxPermissions.queue[0]
if (!currentRequest) return
const approvedHost = currentRequest.host
// Send response via mailbox to the worker
void sendSandboxPermissionResponseViaMailbox(
currentRequest.workerName,
currentRequest.requestId,
approvedHost,
allow,
teamContext?.teamName,
)
if (persistToSettings && allow) {
const update = {
type: 'addRules' as const,
rules: [
{
toolName: WEB_FETCH_TOOL_NAME,
ruleContent: `domain:${approvedHost}`,
},
],
behavior: 'allow' as const,
destination: 'localSettings' as const,
}
setAppState(prev => ({
...prev,
toolPermissionContext: applyPermissionUpdate(
prev.toolPermissionContext,
update,
),
}))
persistPermissionUpdate(update)
SandboxManager.refreshConfig()
}
// Remove from queue
setAppState(prev => ({
...prev,
workerSandboxPermissions: {
...prev.workerSandboxPermissions,
queue: prev.workerSandboxPermissions.queue.slice(1),
},
}))
}}
/>
)}
{focusedInputDialog === 'elicitation' && (
<ElicitationDialog
key={
elicitation.queue[0]!.serverName +
':' +
String(elicitation.queue[0]!.requestId)
}
event={elicitation.queue[0]!}
onResponse={(action, content) => {
const currentRequest = elicitation.queue[0]
if (!currentRequest) return
// Call respond callback to resolve Promise
currentRequest.respond({ action, content })
// For URL accept, keep in queue for phase 2
const isUrlAccept =
currentRequest.params.mode === 'url' &&
action === 'accept'
if (!isUrlAccept) {
setAppState(prev => ({
...prev,
elicitation: {
queue: prev.elicitation.queue.slice(1),
},
}))
}
}}
onWaitingDismiss={action => {
const currentRequest = elicitation.queue[0]
// Remove from queue
setAppState(prev => ({
...prev,
elicitation: {
queue: prev.elicitation.queue.slice(1),
},
}))
currentRequest?.onWaitingDismiss?.(action)
}}
/>
)}
{focusedInputDialog === 'cost' && (
<CostThresholdDialog
onDone={() => {
setShowCostDialog(false)
setHaveShownCostDialog(true)
saveGlobalConfig(current => ({
...current,
hasAcknowledgedCostThreshold: true,
}))
logEvent('tengu_cost_threshold_acknowledged', {})
}}
/>
)}
{focusedInputDialog === 'idle-return' && idleReturnPending && (
<IdleReturnDialog
idleMinutes={idleReturnPending.idleMinutes}
totalInputTokens={getTotalInputTokens()}
onDone={async action => {
const pending = idleReturnPending
setIdleReturnPending(null)
logEvent('tengu_idle_return_action', {
action:
action as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
idleMinutes: Math.round(pending.idleMinutes),
messageCount: messagesRef.current.length,
totalInputTokens: getTotalInputTokens(),
})
if (action === 'dismiss') {
setInputValue(pending.input)
return
}
if (action === 'never') {
saveGlobalConfig(current => {
if (current.idleReturnDismissed) return current
return { ...current, idleReturnDismissed: true }
})
}
if (action === 'clear') {
const { clearConversation } = await import(
'../commands/clear/conversation.js'
)
await clearConversation({
setMessages,
readFileState: readFileState.current,
discoveredSkillNames: discoveredSkillNamesRef.current,
loadedNestedMemoryPaths:
loadedNestedMemoryPathsRef.current,
getAppState: () => store.getState(),
setAppState,
setConversationId,
})
titleGenerationAttemptedRef.current = false
setAutoGeneratedTitle(undefined)
bashTools.current.clear()
bashToolsProcessedIdx.current = 0
}
skipIdleCheckRef.current = true
void onSubmitRef.current(pending.input, {
setCursorOffset: () => {},
clearBuffer: () => {},
resetHistory: () => {},
})
}}
/>
)}
{focusedInputDialog === 'ide-onboarding' && (
<IdeOnboardingDialog
onDone={() => setShowIdeOnboarding(false)}
installationStatus={ideInstallationStatus}
/>
)}
{"external" === 'ant' &&
focusedInputDialog === 'model-switch' &&
AntModelSwitchCallout && (
<AntModelSwitchCallout
onDone={(selection: string, modelAlias?: string) => {
setShowModelSwitchCallout(false)
if (selection === 'switch' && modelAlias) {
setAppState(prev => ({
...prev,
mainLoopModel: modelAlias,
mainLoopModelForSession: null,
}))
}
}}
/>
)}
{"external" === 'ant' &&
focusedInputDialog === 'undercover-callout' &&
UndercoverAutoCallout && (
<UndercoverAutoCallout
onDone={() => setShowUndercoverCallout(false)}
/>
)}
{focusedInputDialog === 'effort-callout' && (
<EffortCallout
model={mainLoopModel}
onDone={selection => {
setShowEffortCallout(false)
if (selection !== 'dismiss') {
setAppState(prev => ({
...prev,
effortValue: selection,
}))
}
}}
/>
)}
{focusedInputDialog === 'remote-callout' && (
<RemoteCallout
onDone={selection => {
setAppState(prev => {
if (!prev.showRemoteCallout) return prev
return {
...prev,
showRemoteCallout: false,
...(selection === 'enable' && {
replBridgeEnabled: true,
replBridgeExplicit: true,
replBridgeOutboundOnly: false,
}),
}
})
}}
/>
)}
{exitFlow}
{focusedInputDialog === 'plugin-hint' && hintRecommendation && (
<PluginHintMenu
pluginName={hintRecommendation.pluginName}
pluginDescription={hintRecommendation.pluginDescription}
marketplaceName={hintRecommendation.marketplaceName}
sourceCommand={hintRecommendation.sourceCommand}
onResponse={handleHintResponse}
/>
)}
{focusedInputDialog === 'lsp-recommendation' &&
lspRecommendation && (
<LspRecommendationMenu
pluginName={lspRecommendation.pluginName}
pluginDescription={lspRecommendation.pluginDescription}
fileExtension={lspRecommendation.fileExtension}
onResponse={handleLspResponse}
/>
)}
{focusedInputDialog === 'desktop-upsell' && (
<DesktopUpsellStartup
onDone={() => setShowDesktopUpsellStartup(false)}
/>
)}
{feature('ULTRAPLAN')
? focusedInputDialog === 'ultraplan-choice' &&
ultraplanPendingChoice && (
<UltraplanChoiceDialog
plan={ultraplanPendingChoice.plan}
sessionId={ultraplanPendingChoice.sessionId}
taskId={ultraplanPendingChoice.taskId}
setMessages={setMessages}
readFileState={readFileState.current}
getAppState={() => store.getState()}
setConversationId={setConversationId}
/>
)
: null}
{feature('ULTRAPLAN')
? focusedInputDialog === 'ultraplan-launch' &&
ultraplanLaunchPending && (
<UltraplanLaunchDialog
onChoice={(choice, opts) => {
const blurb = ultraplanLaunchPending.blurb
setAppState(prev =>
prev.ultraplanLaunchPending
? { ...prev, ultraplanLaunchPending: undefined }
: prev,
)
if (choice === 'cancel') return
// Command's onDone used display:'skip', so add the
// echo here — gives immediate feedback before the
// ~5s teleportToRemote resolves.
setMessages(prev => [
...prev,
createCommandInputMessage(
formatCommandInputTags('ultraplan', blurb),
),
])
const appendStdout = (msg: string) =>
setMessages(prev => [
...prev,
createCommandInputMessage(
`<${LOCAL_COMMAND_STDOUT_TAG}>${escapeXml(msg)}</${LOCAL_COMMAND_STDOUT_TAG}>`,
),
])
// Defer the second message if a query is mid-turn
// so it lands after the assistant reply, not
// between the user's prompt and the reply.
const appendWhenIdle = (msg: string) => {
if (!queryGuard.isActive) {
appendStdout(msg)
return
}
const unsub = queryGuard.subscribe(() => {
if (queryGuard.isActive) return
unsub()
// Skip if the user stopped ultraplan while we
// were waiting — avoids a stale "Monitoring
// <url>" message for a session that's gone.
if (!store.getState().ultraplanSessionUrl) return
appendStdout(msg)
})
}
void launchUltraplan({
blurb,
getAppState: () => store.getState(),
setAppState,
signal: createAbortController().signal,
disconnectedBridge: opts?.disconnectedBridge,
onSessionReady: appendWhenIdle,
})
.then(appendStdout)
.catch(logError)
}}
/>
)
: null}
{mrRender()}
{!toolJSX?.shouldHidePromptInput &&
!focusedInputDialog &&
!isExiting &&
!disabled &&
!cursor && (
<>
{autoRunIssueReason && (
<AutoRunIssueNotification
onRun={handleAutoRunIssue}
onCancel={handleCancelAutoRunIssue}
reason={getAutoRunIssueReasonText(autoRunIssueReason)}
/>
)}
{postCompactSurvey.state !== 'closed' ? (
<FeedbackSurvey
state={postCompactSurvey.state}
lastResponse={postCompactSurvey.lastResponse}
handleSelect={postCompactSurvey.handleSelect}
inputValue={inputValue}
setInputValue={setInputValue}
onRequestFeedback={handleSurveyRequestFeedback}
/>
) : memorySurvey.state !== 'closed' ? (
<FeedbackSurvey
state={memorySurvey.state}
lastResponse={memorySurvey.lastResponse}
handleSelect={memorySurvey.handleSelect}
handleTranscriptSelect={
memorySurvey.handleTranscriptSelect
}
inputValue={inputValue}
setInputValue={setInputValue}
onRequestFeedback={handleSurveyRequestFeedback}
message="How well did Claude use its memory? (optional)"
/>
) : (
<FeedbackSurvey
state={feedbackSurvey.state}
lastResponse={feedbackSurvey.lastResponse}
handleSelect={feedbackSurvey.handleSelect}
handleTranscriptSelect={
feedbackSurvey.handleTranscriptSelect
}
inputValue={inputValue}
setInputValue={setInputValue}
onRequestFeedback={
didAutoRunIssueRef.current
? undefined
: handleSurveyRequestFeedback
}
/>
)}
{/* Frustration-triggered transcript sharing prompt */}
{frustrationDetection.state !== 'closed' && (
<FeedbackSurvey
state={frustrationDetection.state}
lastResponse={null}
handleSelect={() => {}}
handleTranscriptSelect={
frustrationDetection.handleTranscriptSelect
}
inputValue={inputValue}
setInputValue={setInputValue}
/>
)}
{/* Skill improvement survey - appears when improvements detected (ant-only) */}
{"external" === 'ant' &&
skillImprovementSurvey.suggestion && (
<SkillImprovementSurvey
isOpen={skillImprovementSurvey.isOpen}
skillName={
skillImprovementSurvey.suggestion.skillName
}
updates={skillImprovementSurvey.suggestion.updates}
handleSelect={skillImprovementSurvey.handleSelect}
inputValue={inputValue}
setInputValue={setInputValue}
/>
)}
{showIssueFlagBanner && <IssueFlagBanner />}
{
}
<PromptInput
debug={debug}
ideSelection={ideSelection}
hasSuppressedDialogs={!!hasSuppressedDialogs}
isLocalJSXCommandActive={isShowingLocalJSXCommand}
getToolUseContext={getToolUseContext}
toolPermissionContext={toolPermissionContext}
setToolPermissionContext={setToolPermissionContext}
apiKeyStatus={apiKeyStatus}
commands={commands}
agents={agentDefinitions.activeAgents}
isLoading={isLoading}
onExit={handleExit}
verbose={verbose}
messages={messages}
onAutoUpdaterResult={setAutoUpdaterResult}
autoUpdaterResult={autoUpdaterResult}
input={inputValue}
onInputChange={setInputValue}
mode={inputMode}
onModeChange={setInputMode}
stashedPrompt={stashedPrompt}
setStashedPrompt={setStashedPrompt}
submitCount={submitCount}
onShowMessageSelector={handleShowMessageSelector}
onMessageActionsEnter={
// Works during isLoading — edit cancels first; uuid selection survives appends.
feature('MESSAGE_ACTIONS') &&
isFullscreenEnvEnabled() &&
!disableMessageActions
? enterMessageActions
: undefined
}
mcpClients={mcpClients}
pastedContents={pastedContents}
setPastedContents={setPastedContents}
vimMode={vimMode}
setVimMode={setVimMode}
showBashesDialog={showBashesDialog}
setShowBashesDialog={setShowBashesDialog}
onSubmit={onSubmit}
onAgentSubmit={onAgentSubmit}
isSearchingHistory={isSearchingHistory}
setIsSearchingHistory={setIsSearchingHistory}
helpOpen={isHelpOpen}
setHelpOpen={setIsHelpOpen}
insertTextRef={
feature('VOICE_MODE') ? insertTextRef : undefined
}
voiceInterimRange={voice.interimRange}
/>
<SessionBackgroundHint
onBackgroundSession={handleBackgroundSession}
isLoading={isLoading}
/>
</>
)}
{cursor && (
// inputValue is REPL state; typed text survives the round-trip.
<MessageActionsBar cursor={cursor} />
)}
{focusedInputDialog === 'message-selector' && (
<MessageSelector
messages={messages}
preselectedMessage={messageSelectorPreselect}
onPreRestore={onCancel}
onRestoreCode={async (message: UserMessage) => {
await fileHistoryRewind(
(
updater: (prev: FileHistoryState) => FileHistoryState,
) => {
setAppState(prev => ({
...prev,
fileHistory: updater(prev.fileHistory),
}))
},
message.uuid,
)
}}
onSummarize={async (
message: UserMessage,
feedback?: string,
direction: PartialCompactDirection = 'from',
) => {
// Project snipped messages so the compact model
// doesn't summarize content that was intentionally removed.
const compactMessages =
getMessagesAfterCompactBoundary(messages)
const messageIndex = compactMessages.indexOf(message)
if (messageIndex === -1) {
// Selected a snipped or pre-compact message that the
// selector still shows (REPL keeps full history for
// scrollback). Surface why nothing happened instead
// of silently no-oping.
setMessages(prev => [
...prev,
createSystemMessage(
'That message is no longer in the active context (snipped or pre-compact). Choose a more recent message.',
'warning',
),
])
return
}
const newAbortController = createAbortController()
const context = getToolUseContext(
compactMessages,
[],
newAbortController,
mainLoopModel,
)
const appState = context.getAppState()
const defaultSysPrompt = await getSystemPrompt(
context.options.tools,
context.options.mainLoopModel,
Array.from(
appState.toolPermissionContext.additionalWorkingDirectories.keys(),
),
context.options.mcpClients,
)
const systemPrompt = buildEffectiveSystemPrompt({
mainThreadAgentDefinition: undefined,
toolUseContext: context,
customSystemPrompt: context.options.customSystemPrompt,
defaultSystemPrompt: defaultSysPrompt,
appendSystemPrompt: context.options.appendSystemPrompt,
})
const [userContext, systemContext] = await Promise.all([
getUserContext(),
getSystemContext(),
])
const result = await partialCompactConversation(
compactMessages,
messageIndex,
context,
{
systemPrompt,
userContext,
systemContext,
toolUseContext: context,
forkContextMessages: compactMessages,
},
feedback,
direction,
)
const kept = result.messagesToKeep ?? []
const ordered =
direction === 'up_to'
? [...result.summaryMessages, ...kept]
: [...kept, ...result.summaryMessages]
const postCompact = [
result.boundaryMarker,
...ordered,
...result.attachments,
...result.hookResults,
]
// Fullscreen 'from' keeps scrollback; 'up_to' must not
// (old[0] unchanged + grown array means incremental
// useLogMessages path, so boundary never persisted).
// Find by uuid since old is raw REPL history and snipped
// entries can shift the projected messageIndex.
if (isFullscreenEnvEnabled() && direction === 'from') {
setMessages(old => {
const rawIdx = old.findIndex(
m => m.uuid === message.uuid,
)
return [
...old.slice(0, rawIdx === -1 ? 0 : rawIdx),
...postCompact,
]
})
} else {
setMessages(postCompact)
}
// Partial compact bypasses handleMessageFromStream — clear
// the context-blocked flag so proactive ticks resume.
if (feature('PROACTIVE') || feature('KAIROS')) {
proactiveModule?.setContextBlocked(false)
}
setConversationId(randomUUID())
runPostCompactCleanup(context.options.querySource)
if (direction === 'from') {
const r = textForResubmit(message)
if (r) {
setInputValue(r.text)
setInputMode(r.mode)
}
}
// Show notification with ctrl+o hint
const historyShortcut = getShortcutDisplay(
'app:toggleTranscript',
'Global',
'ctrl+o',
)
addNotification({
key: 'summarize-ctrl-o-hint',
text: `Conversation summarized (${historyShortcut} for history)`,
priority: 'medium',
timeoutMs: 8000,
})
}}
onRestoreMessage={handleRestoreMessage}
onClose={() => {
setIsMessageSelectorVisible(false)
setMessageSelectorPreselect(undefined)
}}
/>
)}
{"external" === 'ant' && <DevBar />}
</Box>
{feature('BUDDY') &&
!(companionNarrow && isFullscreenEnvEnabled()) &&
companionVisible ? (
<CompanionSprite />
) : null}
</Box>
}
/>
</MCPConnectionManager>
</KeybindingSetup>
)
if (isFullscreenEnvEnabled()) {
return (
<AlternateScreen mouseTracking={isMouseTrackingEnabled()}>
{mainReturn}
</AlternateScreen>
)
}
return mainReturn
}
|