File size: 87,796 Bytes
3e05655 | 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 | import {
Component,
createEffect,
createMemo,
createSignal,
For,
Match,
onMount,
Show,
Switch,
onCleanup,
Index,
type JSX,
type ComponentProps,
} from "solid-js"
import { createStore } from "solid-js/store"
import stripAnsi from "strip-ansi"
import { Dynamic } from "solid-js/web"
import {
AgentPart,
AssistantMessage,
FilePart,
Message as MessageType,
Part as PartType,
ReasoningPart,
Session,
TextPart,
ToolPart,
UserMessage,
Todo,
QuestionAnswer,
QuestionInfo,
} from "@opencode-ai/sdk/v2"
import { useData } from "../context"
import { useFileComponent } from "@opencode-ai/ui/context/file"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { type UiI18n, useI18n } from "@opencode-ai/ui/context/i18n"
import { BasicTool, GenericTool } from "./basic-tool"
import { Accordion } from "@opencode-ai/ui/accordion"
import { StickyAccordionHeader } from "@opencode-ai/ui/sticky-accordion-header"
import { Collapsible } from "@opencode-ai/ui/collapsible"
import { FileIcon } from "@opencode-ai/ui/file-icon"
import { Icon } from "@opencode-ai/ui/icon"
import { ToolErrorCard } from "./tool-error-card"
import { Checkbox } from "@opencode-ai/ui/checkbox"
import { DiffChanges } from "@opencode-ai/ui/diff-changes"
import { Markdown } from "./markdown"
import { ImagePreview } from "@opencode-ai/ui/image-preview"
import { getDirectory as _getDirectory, getFilename } from "@opencode-ai/core/util/path"
import { AttachmentCardV2 } from "../v2/components/attachment-card-v2"
import { CommentCardV2 } from "../v2/components/comment-card-v2"
import { checksum } from "@opencode-ai/core/util/encode"
import { Tooltip } from "@opencode-ai/ui/tooltip"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { Icon as IconV2 } from "@opencode-ai/ui/v2/icon"
import { IconButtonV2 } from "@opencode-ai/ui/v2/icon-button-v2"
import { ButtonV2 } from "@opencode-ai/ui/v2/button-v2"
import { TooltipV2 } from "@opencode-ai/ui/v2/tooltip-v2"
import { Spinner } from "@opencode-ai/ui/spinner"
import { TextShimmer } from "@opencode-ai/ui/text-shimmer"
import { AnimatedCountList } from "./tool-count-summary"
import { ToolStatusTitle } from "./tool-status-title"
import { patchFiles } from "./apply-patch-file"
import { partDefaultOpen } from "./part-default-open"
import { animate } from "motion"
import { attached, inline, kind, typeLabel } from "./message-file"
import { readPartText } from "./message-part-text"
import { SessionProgressIndicatorV2 } from "../v2/components/session-progress-indicator-v2"
async function writeClipboard(text: string): Promise<boolean> {
const body = typeof document === "undefined" ? undefined : document.body
if (body) {
const textarea = document.createElement("textarea")
textarea.value = text
textarea.setAttribute("readonly", "")
textarea.style.position = "fixed"
textarea.style.opacity = "0"
textarea.style.pointerEvents = "none"
body.appendChild(textarea)
textarea.select()
const copied = document.execCommand("copy")
body.removeChild(textarea)
if (copied) return true
}
const clipboard = typeof navigator === "undefined" ? undefined : navigator.clipboard
if (!clipboard?.writeText) return false
return clipboard.writeText(text).then(
() => true,
() => false,
)
}
function ShellSubmessage(props: { text: string; animate?: boolean }) {
let widthRef: HTMLSpanElement | undefined
let valueRef: HTMLSpanElement | undefined
onMount(() => {
if (!props.animate) return
requestAnimationFrame(() => {
if (widthRef) {
animate(widthRef, { width: "auto" }, { type: "spring", visualDuration: 0.25, bounce: 0 })
}
if (valueRef) {
animate(valueRef, { opacity: 1, filter: "blur(0px)" }, { duration: 0.32, ease: [0.16, 1, 0.3, 1] })
}
})
})
return (
<span data-component="shell-submessage" dir="ltr">
<span ref={widthRef} data-slot="shell-submessage-width" style={{ width: props.animate ? "0px" : undefined }}>
<span data-slot="basic-tool-tool-subtitle">
<span
ref={valueRef}
data-slot="shell-submessage-value"
style={props.animate ? { opacity: 0, filter: "blur(2px)" } : undefined}
>
{props.text}
</span>
</span>
</span>
</span>
)
}
interface Diagnostic {
range: {
start: { line: number; character: number }
end: { line: number; character: number }
}
message: string
severity?: number
}
function getDiagnostics(
diagnosticsByFile: Record<string, Diagnostic[]> | undefined,
filePath: string | undefined,
): Diagnostic[] {
if (!diagnosticsByFile || !filePath) return []
const diagnostics = diagnosticsByFile[filePath] ?? []
return diagnostics.filter((d) => d.severity === 1).slice(0, 3)
}
function DiagnosticsDisplay(props: { diagnostics: Diagnostic[] }): JSX.Element {
const i18n = useI18n()
return (
<Show when={props.diagnostics.length > 0}>
<div data-component="diagnostics">
<For each={props.diagnostics}>
{(diagnostic) => (
<div data-slot="diagnostic">
<span data-slot="diagnostic-label">{i18n.t("ui.messagePart.diagnostic.error")}</span>
<span data-slot="diagnostic-location">
[{diagnostic.range.start.line + 1}:{diagnostic.range.start.character + 1}]
</span>
<span data-slot="diagnostic-message">{diagnostic.message}</span>
</div>
)}
</For>
</div>
</Show>
)
}
export interface MessageProps {
message: MessageType
parts: PartType[]
actions?: UserActions
showAssistantCopyPartID?: string | null
showReasoningSummaries?: boolean
useV2Actions?: boolean
comments?: UserMessageComment[]
}
export type SessionAction = (input: { sessionID: string; messageID: string }) => Promise<void> | void
export type UserActions = {
fork?: SessionAction
revert?: SessionAction
openAttachment?: (file: FilePart) => void
}
export type UserMessageComment = {
path: string
comment: string
selection?: {
startLine: number
endLine: number
}
}
export interface MessagePartProps {
part: PartType
message: MessageType
hideDetails?: boolean
defaultOpen?: boolean
toolOpen?: boolean
onToolOpenChange?: (open: boolean) => void
deferToolContent?: boolean
virtualizeDiff?: boolean
onContentRendered?: () => void
showAssistantCopyPartID?: string | null
turnDurationMs?: number
useV2Actions?: boolean
}
function MessageActionButton(
props: Pick<ComponentProps<"button">, "disabled" | "onMouseDown" | "onClick" | "aria-label"> & {
icon: "check" | "copy" | "reset"
label: JSX.Element
useV2?: boolean
},
) {
const icon = () => (props.icon === "copy" ? "outline-copy" : props.icon)
return (
<Show
when={props.useV2}
fallback={
<Tooltip value={props.label} placement="top" gutter={4}>
<IconButton
icon={props.icon}
size="normal"
variant="ghost"
disabled={props.disabled}
onMouseDown={props.onMouseDown}
onClick={props.onClick}
aria-label={props["aria-label"]}
/>
</Tooltip>
}
>
<TooltipV2 value={props.label} placement="top" gutter={4}>
<IconButtonV2
icon={<IconV2 name={icon()} size="small" />}
size="normal"
variant="ghost-muted"
disabled={props.disabled}
onMouseDown={props.onMouseDown}
onClick={props.onClick}
aria-label={props["aria-label"]}
/>
</TooltipV2>
</Show>
)
}
export type PartComponent = Component<MessagePartProps>
export const PART_MAPPING: Record<string, PartComponent | undefined> = {}
const TEXT_RENDER_PACE_MS = 24
const TEXT_RENDER_IMMEDIATE = 512
const TEXT_RENDER_SNAP = /[\s.,!?;:)\]]/
function step(size: number) {
if (size <= 12) return 2
if (size <= 48) return 4
if (size <= 96) return 8
return Math.min(256, Math.ceil(size / 4))
}
function next(text: string, start: number) {
const end = Math.min(text.length, start + step(text.length - start))
const max = Math.min(text.length, end + 8)
for (let i = end; i < max; i++) {
if (TEXT_RENDER_SNAP.test(text[i] ?? "")) return i + 1
}
return end
}
function createPacedValue(getValue: () => string, live?: () => boolean) {
const [value, setValue] = createSignal(getValue())
let shown = getValue()
let timeout: ReturnType<typeof setTimeout> | undefined
const clear = () => {
if (!timeout) return
clearTimeout(timeout)
timeout = undefined
}
const sync = (text: string) => {
shown = text
setValue(text)
}
const run = () => {
timeout = undefined
const text = getValue()
if (!live?.()) {
sync(text)
return
}
if (!text.startsWith(shown) || text.length <= shown.length) {
sync(text)
return
}
if (text.length - shown.length <= TEXT_RENDER_IMMEDIATE) {
sync(text)
return
}
const end = next(text, shown.length)
sync(text.slice(0, end))
if (end < text.length) timeout = setTimeout(run, TEXT_RENDER_PACE_MS)
}
createEffect(() => {
const text = getValue()
if (!live?.()) {
clear()
sync(text)
return
}
if (!text.startsWith(shown) || text.length < shown.length) {
clear()
sync(text)
return
}
if (text.length - shown.length <= TEXT_RENDER_IMMEDIATE) {
clear()
sync(text)
return
}
if (text.length === shown.length || timeout) return
timeout = setTimeout(run, TEXT_RENDER_PACE_MS)
})
onCleanup(() => {
clear()
})
return value
}
function PacedMarkdown(props: { text: string; cacheKey: string; streaming: boolean }) {
const value = createPacedValue(
() => props.text,
() => props.streaming,
)
return (
<Show when={value()}>
<Markdown text={value()} cacheKey={props.cacheKey} streaming={props.streaming} />
</Show>
)
}
function relativizeProjectPath(path: string, directory?: string) {
if (!path) return ""
if (!directory) return path
if (directory === "/") return path
if (directory === "\\") return path
if (path === directory) return ""
const separator = directory.includes("\\") ? "\\" : "/"
const prefix = directory.endsWith(separator) ? directory : directory + separator
if (!path.startsWith(prefix)) return path
return path.slice(directory.length)
}
function getDirectory(path: string | undefined) {
const data = useData()
return relativizeProjectPath(_getDirectory(path), data.directory)
}
import type { IconProps } from "@opencode-ai/ui/icon"
import { normalize, resolveFileDiff } from "./session-diff"
export type ToolInfo = {
icon: IconProps["name"]
title: string
subtitle?: string
}
function agentTitle(i18n: UiI18n, type?: string) {
if (!type) return i18n.t("ui.tool.agent.default")
return i18n.t("ui.tool.agent", { type })
}
const agentTones: Record<string, string> = {
ask: "var(--icon-agent-ask-base)",
build: "var(--icon-agent-build-base)",
docs: "var(--icon-agent-docs-base)",
plan: "var(--icon-agent-plan-base)",
}
const v2AgentTones: Record<string, string> = {
build: "var(--v2-agent-build-solid)",
explore: "var(--v2-agent-explore-solid)",
plan: "var(--v2-agent-plan-solid)",
review: "var(--v2-agent-review-solid)",
writer: "var(--v2-agent-writer-solid)",
}
const agentThemeColors: Record<string, string> = {
primary: "var(--text-interactive-base)",
secondary: "var(--text-base)",
accent: "var(--icon-info-base)",
success: "var(--icon-success-base)",
warning: "var(--icon-warning-base)",
error: "var(--icon-critical-base)",
info: "var(--icon-info-base)",
}
const v2AgentThemeColors: Record<string, string> = {
primary: "var(--v2-text-text-accent)",
secondary: "var(--v2-text-text-muted)",
accent: "var(--v2-icon-icon-accent)",
success: "var(--v2-state-fg-success)",
warning: "var(--v2-state-fg-warning)",
error: "var(--v2-state-fg-danger)",
info: "var(--v2-state-fg-info)",
}
const agentPalette = [
"var(--icon-agent-ask-base)",
"var(--icon-agent-build-base)",
"var(--icon-agent-docs-base)",
"var(--icon-agent-plan-base)",
"var(--syntax-info)",
"var(--syntax-success)",
"var(--syntax-warning)",
"var(--syntax-property)",
"var(--syntax-constant)",
"var(--text-diff-add-base)",
"var(--text-diff-delete-base)",
"var(--icon-warning-base)",
]
function tone(name: string) {
let hash = 0
for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) >>> 0
return agentPalette[hash % agentPalette.length]
}
function taskAgent(
raw: unknown,
list?: readonly { name: string; color?: string }[],
): { name?: string; color?: string; v2Color?: string } {
if (typeof raw !== "string" || !raw) return {}
const key = raw.toLowerCase()
const item = list?.find((entry) => entry.name === raw || entry.name.toLowerCase() === key)
const v2Tone = item?.color ? undefined : v2AgentTones[key]
const color = agentColor(item?.color, agentThemeColors) ?? agentTones[key] ?? tone(key)
const v2Color = agentColor(item?.color, v2AgentThemeColors) ?? v2Tone ?? color
return {
name: item?.name ?? `${raw[0]!.toUpperCase()}${raw.slice(1)}`,
color,
v2Color,
}
}
function agentColor(value: string | undefined, themeColors: Record<string, string>) {
if (!value) return
return themeColors[value] ?? value
}
function newLayout() {
return typeof document !== "undefined" && document.body.hasAttribute("data-new-layout")
}
function webSearchProviderLabel(provider: unknown, i18n: ReturnType<typeof useI18n>) {
const name = provider === "parallel" ? "Parallel" : provider === "exa" ? "Exa" : undefined
if (name) return i18n.t("ui.tool.websearch.provider", { provider: name })
return i18n.t("ui.tool.websearch")
}
export function getToolInfo(
tool: string,
input: any = {},
metadata: Record<string, unknown> | undefined = {},
): ToolInfo {
const i18n = useI18n()
switch (tool) {
case "read":
return {
icon: "glasses",
title: i18n.t("ui.tool.read"),
subtitle: input.filePath ? getFilename(input.filePath) : undefined,
}
case "list":
return {
icon: "bullet-list",
title: i18n.t("ui.tool.list"),
subtitle: input.path ? getFilename(input.path) : undefined,
}
case "glob":
return {
icon: "magnifying-glass-menu",
title: i18n.t("ui.tool.glob"),
subtitle: input.pattern,
}
case "grep":
return {
icon: "magnifying-glass-menu",
title: i18n.t("ui.tool.grep"),
subtitle: input.pattern,
}
case "webfetch":
return {
icon: "window-cursor",
title: i18n.t("ui.tool.webfetch"),
subtitle: input.url,
}
case "websearch":
return {
icon: "window-cursor",
title: webSearchProviderLabel(metadata?.provider, i18n),
subtitle: input.query,
}
case "task": {
const type =
typeof input.subagent_type === "string" && input.subagent_type
? input.subagent_type[0]!.toUpperCase() + input.subagent_type.slice(1)
: undefined
return {
icon: "task",
title: agentTitle(i18n, type),
subtitle: input.description,
}
}
case "bash":
case "shell":
return {
icon: "console",
title: i18n.t("ui.tool.shell"),
subtitle: input.command,
}
case "edit":
return {
icon: "code-lines",
title: i18n.t("ui.messagePart.title.edit"),
subtitle: input.filePath ? getFilename(input.filePath) : undefined,
}
case "write":
return {
icon: "code-lines",
title: i18n.t("ui.messagePart.title.write"),
subtitle: input.filePath ? getFilename(input.filePath) : undefined,
}
case "patch":
case "apply_patch":
return {
icon: "code-lines",
title: i18n.t("ui.tool.patch"),
subtitle: input.files?.length
? `${input.files.length} ${i18n.t(input.files.length > 1 ? "ui.common.file.other" : "ui.common.file.one")}`
: undefined,
}
case "todowrite":
return {
icon: "checklist",
title: i18n.t("ui.tool.todos"),
}
case "question":
return {
icon: "bubble-5",
title: i18n.t("ui.tool.questions"),
}
case "skill":
return {
icon: "brain",
title: input.name || i18n.t("ui.tool.skill"),
}
default:
return {
icon: "mcp",
title: tool,
}
}
}
function urls(text: string | undefined) {
if (!text) return []
const seen = new Set<string>()
return [...text.matchAll(/https?:\/\/[^\s<>"'`)\]]+/g)]
.map((item) => item[0].replace(/[),.;:!?]+$/g, ""))
.filter((item) => {
if (seen.has(item)) return false
seen.add(item)
return true
})
}
function sessionLink(id: string | undefined, href?: (id: string) => string | undefined) {
if (!id) return undefined
return href?.(id)
}
function taskSession(
input: Record<string, any>,
parentID: string | undefined,
sessions: Session[] | undefined,
agents?: readonly { name: string; color?: string }[],
) {
if (!parentID) return undefined
const description = typeof input.description === "string" ? input.description : ""
const agent = taskAgent(input.subagent_type, agents).name
return (sessions ?? [])
.filter((session) => session.parentID === parentID && !session.time?.archived)
.filter((session) => (description ? session.title.startsWith(description) : true))
.filter((session) => (agent ? session.title.includes(`@${agent}`) : true))
.sort((a, b) => (b.time.created ?? 0) - (a.time.created ?? 0))[0]?.id
}
const CONTEXT_GROUP_TOOLS = new Set(["read", "glob", "grep", "list"])
const HIDDEN_TOOLS = new Set(["todowrite"])
function list<T>(value: T[] | undefined | null, fallback: T[]) {
if (Array.isArray(value)) return value
return fallback
}
function same<T>(a: readonly T[] | undefined, b: readonly T[] | undefined) {
if (a === b) return true
if (!a || !b) return false
if (a.length !== b.length) return false
return a.every((x, i) => x === b[i])
}
export type PartRef = {
messageID: string
partID: string
}
export type PartGroup =
| {
key: string
type: "part"
ref: PartRef
}
| {
key: string
type: "context"
refs: PartRef[]
}
function sameRef(a: PartRef, b: PartRef) {
return a.messageID === b.messageID && a.partID === b.partID
}
function sameGroup(a: PartGroup, b: PartGroup) {
if (a === b) return true
if (a.key !== b.key) return false
if (a.type !== b.type) return false
if (a.type === "part") {
if (b.type !== "part") return false
return sameRef(a.ref, b.ref)
}
if (b.type !== "context") return false
if (a.refs.length !== b.refs.length) return false
return a.refs.every((ref, i) => sameRef(ref, b.refs[i]!))
}
export function sameGroups(a: readonly PartGroup[] | undefined, b: readonly PartGroup[] | undefined) {
if (a === b) return true
if (!a || !b) return false
if (a.length !== b.length) return false
return a.every((item, i) => sameGroup(item, b[i]!))
}
export function groupParts(parts: { messageID: string; part: PartType }[]) {
const result: PartGroup[] = []
let start = -1
const flush = (end: number) => {
if (start < 0) return
const first = parts[start]
const last = parts[end]
if (!first || !last) {
start = -1
return
}
result.push({
key: `context:${first.part.id}`,
type: "context",
refs: parts.slice(start, end + 1).map((item) => ({
messageID: item.messageID,
partID: item.part.id,
})),
})
start = -1
}
parts.forEach((item, index) => {
if (isContextGroupTool(item.part)) {
if (start < 0) start = index
return
}
flush(index - 1)
result.push({
key: `part:${item.messageID}:${item.part.id}`,
type: "part",
ref: {
messageID: item.messageID,
partID: item.part.id,
},
})
})
flush(parts.length - 1)
return result
}
function index<T extends { id: string }>(items: readonly T[]) {
return new Map(items.map((item) => [item.id, item] as const))
}
export function renderable(part: PartType, showReasoningSummaries = true) {
if (part.type === "tool") {
if (HIDDEN_TOOLS.has(part.tool)) return false
if (part.tool === "question") return part.state.status !== "pending" && part.state.status !== "running"
return true
}
if (part.type === "text") return !!part.text?.trim()
if (part.type === "reasoning") return showReasoningSummaries && !!part.text?.trim()
return !!PART_MAPPING[part.type]
}
export { partDefaultOpen } from "./part-default-open"
export function AssistantParts(props: {
messages: AssistantMessage[]
showAssistantCopyPartID?: string | null
turnDurationMs?: number
useV2Actions?: boolean
working?: boolean
showReasoningSummaries?: boolean
shellToolDefaultOpen?: boolean
editToolDefaultOpen?: boolean
}) {
const data = useData()
const emptyParts: PartType[] = []
const emptyTools: ToolPart[] = []
const msgs = createMemo(() => index(props.messages))
const part = createMemo(
() =>
new Map(
props.messages.map((message) => [message.id, index(list(data.store.part?.[message.id], emptyParts))] as const),
),
)
const grouped = createMemo(
() =>
groupParts(
props.messages.flatMap((message) =>
list(data.store.part?.[message.id], emptyParts)
.filter((part) => renderable(part, props.showReasoningSummaries ?? true))
.map((part) => ({
messageID: message.id,
part,
})),
),
),
[] as PartGroup[],
{ equals: sameGroups },
)
const last = createMemo(() => grouped().at(-1)?.key)
return (
<Index each={grouped()}>
{(entryAccessor) => {
const entryType = createMemo(() => entryAccessor().type)
return (
<Switch>
<Match when={entryType() === "context"}>
{(() => {
const parts = createMemo(
() => {
const entry = entryAccessor()
if (entry.type !== "context") return emptyTools
return entry.refs
.map((ref) => part().get(ref.messageID)?.get(ref.partID))
.filter((part): part is ToolPart => !!part && isContextGroupTool(part))
},
emptyTools,
{ equals: same },
)
const busy = createMemo(() => props.working && last() === entryAccessor().key)
return (
<Show when={parts().length > 0}>
<ContextToolGroup parts={parts()} busy={busy()} />
</Show>
)
})()}
</Match>
<Match when={entryType() === "part"}>
{(() => {
const message = createMemo(() => {
const entry = entryAccessor()
if (entry.type !== "part") return
return msgs().get(entry.ref.messageID)
})
const item = createMemo(() => {
const entry = entryAccessor()
if (entry.type !== "part") return
return part().get(entry.ref.messageID)?.get(entry.ref.partID)
})
return (
<Show when={message()}>
<Show when={item()}>
<Part
part={item()!}
message={message()!}
showAssistantCopyPartID={props.showAssistantCopyPartID}
turnDurationMs={props.turnDurationMs}
useV2Actions={props.useV2Actions}
defaultOpen={partDefaultOpen(item()!, props.shellToolDefaultOpen, props.editToolDefaultOpen)}
/>
</Show>
</Show>
)
})()}
</Match>
</Switch>
)
}}
</Index>
)
}
function isContextGroupTool(part: PartType): part is ToolPart {
return part.type === "tool" && CONTEXT_GROUP_TOOLS.has(part.tool)
}
function contextToolDetail(part: ToolPart): string | undefined {
const info = getToolInfo(
part.tool,
part.state.input ?? {},
"metadata" in part.state ? part.state.metadata : undefined,
)
if (info.subtitle) return info.subtitle
if (part.state.status === "error") return part.state.error
if ((part.state.status === "running" || part.state.status === "completed") && part.state.title)
return part.state.title
const description = part.state.input?.description
if (typeof description === "string") return description
return undefined
}
function contextToolTrigger(part: ToolPart, i18n: ReturnType<typeof useI18n>) {
const input = (part.state.input ?? {}) as Record<string, unknown>
const path = typeof input.path === "string" ? input.path : "/"
const filePath = typeof input.filePath === "string" ? input.filePath : undefined
const pattern = typeof input.pattern === "string" ? input.pattern : undefined
const include = typeof input.include === "string" ? input.include : undefined
const offset = typeof input.offset === "number" ? input.offset : undefined
const limit = typeof input.limit === "number" ? input.limit : undefined
switch (part.tool) {
case "read": {
const args: string[] = []
if (offset !== undefined) args.push("offset=" + offset)
if (limit !== undefined) args.push("limit=" + limit)
return {
title: i18n.t("ui.tool.read"),
subtitle: filePath ? getFilename(filePath) : "",
args,
}
}
case "list":
return {
title: i18n.t("ui.tool.list"),
subtitle: getDirectory(path),
}
case "glob":
return {
title: i18n.t("ui.tool.glob"),
subtitle: getDirectory(path),
args: pattern ? ["pattern=" + pattern] : [],
}
case "grep": {
const args: string[] = []
if (pattern) args.push("pattern=" + pattern)
if (include) args.push("include=" + include)
return {
title: i18n.t("ui.tool.grep"),
subtitle: getDirectory(path),
args,
}
}
default: {
const info = getToolInfo(part.tool, input, "metadata" in part.state ? part.state.metadata : undefined)
return {
title: info.title,
subtitle: info.subtitle || contextToolDetail(part),
args: [],
}
}
}
}
function contextToolSummary(parts: ToolPart[]) {
const read = parts.filter((part) => part.tool === "read").length
const search = parts.filter((part) => part.tool === "glob" || part.tool === "grep").length
const list = parts.filter((part) => part.tool === "list").length
return { read, search, list }
}
function ExaOutput(props: { output?: string }) {
const links = createMemo(() => urls(props.output))
return (
<Show when={links().length > 0}>
<div data-component="exa-tool-output">
<div data-slot="exa-tool-links">
<For each={links()}>
{(url) => (
<a
data-slot="exa-tool-link"
href={url}
target="_blank"
rel="noopener noreferrer"
onClick={(event) => event.stopPropagation()}
>
{url}
</a>
)}
</For>
</div>
</div>
</Show>
)
}
export function registerPartComponent(type: string, component: PartComponent) {
PART_MAPPING[type] = component
}
export function Message(props: MessageProps) {
return (
<Switch>
<Match when={props.message.role === "user" && props.message}>
{(userMessage) => (
<UserMessageDisplay
message={userMessage() as UserMessage}
parts={props.parts}
actions={props.actions}
useV2Actions={props.useV2Actions}
comments={props.comments}
/>
)}
</Match>
<Match when={props.message.role === "assistant" && props.message}>
{(assistantMessage) => (
<AssistantMessageDisplay
message={assistantMessage() as AssistantMessage}
parts={props.parts}
showAssistantCopyPartID={props.showAssistantCopyPartID}
showReasoningSummaries={props.showReasoningSummaries}
useV2Actions={props.useV2Actions}
/>
)}
</Match>
</Switch>
)
}
export function AssistantMessageDisplay(props: {
message: AssistantMessage
parts: PartType[]
showAssistantCopyPartID?: string | null
showReasoningSummaries?: boolean
useV2Actions?: boolean
}) {
const emptyTools: ToolPart[] = []
const part = createMemo(() => index(props.parts))
const grouped = createMemo(
() =>
groupParts(
props.parts
.filter((part) => renderable(part, props.showReasoningSummaries ?? true))
.map((part) => ({
messageID: props.message.id,
part,
})),
),
[] as PartGroup[],
{ equals: sameGroups },
)
return (
<Index each={grouped()}>
{(entryAccessor) => {
const entryType = createMemo(() => entryAccessor().type)
return (
<Switch>
<Match when={entryType() === "context"}>
{(() => {
const parts = createMemo(
() => {
const entry = entryAccessor()
if (entry.type !== "context") return emptyTools
return entry.refs
.map((ref) => part().get(ref.partID))
.filter((part): part is ToolPart => !!part && isContextGroupTool(part))
},
emptyTools,
{ equals: same },
)
return (
<Show when={parts().length > 0}>
<ContextToolGroup parts={parts()} />
</Show>
)
})()}
</Match>
<Match when={entryType() === "part"}>
{(() => {
const item = createMemo(() => {
const entry = entryAccessor()
if (entry.type !== "part") return
return part().get(entry.ref.partID)
})
return (
<Show when={item()}>
<Part
part={item()!}
message={props.message}
showAssistantCopyPartID={props.showAssistantCopyPartID}
useV2Actions={props.useV2Actions}
/>
</Show>
)
})()}
</Match>
</Switch>
)
}}
</Index>
)
}
export function ContextToolGroup(props: {
parts: ToolPart[]
busy?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
onSizeChange?: () => void
}) {
const i18n = useI18n()
const [localOpen, setLocalOpen] = createSignal(false)
const open = () => props.open ?? localOpen()
const pending = createMemo(
() =>
!!props.busy || props.parts.some((part) => part.state.status === "pending" || part.state.status === "running"),
)
const summary = createMemo(() => contextToolSummary(props.parts))
const handleOpenChange = (value: boolean) => {
if (props.open === undefined) setLocalOpen(value)
props.onOpenChange?.(value)
props.onSizeChange?.()
}
return (
<Collapsible
open={open()}
onOpenChange={handleOpenChange}
variant="ghost"
class="tool-collapsible"
data-timeline-part-ids={props.parts.map((part) => part.id).join(",")}
>
<Collapsible.Trigger>
<div data-component="context-tool-group-trigger">
<span
data-slot="context-tool-group-title"
class="min-w-0 flex items-center gap-2 text-14-medium text-text-strong"
>
<span data-slot="context-tool-group-label" class="shrink-0">
<ToolStatusTitle
active={pending()}
activeText={i18n.t("ui.sessionTurn.status.gatheringContext")}
doneText={i18n.t("ui.sessionTurn.status.gatheredContext")}
split={false}
/>
</span>
<span
data-slot="context-tool-group-summary"
class="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap font-normal text-text-base"
>
<AnimatedCountList
items={[
{
key: "ui.messagePart.context.read",
count: summary().read,
},
{
key: "ui.messagePart.context.search",
count: summary().search,
},
{
key: "ui.messagePart.context.list",
count: summary().list,
},
]}
fallback=""
/>
</span>
</span>
<Collapsible.Arrow />
</div>
</Collapsible.Trigger>
<Collapsible.Content>
<div data-component="context-tool-group-list">
<Index each={props.parts}>
{(partAccessor) => {
const trigger = createMemo(() => contextToolTrigger(partAccessor(), i18n))
const running = createMemo(
() => partAccessor().state.status === "pending" || partAccessor().state.status === "running",
)
return (
<div data-slot="context-tool-group-item">
<div data-component="tool-trigger">
<div data-slot="basic-tool-tool-trigger-content">
<div data-slot="basic-tool-tool-info">
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<span data-slot="basic-tool-tool-title">
<TextShimmer text={trigger().title} active={running()} />
</span>
<Show when={trigger().subtitle}>
<span data-slot="basic-tool-tool-subtitle">{trigger().subtitle}</span>
</Show>
<Show when={trigger().args?.length}>
<For each={trigger().args}>
{(arg) => <span data-slot="basic-tool-tool-arg">{arg}</span>}
</For>
</Show>
</div>
</div>
</div>
</div>
</div>
</div>
)
}}
</Index>
</div>
</Collapsible.Content>
</Collapsible>
)
}
function UserMessageComments(props: { comments: UserMessageComment[]; bounded: boolean }) {
const i18n = useI18n()
const [state, setState] = createStore({ expanded: false })
const comments = createMemo(() => (props.bounded && !state.expanded ? props.comments.slice(0, 5) : props.comments))
return (
<div data-slot="user-message-comments" data-bounded={props.bounded ? "true" : undefined}>
<For each={comments()}>
{(comment) => (
<CommentCardV2
comment={comment.comment}
path={comment.path}
selection={comment.selection}
title={comment.comment}
tooltip
wide
/>
)}
</For>
<Show when={props.bounded && props.comments.length > 5 && !state.expanded}>
<ButtonV2 size="small" variant="ghost-muted" onClick={() => setState("expanded", true)}>
{i18n.t("ui.common.showMore")}
</ButtonV2>
</Show>
</div>
)
}
export function UserMessageDisplay(props: {
message: UserMessage
parts: PartType[]
actions?: UserActions
useV2Actions?: boolean
comments?: UserMessageComment[]
}) {
const data = useData()
const dialog = useDialog()
const i18n = useI18n()
const [state, setState] = createStore({
copied: false,
busy: false,
})
const copied = () => state.copied
const busy = () => state.busy
const textPart = createMemo(
() => props.parts?.find((p) => p.type === "text" && !(p as TextPart).synthetic) as TextPart | undefined,
)
const text = createMemo(() => textPart()?.text || "")
const files = createMemo(() => (props.parts?.filter((p) => p.type === "file") as FilePart[]) ?? [])
const attachments = createMemo(() => files().filter(attached))
const messageComments = createMemo(() => (newLayout() ? (props.comments ?? []) : []))
const inlineFiles = createMemo(() => files().filter(inline))
const agents = createMemo(() => (props.parts?.filter((p) => p.type === "agent") as AgentPart[]) ?? [])
const model = createMemo(() => {
const providerID = props.message.model?.providerID
const modelID = props.message.model?.modelID
if (!providerID || !modelID) return ""
const match = data.store.provider?.all?.get(providerID)
return match?.models?.[modelID]?.name ?? modelID
})
const timefmt = createMemo(() => new Intl.DateTimeFormat(i18n.locale(), { timeStyle: "short" }))
const stamp = createMemo(() => {
const created = props.message.time?.created
if (typeof created !== "number") return ""
return timefmt().format(created)
})
const metaHead = createMemo(() => {
const agent = props.message.agent
const items = [agent ? agent[0]?.toUpperCase() + agent.slice(1) : "", model()]
return items.filter((x) => !!x).join("\u00A0\u00B7\u00A0")
})
const metaTail = stamp
const openImagePreview = (url: string, alt?: string) => {
dialog.show(() => <ImagePreview src={url} alt={alt} />)
}
const handleCopy = async () => {
const content = text()
if (!content) return
if (await writeClipboard(content)) {
setState("copied", true)
setTimeout(() => setState("copied", false), 2000)
}
}
const revert = () => {
const act = props.actions?.revert
if (!act || busy()) return
setState("busy", true)
void Promise.resolve()
.then(() =>
act({
sessionID: props.message.sessionID,
messageID: props.message.id,
}),
)
.finally(() => setState("busy", false))
}
const renderAttachments = () => (
<Show when={attachments().length > 0}>
<div data-slot="user-message-attachments">
<For each={attachments()}>
{(file) => {
const type = kind(file)
const name = file.filename ?? i18n.t("ui.message.attachment.alt")
return (
<Show
when={newLayout() && type === "file"}
fallback={
<div
data-slot="user-message-attachment"
data-type={type}
data-clickable={type === "image" ? "true" : undefined}
title={type === "file" ? name : undefined}
onClick={() => {
if (type === "image") openImagePreview(file.url, name)
}}
>
<Show
when={type === "image"}
fallback={
<div data-slot="user-message-attachment-file">
<FileIcon node={{ path: name, type: "file" }} />
<span data-slot="user-message-attachment-name">{name}</span>
</div>
}
>
<img data-slot="user-message-attachment-image" src={file.url} alt={name} />
</Show>
</div>
}
>
<AttachmentCardV2
title={getFilename(name)}
hover={name}
clickable={!!props.actions?.openAttachment}
onClick={() => props.actions?.openAttachment?.(file)}
>
{typeLabel(name, file.mime, i18n.t("ui.common.file"))}
</AttachmentCardV2>
</Show>
)
}}
</For>
</div>
</Show>
)
return (
<div data-component="user-message" data-timeline-part-id={textPart()?.id}>
<Show when={!props.useV2Actions}>{renderAttachments()}</Show>
<Show
when={text()}
fallback={
<Show when={messageComments().length > 0}>
<UserMessageComments comments={messageComments()} bounded={false} />
</Show>
}
>
<div data-slot="user-message-body">
<div
data-slot="user-message-text"
dir="auto"
data-comments={messageComments().length > 0 ? "true" : undefined}
>
<HighlightedText text={text()} references={inlineFiles()} agents={agents()} />
<Show when={messageComments().length > 0}>
<UserMessageComments comments={messageComments()} bounded />
</Show>
</div>
</div>
</Show>
<Show when={props.useV2Actions}>{renderAttachments()}</Show>
<Show when={text() || (props.useV2Actions && messageComments().length > 0)}>
<div data-slot="user-message-copy-wrapper">
<Show when={metaHead() || metaTail()}>
<span data-slot="user-message-meta-wrap">
<Show when={metaHead()}>
<span data-slot="user-message-meta" class="text-12-regular text-text-weak cursor-default">
{metaHead()}
</span>
</Show>
<Show when={metaHead() && metaTail()}>
<span data-slot="user-message-meta-sep" class="text-12-regular text-text-weak cursor-default">
{"\u00A0\u00B7\u00A0"}
</span>
</Show>
<Show when={metaTail()}>
<span data-slot="user-message-meta-tail" class="text-12-regular text-text-weak cursor-default">
{metaTail()}
</span>
</Show>
</span>
</Show>
<Show when={props.actions?.revert}>
<MessageActionButton
icon="reset"
label={i18n.t("ui.message.revertMessage")}
useV2={props.useV2Actions}
disabled={!!busy()}
onMouseDown={(event) => event.preventDefault()}
onClick={(event) => {
event.stopPropagation()
revert()
}}
aria-label={i18n.t("ui.message.revertMessage")}
/>
</Show>
<Show when={text()}>
<MessageActionButton
icon={copied() ? "check" : "copy"}
label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyMessage")}
useV2={props.useV2Actions}
onMouseDown={(event) => event.preventDefault()}
onClick={(event) => {
event.stopPropagation()
void handleCopy()
}}
aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyMessage")}
/>
</Show>
</div>
</Show>
</div>
)
}
type HighlightSegment = { text: string; type?: "file" | "agent" }
function HighlightedText(props: { text: string; references: FilePart[]; agents: AgentPart[] }) {
const segments = createMemo(() => {
const text = props.text
const allRefs: { start: number; end: number; type: "file" | "agent" }[] = [
...props.references
.filter((r) => r.source?.text?.start !== undefined && r.source?.text?.end !== undefined)
.map((r) => ({ start: r.source!.text!.start, end: r.source!.text!.end, type: "file" as const })),
...props.agents
.filter((a) => a.source?.start !== undefined && a.source?.end !== undefined)
.map((a) => ({ start: a.source!.start, end: a.source!.end, type: "agent" as const })),
].sort((a, b) => a.start - b.start)
const result: HighlightSegment[] = []
let lastIndex = 0
for (const ref of allRefs) {
if (ref.start < lastIndex) continue
if (ref.start > lastIndex) {
result.push({ text: text.slice(lastIndex, ref.start) })
}
result.push({ text: text.slice(ref.start, ref.end), type: ref.type })
lastIndex = ref.end
}
if (lastIndex < text.length) {
result.push({ text: text.slice(lastIndex) })
}
return result
})
return <For each={segments()}>{(segment) => <span data-highlight={segment.type}>{segment.text}</span>}</For>
}
export function Part(props: MessagePartProps) {
const component = createMemo(() => PART_MAPPING[props.part.type])
return (
<Show when={component()}>
<Dynamic
component={component()}
part={props.part}
message={props.message}
hideDetails={props.hideDetails}
defaultOpen={props.defaultOpen}
toolOpen={props.toolOpen}
onToolOpenChange={props.onToolOpenChange}
deferToolContent={props.deferToolContent}
virtualizeDiff={props.virtualizeDiff}
onContentRendered={props.onContentRendered}
showAssistantCopyPartID={props.showAssistantCopyPartID}
turnDurationMs={props.turnDurationMs}
useV2Actions={props.useV2Actions}
/>
</Show>
)
}
export interface ToolProps {
input: Record<string, any>
metadata: Record<string, any>
tool: string
sessionID?: string
output?: string
status?: string
hideDetails?: boolean
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
deferContent?: boolean
virtualizeDiff?: boolean
onContentRendered?: () => void
forceOpen?: boolean
locked?: boolean
}
export type ToolComponent = Component<ToolProps>
const state: Record<
string,
{
name: string
render?: ToolComponent
}
> = {}
export function registerTool(input: { name: string; render?: ToolComponent }) {
state[input.name] = input
return input
}
export function getTool(name: string) {
return state[name === "apply_patch" ? "patch" : name === "bash" ? "shell" : name]?.render
}
export const ToolRegistry = {
register: registerTool,
render: getTool,
}
function ToolFileAccordion(props: { path: string; actions?: JSX.Element; children: JSX.Element }) {
const value = createMemo(() => props.path || "tool-file")
return (
<Accordion
multiple
data-scope="apply-patch"
style={{ "--sticky-accordion-offset": "calc(32px + var(--tool-content-gap))" }}
defaultValue={[value()]}
>
<Accordion.Item value={value()}>
<StickyAccordionHeader>
<Accordion.Trigger>
<div data-slot="apply-patch-trigger-content">
<div data-slot="apply-patch-file-info">
<FileIcon node={{ path: props.path, type: "file" }} />
<div data-slot="apply-patch-file-name-container">
<Show when={props.path.includes("/")}>
<span data-slot="apply-patch-directory">{`\u202A${getDirectory(props.path)}\u202C`}</span>
</Show>
<span data-slot="apply-patch-filename">{getFilename(props.path)}</span>
</div>
</div>
<div data-slot="apply-patch-trigger-actions">
{props.actions}
<Icon name="chevron-grabber-vertical" size="small" />
</div>
</div>
</Accordion.Trigger>
</StickyAccordionHeader>
<Accordion.Content>{props.children}</Accordion.Content>
</Accordion.Item>
</Accordion>
)
}
PART_MAPPING["tool"] = function ToolPartDisplay(props) {
const data = useData()
const i18n = useI18n()
const part = () => props.part as ToolPart
if (part().tool === "todowrite") return null
const hideQuestion = createMemo(
() => part().tool === "question" && (part().state.status === "pending" || part().state.status === "running"),
)
const emptyInput: Record<string, any> = {}
const emptyMetadata: Record<string, any> = {}
const input = () => part().state?.input ?? emptyInput
// @ts-expect-error
const partMetadata = () => part().state?.metadata ?? emptyMetadata
const taskId = createMemo(() => {
if (part().tool !== "task") return
const value = partMetadata().sessionId
if (typeof value === "string" && value) return value
})
const taskHref = createMemo(() => {
if (part().tool !== "task") return
return sessionLink(taskId(), data.sessionHref)
})
const taskSubtitle = createMemo(() => {
if (part().tool !== "task") return undefined
const value = input().description
if (typeof value === "string" && value) return value
return taskId()
})
const render = createMemo(() => ToolRegistry.render(part().tool) ?? GenericTool)
const controlledOpen = () => (props.onToolOpenChange ? (props.toolOpen ?? props.defaultOpen) : undefined)
const handleToolOpenChange = (open: boolean) => props.onToolOpenChange?.(open)
return (
<Show when={!hideQuestion()}>
<div data-component="tool-part-wrapper" data-timeline-part-id={part().id}>
<Switch>
<Match when={part().state.status === "error" && (part().state as any).error}>
{(error) => {
const cleaned = error().replace("Error: ", "")
if (part().tool === "question" && cleaned.includes("dismissed this question")) {
return (
<div style="width: 100%; display: flex; justify-content: flex-end;">
<span class="text-13-regular text-text-weak cursor-default">
{i18n.t("ui.messagePart.questions.dismissed")}
</span>
</div>
)
}
return (
<ToolErrorCard
tool={part().tool}
error={error()}
title={
part().tool === "websearch" ? webSearchProviderLabel(partMetadata().provider, i18n) : undefined
}
defaultOpen={props.defaultOpen}
open={controlledOpen()}
onOpenChange={props.onToolOpenChange ? handleToolOpenChange : undefined}
subtitle={taskSubtitle()}
href={taskHref()}
onSubtitleClick={(event) => {
if (!data.navigateToSession) return
if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
const id = taskId()
if (!id) return
event.preventDefault()
data.navigateToSession(id)
}}
/>
)
}}
</Match>
<Match when={true}>
<Dynamic
component={render()}
input={input()}
tool={part().tool}
sessionID={part().sessionID}
metadata={partMetadata()}
// @ts-expect-error
output={part().state.output}
status={part().state.status}
hideDetails={props.hideDetails}
defaultOpen={props.defaultOpen}
open={controlledOpen()}
onOpenChange={props.onToolOpenChange ? handleToolOpenChange : undefined}
deferContent={props.deferToolContent}
virtualizeDiff={props.virtualizeDiff}
onContentRendered={props.onContentRendered}
/>
</Match>
</Switch>
</div>
</Show>
)
}
export function MessageDivider(props: { label: string }) {
return (
<div data-component="compaction-part">
<div data-slot="compaction-part-divider">
<span data-slot="compaction-part-line" />
<span data-slot="compaction-part-label" class="text-12-regular text-text-weak">
{props.label}
</span>
<span data-slot="compaction-part-line" />
</div>
</div>
)
}
PART_MAPPING["compaction"] = function CompactionPartDisplay() {
const i18n = useI18n()
return <MessageDivider label={i18n.t("ui.messagePart.compaction")} />
}
PART_MAPPING["text"] = function TextPartDisplay(props) {
const data = useData()
const i18n = useI18n()
const numfmt = createMemo(() => new Intl.NumberFormat(i18n.locale()))
const part = () => props.part as TextPart
const interrupted = createMemo(
() =>
props.message.role === "assistant" && (props.message as AssistantMessage).error?.name === "MessageAbortedError",
)
const model = createMemo(() => {
if (props.message.role !== "assistant") return ""
const message = props.message as AssistantMessage
const match = data.store.provider?.all?.get(message.providerID)
return match?.models?.[message.modelID]?.name ?? message.modelID
})
const duration = createMemo(() => {
if (props.message.role !== "assistant") return ""
const message = props.message as AssistantMessage
const completed = message.time.completed
const ms =
typeof props.turnDurationMs === "number"
? props.turnDurationMs
: typeof completed === "number"
? completed - message.time.created
: -1
if (!(ms >= 0)) return ""
const total = Math.round(ms / 1000)
if (total < 60) return i18n.t("ui.message.duration.seconds", { count: numfmt().format(total) })
const minutes = Math.floor(total / 60)
const seconds = total % 60
return i18n.t("ui.message.duration.minutesSeconds", {
minutes: numfmt().format(minutes),
seconds: numfmt().format(seconds),
})
})
const meta = createMemo(() => {
if (props.message.role !== "assistant") return ""
const agent = (props.message as AssistantMessage).agent
const items = [
agent ? agent[0]?.toUpperCase() + agent.slice(1) : "",
model(),
duration(),
interrupted() ? i18n.t("ui.message.interrupted") : "",
]
return items.filter((x) => !!x).join(" \u00B7 ")
})
const streaming = createMemo(
() => props.message.role === "assistant" && typeof (props.message as AssistantMessage).time.completed !== "number",
)
const text = () => readPartText(data.store.part_text_accum_delta, part())
const isLastTextPart = createMemo(() => {
const last = (data.store.part?.[props.message.id] ?? [])
.filter((item): item is TextPart => item?.type === "text" && !!item.text?.trim())
.at(-1)
return last?.id === part().id
})
const showCopy = createMemo(() => {
if (props.message.role !== "assistant") return isLastTextPart()
if (props.showAssistantCopyPartID === null) return false
if (typeof props.showAssistantCopyPartID === "string") return props.showAssistantCopyPartID === part().id
return isLastTextPart()
})
const [copied, setCopied] = createSignal(false)
const handleCopy = async () => {
const content = text()
if (!content) return
if (await writeClipboard(content)) {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
}
return (
<Show when={text()}>
<div data-component="text-part" data-timeline-part-id={part().id}>
<div data-slot="text-part-body">
<PacedMarkdown text={text()} cacheKey={part().id} streaming={streaming()} />
</div>
<Show when={showCopy()}>
<div data-slot="text-part-copy-wrapper" data-interrupted={interrupted() ? "" : undefined}>
<MessageActionButton
icon={copied() ? "check" : "copy"}
label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
useV2={props.useV2Actions}
onMouseDown={(event) => event.preventDefault()}
onClick={handleCopy}
aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
/>
<Show when={meta()}>
<span data-slot="text-part-meta" class="text-12-regular text-text-weak cursor-default">
{meta()}
</span>
</Show>
</div>
</Show>
</div>
</Show>
)
}
PART_MAPPING["reasoning"] = function ReasoningPartDisplay(props) {
const data = useData()
const part = () => props.part as ReasoningPart
const streaming = createMemo(
() => props.message.role === "assistant" && typeof (props.message as AssistantMessage).time.completed !== "number",
)
const text = () => readPartText(data.store.part_text_accum_delta, part())
return (
<Show when={text()}>
<div data-component="reasoning-part" data-timeline-part-id={part().id}>
<PacedMarkdown text={text()} cacheKey={part().id} streaming={streaming()} />
</div>
</Show>
)
}
ToolRegistry.register({
name: "read",
render(props) {
const data = useData()
const i18n = useI18n()
const args: string[] = []
if (props.input.offset) args.push("offset=" + props.input.offset)
if (props.input.limit) args.push("limit=" + props.input.limit)
const loaded = createMemo(() => {
if (props.status !== "completed") return []
const value = props.metadata.loaded
if (!value || !Array.isArray(value)) return []
return value.filter((p): p is string => typeof p === "string")
})
return (
<>
<BasicTool
{...props}
icon="glasses"
trigger={{
title: i18n.t("ui.tool.read"),
subtitle: props.input.filePath ? getFilename(props.input.filePath) : "",
args,
}}
/>
<For each={loaded()}>
{(filepath) => (
<div data-component="tool-loaded-file">
<Icon name="enter" size="small" />
<span>
{i18n.t("ui.tool.loaded")} {relativizeProjectPath(filepath, data.directory)}
</span>
</div>
)}
</For>
</>
)
},
})
ToolRegistry.register({
name: "list",
render(props) {
const i18n = useI18n()
return (
<BasicTool
{...props}
icon="bullet-list"
trigger={{ title: i18n.t("ui.tool.list"), subtitle: getDirectory(props.input.path || "/") }}
>
<Show when={props.output}>
<div
data-component="tool-output"
data-scrollable
tabIndex={0}
role="region"
aria-label={i18n.t("ui.scrollView.ariaLabel")}
>
<Markdown text={props.output!} />
</div>
</Show>
</BasicTool>
)
},
})
ToolRegistry.register({
name: "glob",
render(props) {
const i18n = useI18n()
return (
<BasicTool
{...props}
icon="magnifying-glass-menu"
trigger={{
title: i18n.t("ui.tool.glob"),
subtitle: getDirectory(props.input.path || "/"),
args: props.input.pattern ? ["pattern=" + props.input.pattern] : [],
}}
>
<Show when={props.output}>
<div
data-component="tool-output"
data-scrollable
tabIndex={0}
role="region"
aria-label={i18n.t("ui.scrollView.ariaLabel")}
>
<Markdown text={props.output!} />
</div>
</Show>
</BasicTool>
)
},
})
ToolRegistry.register({
name: "grep",
render(props) {
const i18n = useI18n()
const args: string[] = []
if (props.input.pattern) args.push("pattern=" + props.input.pattern)
if (props.input.include) args.push("include=" + props.input.include)
return (
<BasicTool
{...props}
icon="magnifying-glass-menu"
trigger={{
title: i18n.t("ui.tool.grep"),
subtitle: getDirectory(props.input.path || "/"),
args,
}}
>
<Show when={props.output}>
<div
data-component="tool-output"
data-scrollable
tabIndex={0}
role="region"
aria-label={i18n.t("ui.scrollView.ariaLabel")}
>
<Markdown text={props.output!} />
</div>
</Show>
</BasicTool>
)
},
})
ToolRegistry.register({
name: "webfetch",
render(props) {
const i18n = useI18n()
const pending = createMemo(() => props.status === "pending" || props.status === "running")
const url = createMemo(() => {
const value = props.input.url
if (typeof value !== "string") return ""
return value
})
return (
<BasicTool
{...props}
hideDetails
icon="window-cursor"
trigger={
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<span data-slot="basic-tool-tool-title">
<TextShimmer text={i18n.t("ui.tool.webfetch")} active={pending()} />
</span>
<Show when={!pending() && url()}>
<a
data-slot="basic-tool-tool-subtitle"
class="clickable subagent-link"
href={url()}
target="_blank"
rel="noopener noreferrer"
onClick={(event) => event.stopPropagation()}
>
{url()}
</a>
</Show>
</div>
<Show when={!pending() && url()}>
<div data-component="tool-action">
<Icon name="square-arrow-top-right" size="small" />
</div>
</Show>
</div>
}
/>
)
},
})
ToolRegistry.register({
name: "websearch",
render(props) {
const i18n = useI18n()
const query = createMemo(() => {
const value = props.input.query
if (typeof value !== "string") return ""
return value
})
const title = createMemo(() => webSearchProviderLabel(props.metadata.provider, i18n))
return (
<BasicTool
{...props}
icon="window-cursor"
trigger={{
title: title(),
subtitle: query(),
subtitleClass: "exa-tool-query",
}}
>
<ExaOutput output={props.output} />
</BasicTool>
)
},
})
ToolRegistry.register({
name: "task",
render(props) {
const data = useData()
const i18n = useI18n()
const childSessionId = createMemo(() => {
const value = props.metadata.sessionId
if (typeof value === "string" && value) return value
return taskSession(props.input, data.sessionID, data.store.session, data.store.agent)
})
const agent = createMemo(() => taskAgent(props.input.subagent_type, data.store.agent))
const title = createMemo(() => agent().name ?? i18n.t("ui.tool.agent.default"))
const tone = createMemo(() => agent().color)
const v2Tone = createMemo(() => agent().v2Color)
const subtitle = createMemo(() => {
const value =
typeof props.input.description === "string" && props.input.description
? props.input.description
: childSessionId()
if (!value) return value
if (props.metadata.background === true) return `${value} (background)`
return value
})
const running = createMemo(() => props.status === "pending" || props.status === "running")
const href = createMemo(() => sessionLink(childSessionId(), data.sessionHref))
const clickable = createMemo(() => !!(childSessionId() && (data.navigateToSession || href())))
const open = () => {
const id = childSessionId()
if (!id) return
data.navigateToSession?.(id)
}
const navigate = (event: MouseEvent) => {
if (!data.navigateToSession) return
if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
event.preventDefault()
open()
}
const navigateKey = (event: KeyboardEvent) => {
if (!clickable() || href()) return
if (event.key !== "Enter" && event.key !== " ") return
event.preventDefault()
open()
}
const trigger = () => (
<div
data-component="task-tool-card"
style={{
"--task-agent-color": v2Tone(),
"--task-agent-legacy-color": tone(),
}}
>
<div data-component="task-tool-surface">
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<Show
when={running()}
fallback={
<Show when={newLayout()}>
<span data-component="task-tool-icon">
<Icon name="subagent" size="small" />
</span>
</Show>
}
>
<span data-component="task-tool-spinner" style={{ color: tone() ?? "var(--icon-interactive-base)" }}>
<Show when={newLayout()} fallback={<Spinner />}>
<SessionProgressIndicatorV2
style={{ color: v2Tone() ?? "light-dark(var(--v2-text-text-base), #ffffff)" }}
/>
</Show>
</span>
</Show>
<span data-component="task-tool-title">{title()}</span>
<Show when={subtitle()}>
<span data-slot="basic-tool-tool-subtitle">{subtitle()}</span>
</Show>
</div>
</div>
</div>
<Show when={clickable()}>
<div data-component="task-tool-action">
<Icon name="square-arrow-top-right" size="small" />
</div>
</Show>
</div>
)
return (
<BasicTool
icon="task"
status={props.status}
trigger={trigger()}
hideDetails
triggerAsLink
triggerHref={href()}
clickable={clickable()}
onTriggerClick={navigate}
onTriggerKeyDown={navigateKey}
/>
)
},
})
ToolRegistry.register({
name: "shell",
render(props) {
const i18n = useI18n()
const pending = () => props.status === "pending" || props.status === "running"
const sawPending = pending()
const text = createMemo(() => {
const cmd = props.input.command ?? props.metadata.command ?? ""
const out = stripAnsi(props.output || props.metadata.output || "").replace(/\r\n?/g, "\n")
return `$ ${cmd}${out ? "\n\n" + out : ""}`
})
const [copied, setCopied] = createSignal(false)
const handleCopy = async () => {
const content = text()
if (!content) return
if (await writeClipboard(content)) {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
}
return (
<BasicTool
{...props}
icon="console"
allowOpenWhilePending
trigger={(open) => (
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<span data-slot="basic-tool-tool-title">
<TextShimmer text={i18n.t("ui.tool.shell")} active={pending()} />
</span>
<Show when={!open() && props.input.command}>
<ShellSubmessage text={props.input.command} animate={sawPending} />
</Show>
</div>
</div>
)}
>
<div data-component="bash-output" dir="ltr">
<div data-slot="bash-copy">
<TooltipV2 value={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")} placement="top">
<IconButtonV2
icon={<IconV2 name={copied() ? "check" : "outline-copy"} size="small" />}
size="normal"
variant="ghost-muted"
onMouseDown={(e) => e.preventDefault()}
onClick={handleCopy}
aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copy")}
/>
</TooltipV2>
</div>
<div
data-slot="bash-scroll"
data-scrollable
tabIndex={0}
role="region"
aria-label={i18n.t("ui.scrollView.ariaLabel")}
>
<pre data-slot="bash-pre">
<code>{text()}</code>
</pre>
</div>
</div>
</BasicTool>
)
},
})
ToolRegistry.register({
name: "edit",
render(props) {
const i18n = useI18n()
const fileComponent = useFileComponent()
const diagnostics = createMemo(() => getDiagnostics(props.metadata.diagnostics, props.input.filePath))
const path = createMemo(() => props.metadata?.filediff?.file || props.input.filePath || "")
const filename = () => getFilename(props.input.filePath ?? "")
const pending = () => props.status === "pending" || props.status === "running"
const diffSource = createMemo(
() => {
const filediff = props.metadata?.filediff
if (!filediff) return
return {
file: filediff.file || props.input.filePath || "",
patch: typeof filediff.patch === "string" ? filediff.patch : undefined,
before: typeof filediff.before === "string" ? filediff.before : undefined,
after: typeof filediff.after === "string" ? filediff.after : undefined,
}
},
undefined,
{
equals: (a, b) =>
a?.file === b?.file && a?.patch === b?.patch && a?.before === b?.before && a?.after === b?.after,
},
)
const fileCompProps = createMemo(() => {
try {
const source = diffSource()
if (source) {
const fileDiff = resolveFileDiff(source)
if (fileDiff) return { fileDiff, hunkSeparators: fileDiff.isPartial ? "simple" : "line-info-basic" }
}
} catch {}
return {
before: {
name: props.metadata?.filediff?.file || props.input.filePath,
contents: props.metadata?.filediff?.before || props.input.oldString || "",
},
after: {
name: props.metadata?.filediff?.file || props.input.filePath,
contents: props.metadata?.filediff?.after || props.input.newString || "",
},
}
})
return (
<div data-component="edit-tool">
<BasicTool
{...props}
icon="code-lines"
defer={props.deferContent !== false}
trigger={
<div data-component="edit-trigger">
<div data-slot="message-part-title-area">
<div data-slot="message-part-title">
<span data-slot="message-part-title-text">
<TextShimmer text={i18n.t("ui.messagePart.title.edit")} active={pending()} />
</span>
<Show when={!pending()}>
<span data-slot="message-part-title-filename">{filename()}</span>
</Show>
</div>
<Show when={!pending() && props.input.filePath?.includes("/")}>
<div data-slot="message-part-path">
<span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
</div>
</Show>
</div>
<div data-slot="message-part-actions">
<Show when={!pending() && props.metadata.filediff}>
<DiffChanges changes={props.metadata.filediff} />
</Show>
</div>
</div>
}
>
<Show when={path()}>
<ToolFileAccordion
path={path()}
actions={
<Show when={!pending() && props.metadata.filediff}>
<DiffChanges changes={props.metadata.filediff!} />
</Show>
}
>
<div data-component="edit-content">
<Dynamic
component={fileComponent}
mode="diff"
virtualize={props.virtualizeDiff}
onRendered={props.onContentRendered}
{...fileCompProps()}
/>
</div>
</ToolFileAccordion>
</Show>
<DiagnosticsDisplay diagnostics={diagnostics()} />
</BasicTool>
</div>
)
},
})
ToolRegistry.register({
name: "write",
render(props) {
const i18n = useI18n()
const fileComponent = useFileComponent()
const diagnostics = createMemo(() => getDiagnostics(props.metadata.diagnostics, props.input.filePath))
const path = createMemo(() => props.input.filePath || "")
const filename = () => getFilename(props.input.filePath ?? "")
const pending = () => props.status === "pending" || props.status === "running"
return (
<div data-component="write-tool">
<BasicTool
{...props}
icon="code-lines"
defer={props.deferContent !== false}
trigger={
<div data-component="write-trigger">
<div data-slot="message-part-title-area">
<div data-slot="message-part-title">
<span data-slot="message-part-title-text">
<TextShimmer text={i18n.t("ui.messagePart.title.write")} active={pending()} />
</span>
<Show when={!pending()}>
<span data-slot="message-part-title-filename">{filename()}</span>
</Show>
</div>
<Show when={!pending() && props.input.filePath?.includes("/")}>
<div data-slot="message-part-path">
<span data-slot="message-part-directory">{getDirectory(props.input.filePath!)}</span>
</div>
</Show>
</div>
<div data-slot="message-part-actions">{/* <DiffChanges diff={diff} /> */}</div>
</div>
}
>
<Show when={props.input.content && path()}>
<ToolFileAccordion path={path()}>
<div data-component="write-content">
<Dynamic
component={fileComponent}
mode="text"
file={{
name: props.input.filePath,
contents: props.input.content,
cacheKey: checksum(props.input.content),
}}
overflow="scroll"
onRendered={props.onContentRendered}
/>
</div>
</ToolFileAccordion>
</Show>
<DiagnosticsDisplay diagnostics={diagnostics()} />
</BasicTool>
</div>
)
},
})
ToolRegistry.register({
name: "patch",
render(props) {
const i18n = useI18n()
const fileComponent = useFileComponent()
const files = createMemo(() => patchFiles(props.metadata.files))
const pending = createMemo(() => props.status === "pending" || props.status === "running")
const single = createMemo(() => {
const list = files()
if (list.length !== 1) return
return list[0]
})
const [expanded, setExpanded] = createSignal<string[]>([])
let seeded = false
createEffect(() => {
const list = files()
if (list.length === 0) return
if (seeded) return
seeded = true
setExpanded(list.filter((f) => f.type !== "delete").map((f) => f.filePath))
})
const subtitle = createMemo(() => {
const count = files().length
if (count === 0) return ""
return `${count} ${i18n.t(count > 1 ? "ui.common.file.other" : "ui.common.file.one")}`
})
return (
<Show
when={single()}
fallback={
<div data-component="apply-patch-tool">
<BasicTool
{...props}
icon="code-lines"
defer={props.deferContent !== false}
trigger={{
title: i18n.t("ui.tool.patch"),
subtitle: subtitle(),
}}
>
<Show when={files().length > 0}>
<Accordion
multiple
data-scope="apply-patch"
style={{ "--sticky-accordion-offset": "calc(32px + var(--tool-content-gap))" }}
value={expanded()}
onChange={(value) => setExpanded(Array.isArray(value) ? value : value ? [value] : [])}
>
<For each={files()}>
{(file) => {
const active = createMemo(() => expanded().includes(file.filePath))
const [visible, setVisible] = createSignal(false)
createEffect(() => {
if (!active()) {
setVisible(false)
return
}
requestAnimationFrame(() => {
if (!active()) return
setVisible(true)
})
})
return (
<Accordion.Item value={file.filePath} data-type={file.type}>
<StickyAccordionHeader>
<Accordion.Trigger>
<div data-slot="apply-patch-trigger-content">
<div data-slot="apply-patch-file-info">
<FileIcon node={{ path: file.relativePath, type: "file" }} />
<div data-slot="apply-patch-file-name-container">
<Show when={file.relativePath.includes("/")}>
<span data-slot="apply-patch-directory">{`\u202A${getDirectory(file.relativePath)}\u202C`}</span>
</Show>
<span data-slot="apply-patch-filename">{getFilename(file.relativePath)}</span>
</div>
</div>
<div data-slot="apply-patch-trigger-actions">
<Switch>
<Match when={file.type === "add"}>
<span data-slot="apply-patch-change" data-type="added">
{i18n.t("ui.patch.action.created")}
</span>
</Match>
<Match when={file.type === "delete"}>
<span data-slot="apply-patch-change" data-type="removed">
{i18n.t("ui.patch.action.deleted")}
</span>
</Match>
<Match when={file.type === "move"}>
<span data-slot="apply-patch-change" data-type="modified">
{i18n.t("ui.patch.action.moved")}
</span>
</Match>
<Match when={true}>
<DiffChanges changes={{ additions: file.additions, deletions: file.deletions }} />
</Match>
</Switch>
<Icon name="chevron-grabber-vertical" size="small" />
</div>
</div>
</Accordion.Trigger>
</StickyAccordionHeader>
<Accordion.Content>
<Show when={props.deferContent === false || visible()}>
<div data-component="apply-patch-file-diff">
<Dynamic
component={fileComponent}
mode="diff"
virtualize={props.virtualizeDiff}
fileDiff={file.view.fileDiff}
hunkSeparators={file.view.fileDiff.isPartial ? "simple" : "line-info-basic"}
onRendered={props.onContentRendered}
/>
</div>
</Show>
</Accordion.Content>
</Accordion.Item>
)
}}
</For>
</Accordion>
</Show>
</BasicTool>
</div>
}
>
<div data-component="apply-patch-tool">
<BasicTool
{...props}
icon="code-lines"
defer={props.deferContent !== false}
trigger={
<div data-component="edit-trigger">
<div data-slot="message-part-title-area">
<div data-slot="message-part-title">
<span data-slot="message-part-title-text">
<TextShimmer text={i18n.t("ui.tool.patch")} active={pending()} />
</span>
<Show when={!pending()}>
<span data-slot="message-part-title-filename">{getFilename(single()!.relativePath)}</span>
</Show>
</div>
<Show when={!pending() && single()!.relativePath.includes("/")}>
<div data-slot="message-part-path">
<span data-slot="message-part-directory">{getDirectory(single()!.relativePath)}</span>
</div>
</Show>
</div>
<div data-slot="message-part-actions">
<Show when={!pending()}>
<DiffChanges changes={{ additions: single()!.additions, deletions: single()!.deletions }} />
</Show>
</div>
</div>
}
>
<ToolFileAccordion
path={single()!.relativePath}
actions={
<Switch>
<Match when={single()!.type === "add"}>
<span data-slot="apply-patch-change" data-type="added">
{i18n.t("ui.patch.action.created")}
</span>
</Match>
<Match when={single()!.type === "delete"}>
<span data-slot="apply-patch-change" data-type="removed">
{i18n.t("ui.patch.action.deleted")}
</span>
</Match>
<Match when={single()!.type === "move"}>
<span data-slot="apply-patch-change" data-type="modified">
{i18n.t("ui.patch.action.moved")}
</span>
</Match>
<Match when={true}>
<DiffChanges changes={{ additions: single()!.additions, deletions: single()!.deletions }} />
</Match>
</Switch>
}
>
<div data-component="apply-patch-file-diff">
<Dynamic
component={fileComponent}
mode="diff"
virtualize={props.virtualizeDiff}
fileDiff={single()!.view.fileDiff}
onRendered={props.onContentRendered}
/>
</div>
</ToolFileAccordion>
</BasicTool>
</div>
</Show>
)
},
})
ToolRegistry.register({
name: "todowrite",
render(props) {
const i18n = useI18n()
const todos = createMemo(() => {
const meta = props.metadata?.todos
if (Array.isArray(meta)) return meta
const input = props.input.todos
if (Array.isArray(input)) return input
return []
})
const subtitle = createMemo(() => {
const list = todos()
if (list.length === 0) return ""
return `${list.filter((t: Todo) => t.status === "completed").length}/${list.length}`
})
return (
<BasicTool
{...props}
defaultOpen
icon="checklist"
trigger={{
title: i18n.t("ui.tool.todos"),
subtitle: subtitle(),
}}
>
<Show when={todos().length}>
<div data-component="todos">
<For each={todos()}>
{(todo: Todo) => (
<Checkbox readOnly checked={todo.status === "completed"}>
<span
data-slot="message-part-todo-content"
data-completed={todo.status === "completed" ? "completed" : undefined}
>
{todo.content}
</span>
</Checkbox>
)}
</For>
</div>
</Show>
</BasicTool>
)
},
})
ToolRegistry.register({
name: "question",
render(props) {
const i18n = useI18n()
const questions = createMemo(() => (props.input.questions ?? []) as QuestionInfo[])
const answers = createMemo(() => (props.metadata.answers ?? []) as QuestionAnswer[])
const completed = createMemo(() => answers().length > 0)
const subtitle = createMemo(() => {
const count = questions().length
if (count === 0) return ""
if (completed()) return i18n.t("ui.question.subtitle.answered", { count })
return `${count} ${i18n.t(count > 1 ? "ui.common.question.other" : "ui.common.question.one")}`
})
return (
<BasicTool
{...props}
defaultOpen={completed()}
icon="bubble-5"
trigger={{
title: i18n.t("ui.tool.questions"),
subtitle: subtitle(),
}}
>
<Show when={completed()}>
<div data-component="question-answers">
<For each={questions()}>
{(q, i) => {
const answer = () => answers()[i()] ?? []
return (
<div data-slot="question-answer-item">
<div data-slot="question-text">{q.question}</div>
<div data-slot="answer-text">{answer().join(", ") || i18n.t("ui.question.answer.none")}</div>
</div>
)
}}
</For>
</div>
</Show>
</BasicTool>
)
},
})
ToolRegistry.register({
name: "skill",
render(props) {
const i18n = useI18n()
const title = createMemo(() => props.input.name || i18n.t("ui.tool.skill"))
const running = createMemo(() => props.status === "pending" || props.status === "running")
const titleContent = () => <TextShimmer text={title()} active={running()} />
const trigger = () => (
<div data-slot="basic-tool-tool-info-structured">
<div data-slot="basic-tool-tool-info-main">
<span data-slot="basic-tool-tool-title" class="capitalize agent-title">
{titleContent()}
</span>
</div>
</div>
)
return <BasicTool icon="brain" status={props.status} trigger={trigger()} hideDetails />
},
})
|