Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 13x 13x 13x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 13x 93x 279x 13x 8x 13x 13x 13x 548x 548x 13x 252x 252x 252x 13x 283x 546x 283x 241x 241x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 241x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 241x 241x 13x 13x 548x 548x 548x 548x 375x 548x 548x 13x 1279x 13x 23x 23x 23x 138x 138x 138x 4x 4x 13x 23x 8x 23x 8x 13x 11x 11x 11x 11x 11x 11x 13x 114x 114x 114x 114x 13x 548x 548x 548x 548x 548x 548x 548x 548x 296x 252x 252x 252x 548x 548x 548x 548x 548x 548x 548x 2x 13x 543x 13x 406x 406x 13x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 129x 1110x 163x 1110x 1110x 1110x 1110x 1110x 408x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 1110x 108x 108x 13x 13x 13x 1110x 153x 1110x 406x 1110x 163x 1110x 138x 15x 138x 138x 1110x 406x 406x 1110x 108x 108x 108x 108x 108x 108x 1110x 187x 185x 1110x 183x 2x 1110x 14x 14x 14x 14x 14x 14x 14x 14x 1110x 9x 9x 9x 9x 1110x 1110x 2x 2x 2x 2x 1110x 1110x 2x 2x 1110x 2x 2x 1110x 7x 7x 1110x 1110x 265x 265x 257x 1110x 34x 1110x 31x 28x 7x 2x 2x 2x 1x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 21x 21x 21x 21x 1x 1x 20x 20x 20x 20x 1110x 645x 645x 645x 488x 157x 1110x 275x 1x 1x 1x 1x 1x 274x 155x 155x 155x 5x 5x 5x 150x 2x 2x 2x 267x 29x 29x 1110x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1110x 1110x 1110x 1110x 645x 7x 3x 5x 1x 3x 1x 1x 265x 1x | import CitationRow from "@/components/chat/Citations/CitationRow";
import {
DocumentDownloader,
DocumentDownloadProvider,
DocumentImageUrl,
} from "@/components/document";
import { useApiHandler } from "@/services/useApiHandler";
import ExecutionPipeline from "@/components/chat/ExecutionPipeline/ExecutionPipeline";
import {
ChatMessage,
Citation,
GraphPlanStage,
NodeExecution,
TraceEvent,
} from "@/objects/Model";
import { planFromTrace } from "@/util/pipelineUtils";
import { groupTraceByNode, hitlFromTrace } from "@/util/traceUtils";
import HumanInputRecord from "@/components/chat/HumanInput/HumanInputRecord";
import { NodeHitl, exchangeToNodeHitl } from "@/objects/Hitl";
import type { UploadedFileRef } from "@/services/api/routers/FileRouter";
import DocumentsPanel from "@/components/chat/DocumentsPanel/DocumentsPanel";
import ComposerMenu from "@/components/chat/ChatPanel/ComposerMenu";
import AttachMenu, {
type AttachItemsProps,
} from "@/components/chat/ChatPanel/AttachMenu";
import WithheldNote from "@/components/chat/ChatPanel/WithheldNote";
import WebSourcesNote from "@/components/chat/ChatPanel/WebSourcesNote";
import { useElementWidth } from "@/hooks/useElementWidth";
import { useWorkspace } from "@/context/WorkspaceContext";
import { errorDetail } from "@/util/apiError";
import SaveToDashboard from "@/components/dashboard/SaveToDashboard";
import SaveAsPdfButton from "@/components/chat/ExportPdf/SaveAsPdfButton";
import AIGeneratedBadge from "@/components/badge/AIGeneratedBadge";
import QualityCheckBadge from "@/components/chat/QualityCheck/QualityCheckBadge";
import CommandPalette, {
optionId,
} from "@/components/chat/CommandPalette/CommandPalette";
import CommandForm, {
CommandToken,
} from "@/components/chat/CommandForm/CommandForm";
import SentCommand from "@/components/chat/CommandForm/SentCommand";
import SentAttachments from "./SentAttachments";
import type { ChatCommandSpec } from "@/objects/ChatCommand";
import { AI_DISCLOSURE } from "@/util/aiDisclosure";
import {
COMMAND_PREFIX,
type CommandEntry,
type CommandSubmission,
commandBlockers,
commandReady,
commandText,
matchCommand,
paletteEntries,
requestRequired,
tokenizeCommand,
} from "@/util/chatCommands";
import {
type FormValue,
type FormValues,
initialValues,
toInputs,
} from "@/util/runForm";
import {
Activity,
AlignLeft,
Bot,
Braces,
Check,
CheckCircle2,
Code2,
Coins,
Copy,
Cpu,
Download,
FileCode,
FileJson2,
FileText,
Gavel,
Loader2,
Paperclip,
ScanSearch,
Send,
Settings2,
Slash,
Sparkles,
Square,
Table2,
Terminal,
Thermometer,
X,
Zap,
} from "lucide-react";
import moment from "moment";
import { Link } from "react-router-dom";
import { decisionHref } from "@/routes/resourceHref";
import VerdictBar from "@/components/decisions/VerdictBar";
import { needsAttention } from "@/util/decisionAttention";
import React, { useEffect, useId, useMemo, useRef, useState } from "react";
import RichMarkdown from "@/components/chat/RichMarkdown/RichMarkdown";
import { parseServerDate } from "@/util/time";
import { CostFigure, describeCost } from "@/components/cost";
export type { NodeExecution, UploadedFileRef };
// ─── Types ────────────────────────────────────────────────────────────────────
export type OutputFormat =
"markdown" | "plain" | "json" | "yaml" | "csv" | "xml";
export interface OutputFormatConfig {
format: OutputFormat;
schema: string;
}
export interface ChatSettings {
temperature: number;
thinking: boolean;
systemPrompt: string;
outputFormat: OutputFormatConfig;
}
const DEFAULT_SETTINGS: ChatSettings = {
temperature: 0.7,
thinking: false,
systemPrompt: "",
outputFormat: { format: "markdown", schema: "" },
};
const FORMAT_OPTIONS: {
value: OutputFormat;
label: string;
icon: React.ElementType;
description: string;
hasSchema: boolean;
}[] = [
{
value: "markdown",
label: "Markdown",
icon: FileText,
description:
"Rich formatted text with headers, lists, and code blocks. The default response format.",
hasSchema: false,
},
{
value: "json",
label: "JSON",
icon: Braces,
description:
"Structured JSON data. Provide an optional JSON Schema to enforce the output shape.",
hasSchema: true,
},
{
value: "yaml",
label: "YAML",
icon: Code2,
description:
"Human-readable YAML. Provide an optional schema to enforce the output structure.",
hasSchema: true,
},
{
value: "csv",
label: "CSV",
icon: Table2,
description: "Tabular data as comma-separated values with a header row.",
hasSchema: false,
},
{
value: "xml",
label: "XML",
icon: FileCode,
description: "Well-formed XML markup.",
hasSchema: false,
},
{
value: "plain",
label: "Plain Text",
icon: AlignLeft,
description:
"Plain text without markdown, headers, bullet points, or code blocks.",
hasSchema: false,
},
];
export interface ChatPanelProps {
messages: ChatMessage[];
displayName: string;
loading: boolean;
/** When this value changes, attached files are cleared. */
conversationId?: string | null;
/** A persisted message id to scroll to and ring, from a `?message=` deep
* link. The Activity and Governance → Rules → Activity pages link to the
* exact message a run or a rule acted on, rather than to the conversation
* and leaving the reader to find it. */
highlightMessageId?: string | null;
/** Optional live status text shown while loading */
statusMessage?: string;
/** Tokens streamed so far; renders a live assistant bubble when non-empty */
streamingContent?: string;
/** Citations accumulated so far during a streaming response */
streamingCitations?: Citation[];
/** Ordered list of all status messages received during the current execution */
executionSteps?: string[];
/** Per-node execution data for multi-agent graph runs */
nodeExecutions?: NodeExecution[];
/**
* Stage plan announced by svc-ai at the start of a graph run, so the whole
* pipeline is drawn before the first node reports in.
*/
graphPlan?: GraphPlanStage[];
/** `command` is the chat command being sent, when there is one: `message`
* is then its line and free text, and `command` carries its form's values
* (svc-core's `command_inputs`). */
onSubmit: (
message: string,
attachedFiles: UploadedFileRef[],
settings: ChatSettings,
command?: CommandSubmission,
) => Promise<void>;
/** Called when the user picks a file; should upload it and return a ref. */
onUploadFile?: (file: File) => Promise<UploadedFileRef | null>;
/** Previously uploaded documents available for re-attachment. */
documents?: UploadedFileRef[];
/** Called when a document is deleted from the library. */
onDeleteDocument?: (id: string) => void;
placeholder?: string;
supportsTemperature?: boolean;
supportsThinking?: boolean;
supportsSystemPrompt?: boolean;
/** Called when the user clicks the stop button during a loading response. */
onStop?: () => void;
/** The turn is waiting on the person (a question or an approval), so
* leaving would not get them an answer. */
paused?: boolean;
/** Grow to the height of a flex-column parent instead of capping the
* thread at 60vh — `ChatLayout` beside the list, on the page and in full
* screen. */
fill?: boolean;
/** The chat commands this chat offers (svc-core's catalogue). With any,
* a typed `/` opens the command palette, and a chosen command becomes a
* token in the message box with its target's form above it. */
commands?: ChatCommandSpec[];
/** Put the caret in the message box when the panel mounts — the chat
* dock, opened by a person who means to type. Only while nothing else
* holds focus (the page itself, or the frame the chat sits in), so a
* chat mounting never takes the caret from a field on the page. */
autoFocus?: boolean;
className?: string;
}
// ─── Execution phase detection ────────────────────────────────────────────────
type ExecutionPhase =
| "connecting"
| "preparing"
| "running"
| "tool"
| "generating"
| "saving"
| "streaming";
interface PhaseConfig {
icon: React.ReactNode;
label: string;
dotClass: string;
iconClass: string;
bgClass: string;
}
const PHASE_CONFIG: Record<ExecutionPhase, PhaseConfig> = {
connecting: {
icon: null,
label: "Connecting",
dotClass: "bg-gray-400 dark:bg-gray-500",
iconClass: "",
bgClass: "",
},
preparing: {
icon: <Cpu className="w-3.5 h-3.5" />,
label: "Preparing",
dotClass: "bg-blue-400",
iconClass: "text-blue-500 dark:text-blue-400",
bgClass:
"bg-blue-50 dark:bg-blue-950/30 border-blue-100 dark:border-blue-900/40",
},
running: {
icon: <Activity className="w-3.5 h-3.5" />,
label: "Running",
dotClass: "bg-emerald-400",
iconClass: "text-emerald-500 dark:text-emerald-400",
bgClass:
"bg-emerald-50 dark:bg-emerald-950/30 border-emerald-100 dark:border-emerald-900/40",
},
tool: {
icon: <Zap className="w-3.5 h-3.5" />,
label: "Tool",
dotClass: "bg-amber-400",
iconClass: "text-amber-500 dark:text-amber-400",
bgClass:
"bg-amber-50 dark:bg-amber-950/30 border-amber-100 dark:border-amber-900/40",
},
generating: {
icon: <Sparkles className="w-3.5 h-3.5" />,
label: "Generating",
dotClass: "bg-violet-400",
iconClass: "text-violet-500 dark:text-violet-400",
bgClass:
"bg-violet-50 dark:bg-violet-950/30 border-violet-100 dark:border-violet-900/40",
},
saving: {
icon: <CheckCircle2 className="w-3.5 h-3.5" />,
label: "Saving",
dotClass: "bg-gray-400",
iconClass: "text-gray-400 dark:text-gray-500",
bgClass:
"bg-gray-50 dark:bg-gray-800/50 border-gray-100 dark:border-gray-700",
},
streaming: {
icon: <Sparkles className="w-3.5 h-3.5" />,
label: "Streaming",
dotClass: "bg-violet-400",
iconClass: "text-violet-500",
bgClass: "",
},
};
function detectPhase(raw: string): ExecutionPhase {
const m = raw.toLowerCase();
Iif (m.includes("saving") || m.includes("finishing")) return "saving";
Iif (m.includes("using tool")) return "tool";
Iif (
m.startsWith("running") &&
!m.includes("skill") &&
!m.includes("with tools")
)
return "running";
Iif (m.includes("skill") || m.includes("with tools")) return "running";
Iif (m.includes("sending to") || m.includes("generat")) return "generating";
return "preparing";
}
function friendlyLabel(raw: string): string {
const m = raw.toLowerCase();
Iif (m.includes("saving conversation")) return "Finishing up";
Iif (m.includes("resolving model")) return "Preparing model";
Iif (m.includes("using tool: web_search")) return "Searching the web";
Iif (m.includes("using tool: query_knowledge_base"))
return "Querying knowledge base";
Iif (m.includes("using tool:")) {
const name = raw
.replace(/using tool:\s*/i, "")
.replace(/…$/, "")
.trim();
return `Using ${name}`;
}
Iif (m.includes("running skill:")) {
const name = raw
.replace(/running skill:\s*/i, "")
.replace(/…$/, "")
.trim();
return `Skill: ${name}`;
}
Iif (m.includes("sending to")) return "Generating response";
Iif (m.startsWith("starting")) return "Initializing";
Iif (m.startsWith("running ")) {
const name = raw
.replace(/^running\s*/i, "")
.replace(/…$/, "")
.trim();
return `Running: ${name}`;
}
return raw.replace(/…$/, "");
}
// ─── Small helpers ────────────────────────────────────────────────────────────
const TypingDots: React.FC = () => (
<div className="flex items-center gap-1 py-0.5">
{[0, 1, 2].map((i) => (
<span
key={i}
className="inline-block w-1.5 h-1.5 rounded-full bg-gray-400 dark:bg-gray-500"
style={{
animation: `chatBounce 1.2s ease-in-out ${i * 0.2}s infinite`,
}}
/>
))}
</div>
);
const FileChip: React.FC<{
name: string;
uploading?: boolean;
onRemove?: () => void;
}> = ({ name, uploading, onRemove }) => (
<div
// A long PDF takes a minute or more to read; Send waits for it.
title={uploading ? `Reading ${name}. Send waits until it's ready.` : undefined}
className="flex items-center gap-1.5 pl-2.5 pr-1.5 py-1 rounded-full bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 text-xs font-medium border border-indigo-200 dark:border-indigo-800"
>
{uploading ? (
<Loader2 className="w-3 h-3 shrink-0 animate-spin" />
) : (
<Paperclip className="w-3 h-3 shrink-0" />
)}
<span className="max-w-[140px] truncate">{name}</span>
{!uploading && onRemove && (
<button
onClick={onRemove}
className="ml-0.5 rounded-full p-0.5 hover:bg-indigo-200 dark:hover:bg-indigo-800 transition-colors"
>
<X className="w-3 h-3" />
</button>
)}
</div>
);
const Toggle: React.FC<{
checked: boolean;
onChange: (v: boolean) => void;
label: string;
description?: string;
}> = ({ checked, onChange, label, description }) => (
<label className="flex items-start gap-3 cursor-pointer">
<div className="relative mt-0.5">
<input
type="checkbox"
className="sr-only"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
/>
<div
className={`w-9 h-5 rounded-full transition-colors ${
checked ? "bg-indigo-500" : "bg-gray-300 dark:bg-gray-600"
}`}
/>
<div
className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${
checked ? "translate-x-4" : ""
}`}
/>
</div>
<div>
<p className="text-sm font-medium text-gray-800 dark:text-gray-200">
{label}
</p>
{description && (
<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
{description}
</p>
)}
</div>
</label>
);
// ─── Shared action-button style ───────────────────────────────────────────────
const ACTION_BTN =
"flex items-center gap-1 p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors";
// ─── Copy Button ─────────────────────────────────────────────────────────────
const CopyButton: React.FC<{ text: string; className?: string }> = ({
text,
className = "",
}) => {
const [copied, setCopied] = useState(false);
return (
<button
onClick={() =>
void navigator.clipboard.writeText(text).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
})
}
title={copied ? "Copied!" : "Copy"}
className={`${ACTION_BTN} ${className}`}
>
{copied ? (
<Check className="w-3.5 h-3.5 text-emerald-500" />
) : (
<Copy className="w-3.5 h-3.5" />
)}
</button>
);
};
// ─── Copy Raw Button (extracts inner content from code fences) ─────────────────
const CopyRawButton: React.FC<{ text: string }> = ({ text }) => {
const [copied, setCopied] = useState(false);
const fenceMatch = /^```[^\n]*\n([\s\S]+?)\n```\s*$/m.exec(text.trim());
Eif (!fenceMatch) return null;
const raw = fenceMatch[1];
return (
<button
onClick={() =>
void navigator.clipboard.writeText(raw).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
})
}
title={copied ? "Copied raw content!" : "Copy raw content"}
className={ACTION_BTN}
>
{copied ? (
<Check className="w-3.5 h-3.5 text-emerald-500" />
) : (
<Code2 className="w-3.5 h-3.5" />
)}
</button>
);
};
// ─── Conversation Toolbar ─────────────────────────────────────────────────────
const ConversationToolbar: React.FC<{
messages: ChatMessage[];
displayName: string;
conversationId?: string | null;
/** The rendered thread, printed as-is for the conversation-wide PDF. */
threadRef: React.RefObject<HTMLElement | null>;
}> = ({ messages, displayName, conversationId, threadRef }) => {
const [copyIdDone, setCopyIdDone] = useState(false);
const count = messages.filter((m) => m.role !== "system").length;
if (count === 0) return null;
const slug = displayName.toLowerCase().replace(/\s+/g, "-");
const handleDownloadMd = () => {
const lines: string[] = [
`# Chat with ${displayName}`,
``,
`*Exported ${new Date().toLocaleDateString()}*`,
``,
`> ${AI_DISCLOSURE.document}`,
``,
`---`,
``,
];
for (const msg of messages) {
Iif (msg.role === "system") continue;
lines.push(msg.role === "user" ? `**You**` : `**${displayName}**`);
Iif (msg.sent_at)
lines.push(`*${moment(parseServerDate(msg.sent_at)).format("MMM D YYYY, h:mm A")}*`);
Iif (msg.attachments?.length)
lines.push(`📎 *${msg.attachments.map((a) => a.name).join(", ")}*`);
lines.push(``);
lines.push(msg.content);
lines.push(``);
lines.push(`---`);
lines.push(``);
}
const blob = new Blob([lines.join("\n")], { type: "text/markdown" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `chat-${slug}.md`;
a.click();
URL.revokeObjectURL(url);
};
const handleDownloadJson = () => {
const payload = {
conversation_id: conversationId ?? null,
model: displayName,
exported_at: new Date().toISOString(),
disclosure: AI_DISCLOSURE.document,
messages: messages
.filter((m) => m.role !== "system")
.map((m) => ({
role: m.role,
ai_generated: m.role === "assistant",
content: m.content,
sent_at: m.sent_at ?? null,
attachments: m.attachments ?? [],
meta: m.meta ?? null,
})),
};
const blob = new Blob([JSON.stringify(payload, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `chat-${slug}.json`;
a.click();
URL.revokeObjectURL(url);
};
const btnClass =
"flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors";
return (
<div className="flex items-center justify-between pb-4 border-b border-gray-100 dark:border-gray-800 mb-1">
<span className="text-[11px] text-gray-400 dark:text-gray-500 tabular-nums">
{count} message{count !== 1 ? "s" : ""}
</span>
<div className="flex items-center gap-0.5">
<button
onClick={handleDownloadMd}
title="Download as Markdown"
className={btnClass}
>
<Download className="w-3 h-3" />
.md
</button>
<button
onClick={handleDownloadJson}
title="Download as JSON"
className={btnClass}
>
<FileJson2 className="w-3 h-3" />
.json
</button>
<SaveAsPdfButton
targetRef={threadRef}
title={`Chat with ${displayName}`}
subtitle={`Exported ${new Date().toLocaleString()}`}
className={btnClass}
label=".pdf"
/>
{conversationId && (
<button
onClick={() => {
void navigator.clipboard.writeText(conversationId).then(() => {
setCopyIdDone(true);
setTimeout(() => setCopyIdDone(false), 2000);
});
}}
title="Copy conversation ID"
className={btnClass}
>
{copyIdDone ? (
<Check className="w-3 h-3 text-emerald-500" />
) : (
<Copy className="w-3 h-3" />
)}
{copyIdDone ? "Copied" : "ID"}
</button>
)}
</div>
</div>
);
};
// ─── Message Metadata ─────────────────────────────────────────────────────────
/** Why a lighter model wrote an answer (svc-core `services/lighter_model.py`). */
const LIGHTER_MODEL_NOTE =
"Written by the agent's lighter model: its Economy cost profile answers a request triage calls simple with the lightest model of the same maker, in the same region.";
const MessageMeta: React.FC<{
sentAt?: string;
tokenCount?: number;
temperature?: number;
outputFormat?: string;
outputSchema?: string;
modelName?: string;
/** An Economy profile's lighter model wrote the answer (`meta.lighter_model`):
* `modelName` is it, and the chip says why. */
lighterModel?: boolean;
/** What the answer's turn cost, from the usage ledger; absent when the
* turn is not on it. Shown on hover, beside the tokens. */
cost?: CostFigure;
align: "left" | "right";
}> = ({
sentAt,
tokenCount = 0,
temperature,
outputFormat,
outputSchema,
modelName,
lighterModel = false,
cost,
align,
}) => {
const [schemaOpen, setSchemaOpen] = useState(false);
const hasContent =
sentAt ||
tokenCount > 0 ||
temperature !== undefined ||
outputFormat ||
outputSchema ||
modelName ||
cost;
const costText = cost ? describeCost(cost) : null;
if (!hasContent) return null;
const timeLabel = sentAt ? moment(parseServerDate(sentAt)).fromNow() : null;
const absoluteTime = sentAt ? parseServerDate(sentAt).toLocaleString() : undefined;
return (
<div
className={`flex flex-wrap items-center gap-x-2.5 gap-y-1 mt-1.5 text-[11px] text-gray-400 dark:text-gray-500 ${
align === "right" ? "justify-end" : "justify-start pl-0.5"
}`}
>
{timeLabel && (
<span title={absoluteTime} className="cursor-default tabular-nums">
{timeLabel}
</span>
)}
{modelName && (
<span
title={lighterModel ? LIGHTER_MODEL_NOTE : undefined}
className="flex items-center gap-0.5 px-1.5 py-0.5 rounded border font-mono text-[10px] bg-gray-50 dark:bg-gray-800/60 border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400"
>
<Cpu className="w-3 h-3" />
{modelName}
{lighterModel && (
<span className="font-sans text-gray-400 dark:text-gray-500">
· lighter model
</span>
)}
</span>
)}
{tokenCount > 0 && (
<span className="flex items-center gap-0.5 tabular-nums">
<Activity className="w-3 h-3" />
{tokenCount.toLocaleString()} tok
</span>
)}
{costText && (
<span
className="flex items-center gap-0.5 tabular-nums opacity-0 group-hover:opacity-100 transition-opacity"
title={
costText.unknown
? "What this answer cost: none of its calls could be priced"
: costText.lowerBound
? "What this answer cost, at least: some of its calls could not be priced"
: "What this answer cost"
}
>
<Coins className="w-3 h-3" />
{costText.text}
</span>
)}
{temperature !== undefined && (
<span
className="flex items-center gap-0.5 tabular-nums"
title="Temperature"
>
<Thermometer className="w-3 h-3 text-orange-400" />
{temperature.toFixed(1)}
</span>
)}
{outputFormat && outputFormat !== "markdown" && (
<span className="px-1.5 py-0.5 rounded border font-mono uppercase text-[10px] bg-indigo-50 dark:bg-indigo-950/30 border-indigo-100 dark:border-indigo-900/40 text-indigo-500 dark:text-indigo-400">
{outputFormat === "plain" ? "txt" : outputFormat}
</span>
)}
{outputSchema && (
<button
onClick={() => setSchemaOpen((v) => !v)}
title={schemaOpen ? "Hide schema" : "Show schema"}
className={`flex items-center gap-0.5 transition-colors hover:text-gray-600 dark:hover:text-gray-300 ${
schemaOpen ? "text-indigo-500 dark:text-indigo-400" : ""
}`}
>
<Code2 className="w-3 h-3" />
schema
</button>
)}
{outputSchema && schemaOpen && (
<pre className="w-full mt-0.5 text-[10px] font-mono text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/60 rounded-lg p-2.5 overflow-x-auto border border-gray-200 dark:border-gray-700 whitespace-pre-wrap leading-relaxed">
{outputSchema}
</pre>
)}
</div>
);
};
// ─── Response Format ──────────────────────────────────────────────────────────
const formatOption = (format: OutputFormat) =>
FORMAT_OPTIONS.find((o) => o.value === format) ?? FORMAT_OPTIONS[0];
/** The format the answer should come back in — a section of the Response
* settings panel. svc-core sends a format other than markdown on to svc-ai
* as `output_format`, which shapes the answer to it (and to the schema,
* for JSON). */
const ResponseFormatSection: React.FC<{
config: OutputFormatConfig;
onChange: (config: OutputFormatConfig) => void;
}> = ({ config, onChange }) => {
const currentOption = formatOption(config.format);
const hasSchema = currentOption.hasSchema;
return (
<div className="space-y-2">
<p className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
<FileText className="w-4 h-4 text-gray-400" />
Response format
</p>
<div className="flex flex-wrap gap-1.5">
{FORMAT_OPTIONS.map((opt) => {
const Icon = opt.icon;
const active = config.format === opt.value;
return (
<button
key={opt.value}
type="button"
aria-pressed={active}
onClick={() =>
onChange({
format: opt.value,
schema: opt.hasSchema ? config.schema : "",
})
}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium border transition-all ${
active
? "bg-indigo-100 dark:bg-indigo-900/40 border-indigo-200 dark:border-indigo-800 text-indigo-700 dark:text-indigo-300"
: "bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
}`}
>
<Icon className="w-3.5 h-3.5" />
{opt.label}
</button>
);
})}
</div>
<p className="text-xs text-gray-500 dark:text-gray-400 italic">
{currentOption.description}
</p>
{hasSchema && (
<div className="space-y-1.5">
<label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
<Braces className="w-4 h-4 text-gray-400" />
Schema Definition
<span className="text-xs text-gray-400 dark:text-gray-500 font-normal ml-1">
(optional)
</span>
</label>
<textarea
value={config.schema}
onChange={(e) => onChange({ ...config, schema: e.target.value })}
placeholder={
config.format === "json"
? '{\n "type": "object",\n "properties": {\n "field": { "type": "string" }\n }\n}'
: "type: object\nproperties:\n field:\n type: string"
}
rows={5}
spellCheck={false}
className="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-xs font-mono text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 resize-none focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
/>
<p className="text-xs text-gray-400 dark:text-gray-500">
The model will respond with {config.format.toUpperCase()} matching
this schema. Leave blank for generic {config.format.toUpperCase()}{" "}
output.
</p>
</div>
)}
</div>
);
};
// ─── Settings Panel ───────────────────────────────────────────────────────────
/** What the model may be tuned on (`supports*`), and the response format,
* which every chat takes. */
const SettingsPanel: React.FC<{
settings: ChatSettings;
onChange: (s: ChatSettings) => void;
supportsTemperature: boolean;
supportsThinking: boolean;
supportsSystemPrompt: boolean;
}> = ({
settings,
onChange,
supportsTemperature,
supportsThinking,
supportsSystemPrompt,
}) => {
const patch = (partial: Partial<ChatSettings>) =>
onChange({ ...settings, ...partial });
return (
<div className="border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 px-4 py-4 space-y-4">
<p className="text-xs font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
Response Settings
</p>
{supportsTemperature && (
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
<Thermometer className="w-4 h-4 text-orange-400" />
Temperature
</label>
<span className="text-sm font-mono text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded">
{settings.temperature.toFixed(1)}
</span>
</div>
<input
type="range"
min={0}
max={2}
step={0.1}
value={settings.temperature}
onChange={(e) => patch({ temperature: parseFloat(e.target.value) })}
className="w-full h-1.5 rounded-full accent-indigo-500 cursor-pointer"
/>
<div className="flex justify-between text-xs text-gray-400">
<span>Precise</span>
<span>Creative</span>
</div>
</div>
)}
{supportsThinking && (
<Toggle
checked={settings.thinking}
onChange={(v) => patch({ thinking: v })}
label="Extended Thinking"
description="Enables deeper reasoning before responding. Increases latency."
/>
)}
{supportsSystemPrompt && (
<div className="space-y-1.5">
<label className="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-300">
<Terminal className="w-4 h-4 text-gray-400" />
System Prompt
</label>
<textarea
value={settings.systemPrompt}
onChange={(e) => patch({ systemPrompt: e.target.value })}
placeholder="e.g. You are a helpful travel assistant..."
rows={3}
className="w-full rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 px-3 py-2 text-sm text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 resize-none focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
/>
<p className="text-xs text-gray-400 dark:text-gray-500">
Injected as a system message before each prompt.
</p>
</div>
)}
<ResponseFormatSection
config={settings.outputFormat}
onChange={(outputFormat) => patch({ outputFormat })}
/>
</div>
);
};
// ─── Execution Trace ──────────────────────────────────────────────────────────
const ExecutionTrace: React.FC<{
steps: string[];
currentStatus: string | undefined;
isStreaming: boolean;
}> = ({ steps, currentStatus, isStreaming }) => {
// Determine which steps are completed vs. the active one.
// When streaming the last status step is complete; the active state is "streaming".
const completedSteps = isStreaming ? steps : steps.slice(0, -1);
const activeStep = isStreaming
? null
: (steps[steps.length - 1] ?? currentStatus);
Iif (steps.length === 0 && !currentStatus) {
return <TypingDots />;
}
const phase: ExecutionPhase = isStreaming
? "streaming"
: activeStep
? detectPhase(activeStep)
: "connecting";
const cfg = PHASE_CONFIG[phase];
return (
<div className="space-y-2">
{/* Completed steps */}
{completedSteps.length > 0 && (
<div className="space-y-1">
{completedSteps.map((step, i) => (
<div
key={i}
className="flex items-center gap-2 text-xs text-gray-400 dark:text-gray-500"
>
<CheckCircle2 className="w-3 h-3 shrink-0 text-emerald-400 dark:text-emerald-500" />
<span className="truncate">{friendlyLabel(step)}</span>
</div>
))}
</div>
)}
{/* Active step or streaming indicator */}
{!isStreaming && activeStep && (
<div
className={`flex items-center gap-2 px-2.5 py-1.5 rounded-lg border text-xs font-medium ${cfg.bgClass}`}
>
<span className={`shrink-0 animate-pulse ${cfg.iconClass}`}>
{cfg.icon}
</span>
<span className={`truncate ${cfg.iconClass}`}>
{friendlyLabel(activeStep)}
</span>
<span
className={`ml-auto shrink-0 w-1.5 h-1.5 rounded-full animate-pulse ${cfg.dotClass}`}
/>
</div>
)}
{isStreaming && completedSteps.length > 0 && (
<div className="flex items-center gap-1.5 text-xs text-violet-500 dark:text-violet-400 font-medium">
<Sparkles className="w-3 h-3 animate-pulse" />
<span>Generating</span>
</div>
)}
</div>
);
};
// ─── Agent Streaming Bubble ───────────────────────────────────────────────────
const AgentExecutionBubble: React.FC<{
displayName: string;
statusMessage: string | undefined;
streamingContent: string;
streamingCitations: Citation[];
executionSteps: string[];
nodeExecutions: NodeExecution[];
graphPlan: GraphPlanStage[] | undefined;
}> = ({
displayName,
statusMessage,
streamingContent,
streamingCitations,
executionSteps,
nodeExecutions,
graphPlan,
}) => {
// The pipeline view takes over as soon as either the plan or the first node
// arrives; before that (and for non-graph executions, which announce no
// plan and emit no nodes) the flat status trace is all there is to show.
const hasPipeline = nodeExecutions.length > 0 || !!graphPlan;
const isStreaming = streamingContent.length > 0;
const hasSteps = executionSteps.length > 0 || !!statusMessage;
return (
<div className="flex gap-3 group">
<div className="w-7 h-7 rounded-full bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center shrink-0 mt-1">
<Bot className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</div>
<div className="flex-1 min-w-0 max-w-[80%] space-y-2">
<p className="flex items-center gap-1.5 text-xs text-gray-400 dark:text-gray-500 pl-0.5">
{displayName}
<AIGeneratedBadge compact title={AI_DISCLOSURE.answerTitle} />
</p>
{hasPipeline ? (
<ExecutionPipeline
plan={graphPlan}
executions={nodeExecutions}
finished={false}
citations={streamingCitations}
statusMessage={
statusMessage ? friendlyLabel(statusMessage) : undefined
}
defaultExpanded
/>
) : (
<>
{/* Fallback: flat status + streaming for non-graph executions */}
{hasSteps && (
<div className="bg-gray-50 dark:bg-gray-800/60 border border-gray-200 dark:border-gray-700 rounded-xl px-3 py-2.5">
<ExecutionTrace
steps={executionSteps}
currentStatus={statusMessage}
isStreaming={isStreaming}
/>
</div>
)}
{isStreaming && (
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 px-4 py-3 rounded-xl shadow-sm">
<RichMarkdown content={streamingContent} />
<span className="inline-block w-0.5 h-3.5 bg-violet-400 dark:bg-violet-500 ml-0.5 align-middle animate-pulse" />
{streamingCitations.length > 0 && (
<div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
<CitationRow citations={streamingCitations} />
</div>
)}
</div>
)}
{!hasSteps && !isStreaming && (
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 px-4 py-3 rounded-xl shadow-sm">
<TypingDots />
</div>
)}
</>
)}
</div>
</div>
);
};
// ─── Message Bubble ───────────────────────────────────────────────────────────
const MessageBubble: React.FC<{
message: ChatMessage;
displayName: string;
conversationId?: string | null;
/** Sends the question this answer answered again: on the latest answer,
* when its web searches found nothing and no rule was the reason. */
onAskAgain?: () => void;
}> = ({ message, displayName, conversationId, onAskAgain }) => {
// The printed PDF is this node, exactly as rendered — see util/pdfExport.
const bodyRef = useRef<HTMLDivElement | null>(null);
// Asked, from the hover actions, to judge an answer that did not ask for
// it (see `needsAttention`).
const [judging, setJudging] = useState(false);
const { getApiHandler } = useApiHandler();
// A document in the reply downloads from the stored message, so only a
// saved one (with an id) offers it; a reply still streaming does not.
const messageId = message.id;
const downloadDocument: DocumentDownloader | null =
messageId && conversationId
? (index, document) =>
getApiHandler().conversation_router.downloadDocument(
conversationId,
messageId,
index,
`${document.title}.pdf`,
)
: null;
// A document's images are the copies stored with the saved answer.
const documentImageUrl: DocumentImageUrl | null =
messageId && conversationId && message.role === "assistant"
? (asset) =>
getApiHandler().conversation_router.documentImageUrl(
conversationId,
messageId,
asset,
)
: null;
Iif (message.role === "system") {
return (
<div className="flex justify-center my-2">
<div className="flex items-center gap-1.5 px-3 py-1 rounded-full bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/40 text-amber-700 dark:text-amber-400 text-xs italic">
<Terminal className="w-3 h-3 shrink-0" />
<span>System: {message.content}</span>
</div>
</div>
);
}
if (message.role === "user") {
return (
<div className="flex justify-end gap-2.5 group">
<div className="max-w-[75%]">
<div className="flex items-center justify-between mb-1.5 pr-1">
<div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
<SaveToDashboard
content={message.content}
role="user"
conversationId={conversationId}
sourceLabel="Your message"
className={ACTION_BTN}
/>
<CopyButton text={message.content} />
</div>
<p className="text-xs text-gray-400 dark:text-gray-500">You</p>
</div>
{message.attachments && message.attachments.length > 0 && (
<SentAttachments attachments={message.attachments} />
)}
{message.meta?.command ? (
<SentCommand
record={message.meta.command}
content={message.content}
/>
) : message.content || !message.attachments?.length ? (
// Documents sent without a word have no words to show.
<div className="bg-indigo-500 text-white px-4 py-3 rounded-2xl rounded-tr-sm text-sm leading-relaxed shadow-sm">
{message.content}
</div>
) : null}
<MessageMeta sentAt={message.sent_at} align="right" />
</div>
<div className="w-7 h-7 rounded-full bg-indigo-100 dark:bg-indigo-900/40 border border-indigo-200 dark:border-indigo-800 flex items-center justify-center shrink-0 mt-6">
<span className="text-xs font-bold text-indigo-600 dark:text-indigo-400">
Y
</span>
</div>
</div>
);
}
// assistant
const meta = message.meta;
// Every answer is recorded; only one something happened to — a rule acted,
// the quality check failed, a verdict was given — puts its record and the
// verdict in view. The rest keep them one hover away, so a greeting is
// just a greeting.
const record = decisionHref(message.invocation_id);
const attention = !!record && needsAttention(message);
const showVerdict = !!message.invocation_id && (attention || judging);
const trace: TraceEvent[] = Array.isArray(message?.trace)
? message.trace
: [];
const hasTrace = trace.length > 0;
const traceNodes: NodeExecution[] = hasTrace
? groupTraceByNode(trace).map((n) => ({
node_id: n.node_id,
is_system_node: n.is_system_node,
streamingContent: "",
tools: n.tools,
done: true,
output: n.output_preview || undefined,
system_result: n.system_result,
system_input: n.system_input,
tokens: n.tokens,
duration_ms: n.duration_ms,
hitl: n.hitl,
started_ms: n.started_ms,
ended_ms: n.ended_ms,
pass: n.pass,
}))
: [];
// Every time this turn stopped for the person. The persisted record on
// meta is authoritative; a live turn (or one stored before it existed)
// reads the same thing off its trace.
const humanInput: NodeHitl[] = meta?.hitl?.length
? meta.hitl.map(exchangeToNodeHitl)
: hitlFromTrace(trace);
// Traces persisted before graph_plan existed carry no plan — the pipeline
// then renders exactly the nodes that ran, with no skipped stages.
const tracePlan = hasTrace ? planFromTrace(trace) : undefined;
return (
<div className="flex gap-3 group">
<div className="w-7 h-7 rounded-full bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center shrink-0 mt-6">
<Bot className="w-3.5 h-3.5 text-gray-500 dark:text-gray-400" />
</div>
<div className="max-w-[80%] min-w-0 flex-1">
<div className="flex items-center justify-between mb-1.5 pl-0.5">
<p className="flex items-center gap-1.5 text-xs text-gray-400 dark:text-gray-500">
{displayName}
<AIGeneratedBadge compact title={AI_DISCLOSURE.answerTitle} />
{meta?.eval_outcome && (
<QualityCheckBadge
outcome={meta.eval_outcome}
score={meta.eval_score}
/>
)}
{/* The answer's decision record: what was asked, what answered,
the rules, checks, people, calls and cost behind it. In view
when the answer calls for it; otherwise among the hover
actions. Absent on answers from before turns had ids. */}
{attention && record && (
<Link
to={record}
title="Open this answer's decision record"
className="inline-flex items-center gap-1 text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:underline"
>
<ScanSearch className="size-3" />
Why did it do this?
</Link>
)}
</p>
<div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">
{record && !attention && (
<Link
to={record}
aria-label="Why did it do this?"
title="Why did it do this? Open this answer's decision record"
className={ACTION_BTN}
>
<ScanSearch className="w-3.5 h-3.5" />
</Link>
)}
{message.invocation_id && !showVerdict && (
<button
type="button"
aria-label="Judge this answer"
title="Was this right? Accept, correct or reject it"
onClick={() => setJudging(true)}
className={ACTION_BTN}
>
<Gavel className="w-3.5 h-3.5" />
</button>
)}
<SaveToDashboard
content={message.content}
role="assistant"
conversationId={conversationId}
sourceLabel={displayName}
className={ACTION_BTN}
/>
<SaveAsPdfButton
targetRef={bodyRef}
title={`Response from ${displayName}`}
subtitle={
message.sent_at
? `${displayName} · ${moment(parseServerDate(message.sent_at)).format("MMM D YYYY, h:mm A")}`
: displayName
}
className={ACTION_BTN}
/>
<CopyRawButton text={message.content} />
<CopyButton text={message.content} />
</div>
</div>
{hasTrace && (
<div className="mb-2">
<ExecutionPipeline
plan={tracePlan}
executions={traceNodes}
finished
/>
</div>
)}
{humanInput.length > 0 && (
<div className="mb-2 space-y-1.5">
{humanInput.map((hitl, i) => (
<HumanInputRecord key={i} hitl={hitl} />
))}
</div>
)}
<div
ref={bodyRef}
className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 px-4 py-3.5 rounded-2xl rounded-tl-sm shadow-sm text-gray-800 dark:text-gray-200"
>
<DocumentDownloadProvider
download={downloadDocument}
imageUrl={documentImageUrl}
>
<RichMarkdown content={message.content} />
</DocumentDownloadProvider>
{message.citations && message.citations.length > 0 && (
<div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
<p className="text-xs text-gray-400 dark:text-gray-500 mb-2 font-medium">
Sources
</p>
<CitationRow citations={message.citations} />
</div>
)}
</div>
{/* An Output rule withheld the answer: the bubble holds its message.
Quiet — the decision record ("Why did it do this?") says more. */}
{meta?.withheld && <WithheldNote withheld={meta.withheld} />}
{/* What a Tools rule did to the answer's web searches, with the
edit that would change it — or that no rule was the reason. */}
{meta?.web_search && (
<WebSourcesNote summary={meta.web_search} onAskAgain={onAskAgain} />
)}
{/* Was it right? The person's verdict, kept on the turn's decision
record — and what lets a corrected answer become an evaluation
case. Only answers with a record can take one. */}
{message.invocation_id && showVerdict && (
<VerdictBar
key={message.invocation_id}
invocationId={message.invocation_id}
answer={message.content}
verdict={message.verdict}
/>
)}
<MessageMeta
sentAt={message.sent_at}
tokenCount={
typeof meta?.token_count === "number" ? meta.token_count : undefined
}
cost={
message.cost_usd !== undefined
? {
cost_usd: message.cost_usd,
unpriced: message.unpriced_calls ?? 0,
}
: undefined
}
temperature={
typeof meta?.temperature === "number" ? meta.temperature : undefined
}
outputFormat={
typeof meta?.output_format === "string"
? meta.output_format
: undefined
}
outputSchema={
typeof meta?.output_schema === "string"
? meta.output_schema
: undefined
}
modelName={
typeof meta?.model_name === "string" ? meta.model_name : undefined
}
lighterModel={Boolean(meta?.lighter_model?.answered)}
align="left"
/>
</div>
</div>
);
};
// ─── Empty State ──────────────────────────────────────────────────────────────
const EmptyState: React.FC<{ displayName: string }> = ({ displayName }) => (
<div className="flex flex-col items-center justify-center h-full gap-3 text-center select-none">
<div className="w-14 h-14 rounded-2xl bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center">
<Bot className="w-7 h-7 text-gray-400 dark:text-gray-500" />
</div>
<div>
<p className="text-sm font-medium text-gray-600 dark:text-gray-400">
Chat with {displayName}
</p>
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
Type a message below to start the conversation
</p>
</div>
</div>
);
// ─── ChatPanel ────────────────────────────────────────────────────────────────
/** The message box's height: its text's, up to 160px. */
/** Below this much room in the input row, the composer's four actions fold
* into one menu (`ComposerMenu`): beside the message box they take 152px,
* which left it under 360px — about half the row in the chat dock. Measured
* on the row, not the window, like `ChatLayout`'s `STACK_BELOW_PX`. */
export const COMPACT_BELOW_PX = 560;
function fitTextarea(el: HTMLTextAreaElement) {
el.style.height = "auto";
el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
}
const ChatPanel: React.FC<ChatPanelProps> = ({
messages,
displayName,
loading,
conversationId,
highlightMessageId,
statusMessage,
streamingContent = "",
streamingCitations = [],
executionSteps = [],
nodeExecutions = [],
graphPlan,
onSubmit,
onUploadFile,
documents = [],
onDeleteDocument,
placeholder = "Type a message…",
supportsTemperature = false,
supportsThinking = false,
supportsSystemPrompt = false,
onStop,
paused = false,
fill = false,
commands,
autoFocus = false,
className = "",
}) => {
const [input, setInput] = useState("");
// ── Chat commands ──
// A chosen command is a token at the start of the message box — its line
// in code type, never text a person could half-edit — with its target's
// form above the box; the message box then holds only the free text.
const [activeCommand, setActiveCommand] = useState<CommandEntry | null>(
null,
);
const [formValues, setFormValues] = useState<FormValues>({});
const [touched, setTouched] = useState<Record<string, boolean>>({});
const [attempted, setAttempted] = useState(false);
// What each command's form held when its token was turned back into text,
// so Backspace past the token does not throw a filled-in form away.
const drafts = useRef<Record<string, FormValues>>({});
const formRef = useRef<HTMLElement>(null);
const formId = useId();
const [focusTo, setFocusTo] = useState<"form" | "message" | null>(null);
const formFields = useMemo(
() => activeCommand?.target.form?.fields ?? [],
[activeCommand],
);
const formCheck = useMemo(
() => toInputs(formFields, formValues),
[formFields, formValues],
);
const blockers = activeCommand
? commandBlockers(activeCommand, formCheck.errors, input)
: null;
// The palette lists the command lines a typed "/" completes to; Esc closes
// it for the text it was open on, and typing reopens it. None while a
// command is chosen: a turn runs one.
const paletteId = useId();
const [paletteIndex, setPaletteIndex] = useState(0);
const [paletteClosedFor, setPaletteClosedFor] = useState<string | null>(
null,
);
const paletteItems = useMemo(
() => (activeCommand ? [] : paletteEntries(input, commands)),
[activeCommand, input, commands],
);
const paletteOpen = paletteItems.length > 0 && paletteClosedFor !== input;
const commandsOffered = (commands ?? []).some((c) => c.targets.length > 0);
const [attachedFiles, setAttachedFiles] = useState<UploadedFileRef[]>([]);
const [uploadingNames, setUploadingNames] = useState<string[]>([]);
// Why the last upload failed — a reader of Knowledge in an organisation
// may attach its documents but not add to them.
const [uploadError, setUploadError] = useState<string | null>(null);
const sharedLibrary = useWorkspace().kind !== "personal";
const [settings, setSettings] = useState<ChatSettings>(DEFAULT_SETTINGS);
const [showSettings, setShowSettings] = useState(false);
const [showDocuments, setShowDocuments] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// 0 is unmeasured (jsdom, a hidden chat), which keeps the wide composer.
const [toolsRowRef, toolsRowWidth] = useElementWidth<HTMLDivElement>();
const compact = toolsRowWidth > 0 && toolsRowWidth < COMPACT_BELOW_PX;
const scrollRef = useRef<HTMLDivElement | null>(null);
const highlightRef = useRef<HTMLDivElement | null>(null);
// A format other than the default is shown on the settings button, since
// it changes what comes back while the panel is closed.
const format = formatOption(settings.outputFormat.format);
const formatChosen = format.value !== "markdown";
const attachedIds = new Set(attachedFiles.map((f) => f.id));
// On mount only: a prop that changes later is not a request to move focus.
useEffect(() => {
const el = textareaRef.current;
if (!autoFocus || !el) return;
const active = document.activeElement;
Iif (active && active !== document.body && !active.contains(el)) return;
el.focus({ preventScroll: true });
}, []);
// Clear attached files when switching conversations
useEffect(() => {
setAttachedFiles([]);
}, [conversationId]);
useEffect(() => {
setPaletteIndex(0);
}, [paletteItems.length, input]);
// Keep the chosen command's form as it is filled in (see `drafts`).
useEffect(() => {
if (activeCommand) drafts.current[activeCommand.line] = formValues;
}, [activeCommand, formValues]);
// Focus moves once what it moves to is rendered: the form's first field
// when a command is picked, the message box otherwise.
useEffect(() => {
if (!focusTo) return;
const field =
focusTo === "form"
? formRef.current?.querySelector<HTMLElement>("input, select, textarea")
: null;
(field ?? textareaRef.current)?.focus();
setFocusTo(null);
}, [focusTo]);
// Auto-resize textarea — to its text, and again whenever its width
// changes: a chat that stacks or goes full screen widens the box after
// its first height was measured, and that height (the placeholder wrapped
// over several lines in a narrow box) used to stay until the next key.
useEffect(() => {
const el = textareaRef.current;
Eif (el) fitTextarea(el);
}, [input]);
useEffect(() => {
const el = textareaRef.current;
Iif (!el || typeof ResizeObserver !== "function") return;
let width = el.clientWidth;
const observer = new ResizeObserver(() => {
// Only a change of width: fitting the height resizes the box too.
if (el.clientWidth === width) return;
width = el.clientWidth;
fitTextarea(el);
});
observer.observe(el);
return () => observer.disconnect();
}, []);
// Scroll to bottom on new messages / streaming updates — unless a deep
// link asked for a particular message, in which case scrolling to the end
// would immediately undo the thing the link was for.
useEffect(() => {
if (highlightMessageId) return;
scrollRef.current?.scrollTo({
top: scrollRef.current.scrollHeight,
behavior: "smooth",
});
}, [messages, loading, streamingContent, highlightMessageId]);
// …and bring the linked message into view once it is rendered. Keyed on the
// id and the message list, because a deep link arrives before the
// conversation it points into has loaded.
useEffect(() => {
if (!highlightMessageId) return;
highlightRef.current?.scrollIntoView({
behavior: "smooth",
block: "center",
});
}, [highlightMessageId, messages]);
/** Make `entry` the chosen command, `request` the message box's text. */
const chooseCommand = (
entry: CommandEntry,
request: string,
focus: "form" | "message",
) => {
const fields = entry.target.form?.fields ?? [];
setActiveCommand(entry);
setFormValues(drafts.current[entry.line] ?? initialValues(fields));
setTouched({});
setAttempted(false);
setInput(request);
setPaletteClosedFor(null);
setFocusTo(focus === "form" && fields.length ? "form" : "message");
};
/** Let go of the chosen command; `keepDraft` keeps its form's values for
* the next time it is chosen. */
const dropCommand = (keepDraft: boolean) => {
if (activeCommand && !keepDraft) delete drafts.current[activeCommand.line];
setActiveCommand(null);
setTouched({});
setAttempted(false);
};
const pickCommand = (entry: CommandEntry) => chooseCommand(entry, "", "form");
const openPalette = () => {
dropCommand(true);
setInput(COMMAND_PREFIX);
setPaletteClosedFor(null);
textareaRef.current?.focus();
};
const attachFiles = () => fileInputRef.current?.click();
const attachDocument = (doc: UploadedFileRef) =>
setAttachedFiles((prev) =>
prev.some((p) => p.id === doc.id) ? prev : [...prev, doc],
);
// The documents library and Response settings take the same place above
// the message box, so opening one closes the other.
const toggleDocuments = () => {
setShowDocuments((v) => !v);
setShowSettings(false);
};
const toggleSettings = () => {
setShowSettings((v) => !v);
setShowDocuments(false);
};
// What attaching offers, from the paperclip beside the box or from the
// narrow composer's menu (`AttachMenu`).
const attach: AttachItemsProps = {
onUpload: attachFiles,
canUpload: !!onUploadFile,
documents,
attachedIds,
onAttach: attachDocument,
documentsOpen: showDocuments,
onToggleDocuments: toggleDocuments,
};
const handleInputChange = (value: string) => {
// A whole command line typed (or pasted), then a space or a line break,
// becomes the token; what follows it stays as the free text.
const token = activeCommand ? null : tokenizeCommand(value, commands);
if (token) chooseCommand(token.entry, token.request, "message");
else setInput(value);
};
const setFormValue = (name: string, value: FormValue) =>
setFormValues((prev) => ({ ...prev, [name]: value }));
const handleSend = async () => {
// One turn at a time: Enter is held while an answer is still coming,
// exactly as the Send button is (`canSend`). The box stays editable, so
// the next message can be written meanwhile.
if (loading || uploadingNames.length > 0) return;
if (activeCommand && blockers) {
if (!commandReady(blockers)) {
// Show every error, and go to the first thing left to fill in.
setAttempted(true);
const first = formFields.find((f) => formCheck.errors[f.name]);
const holder = first
? Array.from(
formRef.current?.querySelectorAll<HTMLElement>("[data-field]") ??
[],
).find((el) => el.dataset.field === first.name)
: undefined;
const field = holder?.querySelector<HTMLElement>(
"input, select, textarea",
);
(field ?? textareaRef.current)?.focus();
return;
}
const entry = activeCommand;
const request = input.trim();
const command: CommandSubmission = {
entry,
inputs: formCheck.inputs,
request,
};
const currentFiles = [...attachedFiles];
dropCommand(false);
setInput("");
setAttachedFiles([]);
await onSubmit(commandText(entry, request), currentFiles, settings, command);
return;
}
const text = input.trim();
Iif (!text && attachedFiles.length === 0) return;
// A whole command line sent as text — typed before the catalogue came,
// or with the palette closed — becomes the token instead, so its form
// is seen before anything runs.
const typed = matchCommand(text, commands);
if (typed) {
chooseCommand(typed, typed.request, "form");
return;
}
setInput("");
const currentFiles = [...attachedFiles];
setAttachedFiles([]);
await onSubmit(text, currentFiles, settings);
};
// The latest answer's question, sent again as it was asked — the note
// under an answer whose web searches found nothing offers it. Not for a
// chat command, whose form is not kept on the message.
const askAgainFor = (index: number): (() => void) | undefined => {
const answer = messages[index];
const question = messages[index - 1];
if (
loading ||
index !== messages.length - 1 ||
answer?.role !== "assistant" ||
question?.role !== "user" ||
question.meta?.command ||
!question.content.trim()
) {
return undefined;
}
return () => void onSubmit(question.content, [], settings);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// Backspace into the token turns it back into text to edit; the form
// keeps its values for when it is chosen again.
if (e.key === "Backspace" && activeCommand && input === "") {
e.preventDefault();
const line = activeCommand.line;
dropCommand(true);
setInput(line);
return;
}
if (paletteOpen) {
const count = paletteItems.length;
Iif (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const step = e.key === "ArrowDown" ? 1 : -1;
setPaletteIndex((i) => (i + step + count) % count);
return;
}
if ((e.key === "Enter" || e.key === "Tab") && !e.shiftKey) {
e.preventDefault();
pickCommand(paletteItems[Math.min(paletteIndex, count - 1)]);
return;
}
if (e.key === "Escape") {
e.preventDefault();
setPaletteClosedFor(input);
return;
}
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend().catch(console.error);
}
};
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const selected = Array.from(e.target.files ?? []);
e.target.value = "";
Iif (selected.length === 0 || !onUploadFile) return;
setUploadError(null);
setUploadingNames((prev) => [...prev, ...selected.map((f) => f.name)]);
// Settled one by one, so a refused file neither strands the others nor
// leaves its "uploading" chip behind.
const settled = await Promise.allSettled(
selected.map((f) => onUploadFile(f)),
);
const results = settled.map((r) =>
r.status === "fulfilled" ? r.value : null,
);
const failures = settled.flatMap((r, i) =>
r.status === "rejected"
? [`${selected[i].name}: ${errorDetail(r.reason, "upload failed")}`]
: [],
);
if (failures.length > 0) {
setUploadError(`Couldn't upload ${failures.join("; ")}`);
}
setUploadingNames((prev) => {
const toRemove = selected.map((f) => f.name);
const remaining = [...prev];
for (const name of toRemove) {
const idx = remaining.indexOf(name);
Eif (idx !== -1) remaining.splice(idx, 1);
}
return remaining;
});
const uploaded = results.filter(Boolean) as UploadedFileRef[];
setAttachedFiles((prev) => [
...prev,
...uploaded.filter((u) => !prev.some((p) => p.id === u.id)),
]);
};
const canSend =
(blockers
? commandReady(blockers)
: input.trim().length > 0 || attachedFiles.length > 0) &&
!loading &&
uploadingNames.length === 0;
// A command's line being typed reads as code, before it is a token.
const typingCommand = !activeCommand && paletteItems.length > 0;
const messagePlaceholder = activeCommand
? requestRequired(activeCommand)
? activeCommand.spec.request_hint
: "Additional instructions (optional)"
: commandsOffered
? `${placeholder} Type / for commands.`
: placeholder;
return (
<div
className={`flex flex-col rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 overflow-hidden shadow-sm ${
// An explicit floor: `overflow-hidden` lets a flex item shrink to
// nothing, which a tall form beside it in the column would do.
fill ? "flex-1 min-h-[22rem]" : ""
} ${className}`}
>
{/* ── Messages ── */}
<div
ref={scrollRef}
data-testid="chat-thread"
className="flex-1 overflow-y-auto px-5 py-6 space-y-6 min-h-0"
style={fill ? undefined : { minHeight: "360px", maxHeight: "60vh" }}
>
{messages.length === 0 && !loading ? (
<EmptyState displayName={displayName} />
) : (
<>
<ConversationToolbar
messages={messages}
displayName={displayName}
conversationId={conversationId}
threadRef={scrollRef}
/>
{messages.map((msg, i) => (
// The anchor a deep link lands on. Wrapping rather than
// threading an id through three bubble branches keeps the
// highlight in one place, and the ring sits outside the
// bubble's own styling so no message type has to know about it.
<div
// Keyed by the message, not its place: a bubble keeps state
// (a verdict, a copied tick, an open schema), and keyed by
// index the first answer of the next conversation opened
// inherited the last one's.
key={msg.id ?? `${conversationId ?? "new"}:${i}`}
data-message-id={msg.id}
ref={
msg.id && msg.id === highlightMessageId
? highlightRef
: undefined
}
className={
msg.id && msg.id === highlightMessageId
? "rounded-2xl ring-2 ring-violet-400 dark:ring-violet-500 ring-offset-4 ring-offset-white dark:ring-offset-gray-900 transition-shadow"
: undefined
}
>
<MessageBubble
message={msg}
displayName={displayName}
conversationId={conversationId}
onAskAgain={askAgainFor(i)}
/>
</div>
))}
{loading && (
<AgentExecutionBubble
displayName={displayName}
statusMessage={statusMessage}
streamingContent={streamingContent}
streamingCitations={streamingCitations}
executionSteps={executionSteps}
nodeExecutions={nodeExecutions}
graphPlan={graphPlan}
/>
)}
</>
)}
</div>
{/* ── Settings Panel ── */}
{showSettings && (
<SettingsPanel
settings={settings}
onChange={setSettings}
supportsTemperature={supportsTemperature}
supportsThinking={supportsThinking}
supportsSystemPrompt={supportsSystemPrompt}
/>
)}
{/* ── Documents Panel ── */}
{showDocuments && (
<DocumentsPanel
documents={documents}
attachedIds={attachedIds}
onAttach={attachDocument}
onDetach={(id) =>
setAttachedFiles((prev) => prev.filter((f) => f.id !== id))
}
onDelete={onDeleteDocument}
shared={sharedLibrary}
/>
)}
{/* ── Input Area ── */}
<div className="border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 px-3 py-3 space-y-2">
{uploadError && (
<div
role="alert"
className="flex items-start gap-2 text-xs text-red-600 dark:text-red-400"
>
<span className="flex-1 min-w-0">{uploadError}</span>
<button
type="button"
onClick={() => setUploadError(null)}
aria-label="Dismiss"
className="shrink-0 p-0.5 rounded hover:bg-red-50 dark:hover:bg-red-900/30"
>
<X className="w-3 h-3" />
</button>
</div>
)}
{(attachedFiles.length > 0 || uploadingNames.length > 0) && (
<div className="flex flex-wrap gap-2">
{uploadingNames.map((name, i) => (
<FileChip key={`uploading-${i}`} name={name} uploading />
))}
{attachedFiles.map((f) => (
<FileChip
key={f.id}
name={f.name}
onRemove={() =>
setAttachedFiles((prev) => prev.filter((a) => a.id !== f.id))
}
/>
))}
</div>
)}
{paletteOpen && (
<CommandPalette
id={paletteId}
entries={paletteItems}
activeIndex={paletteIndex}
onPick={pickCommand}
onActivate={setPaletteIndex}
/>
)}
{activeCommand && blockers && (
<CommandForm
ref={formRef}
entry={activeCommand}
values={formValues}
errors={formCheck.errors}
blockers={blockers}
touched={touched}
attempted={attempted}
onChange={setFormValue}
onTouch={(name) =>
setTouched((prev) => (prev[name] ? prev : { ...prev, [name]: true }))
}
onSubmit={() => void handleSend().catch(console.error)}
idPrefix={formId}
/>
)}
{/* The tools, then the message box and Send. Where the row is
narrow (`compact`: the chat dock, a phone) the tools are one menu
and the box takes the rest of the line. Otherwise they sit beside
it, and should the row be too narrow for both before it is
measured, the box takes the next line whole rather than shrinking
to a sliver beside them: its 14rem basis does not fit, so it
wraps. `grow`, not `flex-1`, whose `flex: 1 1 0%` would zero the
basis. */}
<div
ref={toolsRowRef}
data-compact={compact || undefined}
className={
compact ? "flex items-end gap-2" : "flex flex-wrap items-end gap-2"
}
>
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={(e) => {
handleFileChange(e).catch(console.error);
}}
/>
{compact ? (
<ComposerMenu
attach={attach}
onCommands={commandsOffered ? openPalette : undefined}
settingsOpen={showSettings}
onToggleSettings={toggleSettings}
thinking={settings.thinking}
formatLabel={formatChosen ? format.label : undefined}
/>
) : (
<div className="flex shrink-0 items-end gap-2">
<AttachMenu {...attach} />
{commandsOffered && (
<button
type="button"
onClick={openPalette}
title="Commands — run a skill directly"
aria-label="Commands"
className="shrink-0 w-8 h-8 p-0 flex items-center justify-center rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors mb-0.5"
>
<Slash className="w-4 h-4" />
</button>
)}
<button
type="button"
onClick={toggleSettings}
title={
formatChosen
? `Response settings · ${format.label}`
: "Response settings"
}
aria-label="Response settings"
aria-expanded={showSettings}
className={`shrink-0 w-8 h-8 p-0 flex items-center justify-center rounded-lg transition-colors mb-0.5 ${
showSettings || formatChosen
? "text-indigo-600 dark:text-indigo-400 bg-indigo-100 dark:bg-indigo-900/40"
: "text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-700"
}`}
>
{settings.thinking ? (
<Sparkles className="w-4 h-4" />
) : (
<Settings2 className="w-4 h-4" />
)}
</button>
</div>
)}
<div
data-testid="chat-composer"
className={
compact
? "flex flex-1 min-w-0 items-end gap-2"
: "flex grow basis-56 min-w-0 items-end gap-2"
}
>
{/* The box: a chosen command's token, then the text. They share
a line while there is room for the text beside the token
(its 8rem basis), and the text takes the next one when not. */}
<div
className={`flex flex-1 min-w-0 flex-wrap items-start rounded-lg border bg-white dark:bg-gray-900 transition-colors focus-within:ring-2 focus-within:ring-indigo-500/40 ${
activeCommand
? "border-indigo-300 dark:border-indigo-700"
: "border-gray-200 dark:border-gray-700 focus-within:border-indigo-400 dark:focus-within:border-indigo-600"
}`}
>
{activeCommand && (
<span className="ml-1.5 mt-1.5 flex min-w-0 max-w-full">
<CommandToken
entry={activeCommand}
onRemove={() => {
dropCommand(false);
setFocusTo("message");
}}
/>
</span>
)}
<textarea
ref={textareaRef}
value={input}
onChange={(e) => handleInputChange(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={messagePlaceholder}
aria-label="Message"
aria-autocomplete={commandsOffered ? "list" : undefined}
aria-controls={paletteOpen ? paletteId : undefined}
aria-expanded={commandsOffered ? paletteOpen : undefined}
aria-activedescendant={
paletteOpen ? optionId(paletteId, paletteIndex) : undefined
}
rows={1}
className={`grow basis-32 min-w-0 resize-none bg-transparent px-3 py-2 text-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none ${
typingCommand
? "font-mono text-indigo-700 dark:text-indigo-300"
: "text-gray-800 dark:text-gray-200"
}`}
style={{ overflow: "hidden", maxHeight: "160px" }}
/>
</div>
{loading && onStop ? (
<button
onClick={onStop}
title="Stop generation"
className="shrink-0 w-8 h-8 p-0 flex items-center justify-center rounded-lg mb-0.5 bg-red-500 hover:bg-red-600 text-white shadow-sm hover:shadow transition-all"
>
<Square className="w-3.5 h-3.5 fill-current" />
</button>
) : (
<button
onClick={() => void handleSend().catch(console.error)}
disabled={!canSend}
title="Send message (Enter)"
className={`shrink-0 w-8 h-8 p-0 flex items-center justify-center rounded-lg mb-0.5 transition-all ${
canSend
? "bg-indigo-500 hover:bg-indigo-600 text-white shadow-sm hover:shadow"
: "bg-gray-200 dark:bg-gray-700 text-gray-400 dark:text-gray-500 cursor-not-allowed"
}`}
>
<Send className="w-4 h-4" />
</button>
)}
</div>
</div>
<p
role="note"
className="flex items-center justify-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 text-center"
>
<Bot className="w-3 h-3 shrink-0" aria-hidden="true" />
{AI_DISCLOSURE.chat}
</p>
{/* Compact, the keyboard hint goes (attached files show as chips
anyway); the note that a turn outlives the page stays. */}
{(!compact || (loading && !paused)) && (
<p className="text-xs text-gray-400 dark:text-gray-500 text-center">
{loading && !paused ? (
// Closing the page does not stop the turn: the server finishes
// it and stores the answer (svc-core app/services/chat_socket.py).
"You can leave this page: the answer is saved to this conversation when it's ready."
) : (
<>
Enter to send · Shift+Enter for new line
{formFields.length > 0 && " · Ctrl+Enter from the form"}
{(attachedFiles.length > 0 || uploadingNames.length > 0) &&
` · ${attachedFiles.length + uploadingNames.length} file${attachedFiles.length + uploadingNames.length > 1 ? "s" : ""} attached`}
</>
)}
</p>
)}
</div>
{/* Bounce animation */}
<style>{`
@keyframes chatBounce {
0%, 60%, 100% { transform: translateY(0); }
30% { transform: translateY(-4px); }
}
`}</style>
</div>
);
};
export default ChatPanel;
|