Spaces:
Running
Running
File size: 62,036 Bytes
8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b 5a6c225 8c9362b |
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 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AIDA Agent Test Console</title>
<style>
:root {
--primary: #2563eb;
--bg: #f8fafc;
--chat-bg: #ffffff;
--user-msg: #eff6ff;
--ai-msg: #f1f5f9;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: var(--bg);
color: #1e293b;
height: 100vh;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.container {
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-template-columns: 300px 1fr;
gap: 20px;
height: 100%;
}
.sidebar {
background: white;
padding: 20px;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
gap: 20px;
overflow-y: auto;
}
.main-chat {
background: white;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
overflow: hidden;
}
h2,
h3 {
margin-top: 0;
}
/* Forms */
.form-group {
margin-bottom: 12px;
}
label {
display: block;
font-size: 0.875rem;
font-weight: 500;
margin-bottom: 4px;
}
input,
select,
textarea {
width: 100%;
padding: 8px 12px;
border: 1px solid #e2e8f0;
border-radius: 6px;
font-size: 0.875rem;
box-sizing: border-box;
}
button {
background-color: var(--primary);
color: white;
border: none;
padding: 8px 16px;
border-radius: 6px;
font-weight: 500;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.9;
}
button.secondary {
background-color: #64748b;
}
/* Chat Area */
#chat-history {
flex: 1;
padding: 20px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 16px;
}
.message {
max-width: 80%;
padding: 12px 16px;
border-radius: 12px;
line-height: 1.5;
position: relative;
}
.message.user {
align-self: flex-end;
background-color: var(--user-msg);
color: #1e3a8a;
border-bottom-right-radius: 4px;
}
.message.ai {
align-self: flex-start;
background-color: var(--ai-msg);
color: #334155;
border-bottom-left-radius: 4px;
}
.message .meta {
font-size: 0.75rem;
opacity: 0.7;
margin-bottom: 4px;
}
.message pre {
background: rgba(0, 0, 0, 0.05);
padding: 8px;
border-radius: 4px;
overflow-x: auto;
margin: 8px 0;
}
/* Input Area */
.input-area {
padding: 20px;
border-top: 1px solid #e2e8f0;
display: flex;
gap: 10px;
}
/* Status & Debug */
.status-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 500;
}
.status-badge.success {
background: #dcfce7;
color: #166534;
}
.status-badge.error {
background: #fee2e2;
color: #991b1b;
}
#json-output {
font-family: monospace;
font-size: 0.75rem;
white-space: pre-wrap;
background: #1e293b;
color: #a5b4fc;
padding: 10px;
border-radius: 6px;
max-height: 200px;
overflow-y: auto;
}
.hidden {
display: none;
}
/* Typing Indicator */
.typing-indicator {
padding: 12px 16px;
background-color: var(--ai-msg);
color: #64748b;
border-bottom-left-radius: 4px;
border-radius: 12px;
align-self: flex-start;
font-size: 0.875rem;
display: flex;
align-items: center;
gap: 4px;
width: fit-content;
}
.typing-dot {
width: 6px;
height: 6px;
background-color: #64748b;
border-radius: 50%;
animation: bounce 1.4s infinite ease-in-out both;
}
.typing-dot:nth-child(1) {
animation-delay: -0.32s;
}
.typing-dot:nth-child(2) {
animation-delay: -0.16s;
}
@keyframes bounce {
0%,
80%,
100% {
transform: scale(0);
}
40% {
transform: scale(1);
}
}
/* Listing Card Unit (Message + Card together) */
.listing-card-unit {
margin-top: 10px;
border-radius: 12px;
overflow: hidden;
background: #f8fafc;
border: 1px solid #e2e8f0;
}
.listing-card-unit .card-message {
padding: 12px 16px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
font-size: 14px;
line-height: 1.5;
}
.listing-card-unit .card-message p {
margin: 0;
}
.listing-card-unit .card-message strong {
font-weight: 600;
}
/* Listing Draft Preview */
.listing-draft {
margin-top: 0;
border: none;
border-radius: 0 0 8px 8px;
overflow: hidden;
background: white;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.listing-draft img.hero {
width: 100%;
height: 200px;
object-fit: cover;
transition: opacity 0.3s ease;
}
.listing-draft img.hero.hidden {
display: none;
}
.listing-draft .draft-image-container {
position: relative;
height: 200px;
overflow: hidden;
}
.listing-draft .content {
padding: 16px;
}
.listing-draft h3 {
margin: 0 0 8px 0;
font-size: 1.1rem;
color: #1e293b;
}
.listing-draft p {
margin: 0 0 12px 0;
color: #64748b;
font-size: 0.9rem;
line-height: 1.5;
}
.listing-draft .details {
display: flex;
gap: 12px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.listing-draft .pill {
background: #f1f5f9;
color: #475569;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
font-weight: 500;
}
.listing-draft .amenities {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #f1f5f9;
}
/* Search Results Cards - With Hero Images */
.search-results-container {
margin-top: 12px;
width: 100%;
}
.search-results-scroll {
display: flex;
gap: 16px;
overflow-x: auto;
padding: 8px 4px 16px 4px;
scroll-snap-type: x mandatory;
scrollbar-width: thin;
scrollbar-color: #cbd5e1 transparent;
}
.search-results-scroll::-webkit-scrollbar {
height: 8px;
}
.search-results-scroll::-webkit-scrollbar-track {
background: #f1f5f9;
border-radius: 4px;
}
.search-results-scroll::-webkit-scrollbar-thumb {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 4px;
}
.search-results-single {
display: flex;
justify-content: flex-start;
}
.search-result-card {
min-width: 300px;
max-width: 340px;
border: 1px solid #e2e8f0;
border-radius: 12px;
overflow: hidden;
background: white;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
scroll-snap-align: start;
flex-shrink: 0;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.search-result-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 24px -4px rgba(0, 0, 0, 0.15);
}
.search-card-image-container {
position: relative;
height: 160px;
overflow: hidden;
}
.search-card-hero {
width: 100%;
height: 100%;
object-fit: cover;
transition: opacity 0.3s ease;
}
.search-card-hero.hidden {
display: none;
}
.search-result-card:hover .search-card-hero {
opacity: 0.95;
}
.search-card-type {
position: absolute;
top: 12px;
left: 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 4px 12px;
border-radius: 20px;
font-size: 0.75rem;
font-weight: 600;
text-transform: capitalize;
}
.search-relevance-badge {
position: absolute;
top: 12px;
right: 12px;
background: rgba(255, 255, 255, 0.95);
color: #f59e0b;
padding: 4px 10px;
border-radius: 20px;
font-size: 0.7rem;
font-weight: 600;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.search-card-content {
padding: 16px;
}
.search-card-title {
margin: 0 0 4px 0;
font-size: 1.1rem;
font-weight: 600;
color: #1e293b;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.search-card-location {
margin: 0 0 8px 0;
font-size: 0.85rem;
color: #64748b;
}
.search-card-desc {
margin: 0 0 12px 0;
font-size: 0.875rem;
color: #475569;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.search-card-details {
display: flex;
gap: 16px;
margin-bottom: 10px;
}
.search-detail {
font-size: 0.875rem;
color: #64748b;
}
.search-card-amenities {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 12px;
}
.amenity-pill {
background: #f1f5f9;
color: #475569;
padding: 3px 8px;
border-radius: 4px;
font-size: 0.72rem;
}
.search-card-footer {
display: flex;
align-items: baseline;
padding-top: 12px;
border-top: 1px solid #f1f5f9;
}
.search-card-price {
font-size: 1.25rem;
font-weight: 700;
color: #059669;
}
.search-card-price-type {
font-size: 0.85rem;
color: #94a3b8;
margin-left: 2px;
}
/* ============================================================
MY LISTINGS CARDS - With Edit/Delete Buttons
============================================================ */
.my-listings-container {
margin-top: 12px;
}
.my-listings-scroll {
display: flex;
gap: 16px;
overflow-x: auto;
padding: 8px 0;
scroll-snap-type: x mandatory;
}
.my-listing-card {
min-width: 280px;
max-width: 320px;
background: white;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
overflow: hidden;
scroll-snap-align: start;
border: 1px solid #e2e8f0;
}
.my-listing-card-image {
position: relative;
height: 140px;
overflow: hidden;
}
.my-listing-card-image img {
width: 100%;
height: 100%;
object-fit: cover;
transition: opacity 0.3s ease;
}
.my-listing-card-image img.hidden {
display: none;
}
.my-listing-card-content {
padding: 14px;
}
.my-listing-card-title {
margin: 0 0 6px 0;
font-size: 1rem;
font-weight: 600;
color: #1e293b;
}
.my-listing-card-location {
margin: 0 0 10px 0;
font-size: 0.85rem;
color: #64748b;
}
.my-listing-card-price {
font-size: 1.1rem;
font-weight: 700;
color: #059669;
margin-bottom: 14px;
}
.my-listing-card-actions {
display: flex;
gap: 10px;
padding-top: 12px;
border-top: 1px solid #f1f5f9;
}
.my-listing-btn {
flex: 1;
padding: 8px 12px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 0.85rem;
font-weight: 500;
transition: all 0.2s ease;
}
.my-listing-btn-edit {
background: #f0f9ff;
color: #0369a1;
border: 1px solid #bae6fd;
}
.my-listing-btn-edit:hover {
background: #e0f2fe;
}
.my-listing-btn-delete {
background: #fef2f2;
color: #dc2626;
border: 1px solid #fecaca;
}
.my-listing-btn-delete:hover {
background: #fee2e2;
}
.my-listing-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* ============================================================
IMAGE CAROUSEL - DOT INDICATORS
============================================================ */
.carousel-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 6px;
z-index: 10;
background: rgba(0, 0, 0, 0.3);
padding: 6px 10px;
border-radius: 20px;
backdrop-filter: blur(4px);
}
.carousel-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.5);
cursor: pointer;
transition: all 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.3);
}
.carousel-dot:hover {
background: rgba(255, 255, 255, 0.8);
transform: scale(1.2);
}
.carousel-dot.active {
background: white;
width: 24px;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.8);
}
</style>
</head>
<body>
<div class="container">
<div class="sidebar">
<div>
<h2>Authentication</h2>
<!-- Login Form -->
<div id="login-form">
<div class="form-group">
<label>Identifier (Email/Phone)</label>
<input type="text" id="auth-identifier" placeholder="e.g. user@example.com"
value="test@example.com">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="auth-password" value="Password123!">
</div>
<button onclick="login()">Login</button>
</div>
<!-- Authenticated State -->
<div id="auth-success" class="hidden">
<div class="status-badge success"
style="margin-bottom: 10px; width: 100%; box-sizing: border-box; text-align: center;">Logged In
</div>
<div class="form-group">
<label>User ID</label>
<input type="text" id="user-id" readonly>
</div>
<div class="form-group">
<label>Access Token</label>
<input type="text" id="access-token" readonly style="text-overflow: ellipsis;">
</div>
<button class="secondary" onclick="logout()">Logout</button>
</div>
<!-- Fallback Token Input -->
<div class="form-group" style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px;">
<label>Manual Token Override</label>
<textarea id="manual-token" rows="2" placeholder="Paste JWT here if login fails"></textarea>
</div>
</div>
<div>
<h3>Session Options</h3>
<div class="form-group">
<label>Session ID</label>
<input type="text" id="session-id" placeholder="Auto-generated">
</div>
<div class="form-group">
<label>User Role</label>
<select id="user-role">
<option value="renter">Renter</option>
<option value="landlord">Landlord</option>
<option value="admin">Admin</option>
</select>
</div>
<button class="secondary" onclick="newConversation()">Start New Conversation</button>
</div>
<div style="flex: 1; display: flex; flex-direction: column;">
<h3>Debug Output</h3>
<div id="json-output">Ready...</div>
</div>
</div>
<div class="main-chat">
<div
style="padding: 15px 20px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center;">
<h2 style="margin:0; font-size: 1.25rem;">AIDA Chat</h2>
<div id="connection-status" class="status-badge">Disconnected</div>
</div>
<div id="chat-history">
<!-- Messages will appear here -->
<div class="message ai">
<div class="meta">System</div>
Hello! I am AIDA. Please log in relative to the sidebar to start chatting.
</div>
</div>
<!-- Image Preview Area -->
<div id="image-preview-container"
style="display:none; padding: 10px 20px; background: #f0f9ff; border-top: 1px solid #e0f2fe;">
<div style="position: relative; display: inline-block;">
<img id="image-preview" src=""
style="height: 80px; width: auto; border-radius: 8px; border: 2px solid #3b82f6; object-fit: cover;">
<button onclick="clearImage()"
style="position: absolute; top: -10px; right: -10px; background: #ef4444; color: white; border: 2px solid white; border-radius: 50%; width: 24px; height: 24px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">✕</button>
</div>
<div
style="display: inline-block; vertical-align: top; margin-left: 10px; margin-top: 25px; color: #3b82f6; font-size: 0.9rem; font-weight: 500;">
Image ready to send
</div>
</div>
<div class="input-area">
<input type="file" id="file-input" accept="image/*" style="display: none;"
onchange="handleFileSelect(this)">
<input type="text" id="message-input" placeholder="Type your message..."
onkeypress="if(event.key === 'Enter') sendMessage()">
<button onclick="sendMessage()" style="width: auto;">Send</button>
<button onclick="triggerFileSelect()" class="secondary" style="width: auto; background-color: #f59e0b;"
title="Upload Image">📷</button>
</div>
<!-- Typing Indicator (Hidden by default) -->
<div id="typing-indicator" class="typing-indicator hidden" style="margin: 0 20px 20px 20px;">
<span>Thinking</span>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
</div>
</div>
</div>
<script>
// State
let authToken = '';
let currentSessionId = '';
// Use 127.0.0.1 to avoid localhost DNS/Av issues
const API_BASE = 'http://127.0.0.1:8000';
// CLOUDFLARE WORKER URL (Replace with your actual deployed Worker URL)
const CF_WORKER_URL = "https://lojiz-worker.lojiz-uploadapi.workers.dev"; // UPDATE THIS!
// Image Upload State
let pendingUploadFile = null;
// Init
window.onload = function () {
currentSessionId = generateUUID();
document.getElementById('session-id').value = currentSessionId;
checkHealth();
};
// Global user personalization data
let userName = '';
let userLocation = '';
// Utils
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Image Handling Functions
function triggerFileSelect() {
document.getElementById('file-input').click();
}
function handleFileSelect(input) {
if (input.files && input.files[0]) {
const file = input.files[0];
pendingUploadFile = file;
// Show preview
const reader = new FileReader();
reader.onload = function (e) {
document.getElementById('image-preview').src = e.target.result;
document.getElementById('image-preview-container').style.display = 'block';
// Focus input so user can type message immediately
document.getElementById('message-input').focus();
}
reader.readAsDataURL(file);
}
}
function clearImage() {
pendingUploadFile = null;
document.getElementById('file-input').value = '';
document.getElementById('image-preview-container').style.display = 'none';
}
// Image URL Regex
const IMG_URL_REGEX = /(https?:\/\/.*\.(?:png|jpg|jpeg|gif|webp|svg))/i;
// Markdown to HTML formatter (Browser-compatible, no lookbehind)
function formatMarkdown(text) {
if (!text) return '';
// Escape HTML first to prevent XSS
let formatted = text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
// Convert markdown to HTML
// Bold: **text** (handle first to avoid conflict with single *)
formatted = formatted.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
formatted = formatted.replace(/__([^_]+)__/g, '<strong>$1</strong>');
// Italic: *text* (simple version - works after bold is processed)
formatted = formatted.replace(/\*([^*]+)\*/g, '<em>$1</em>');
formatted = formatted.replace(/_([^_]+)_/g, '<em>$1</em>');
// Headers: # Header
formatted = formatted.replace(/^### (.+)$/gm, '<h4>$1</h4>');
formatted = formatted.replace(/^## (.+)$/gm, '<h3>$1</h3>');
formatted = formatted.replace(/^# (.+)$/gm, '<h2>$1</h2>');
// Line breaks
formatted = formatted.replace(/\n/g, '<br>');
// Horizontal rule: ---
formatted = formatted.replace(/---/g, '<hr style="border:none; border-top:1px solid #e2e8f0; margin:10px 0;">');
return formatted;
}
function updateDebug(data) {
const el = document.getElementById('json-output');
el.textContent = JSON.stringify(data, null, 2);
}
function addMessage(role, text, debugInfo = null, isHtml = false) {
const history = document.getElementById('chat-history');
const div = document.createElement('div');
div.className = `message ${role}`;
let html = `<div class="meta">${role === 'user' ? 'You' : 'AIDA'}</div>`;
if (isHtml) {
html += `<div>${text}</div>`;
} else {
// Check for image URL to render it
const imgMatch = text.match(IMG_URL_REGEX);
if (imgMatch) {
// If text contains an image URL, render the image + the text (if it's not JUST the url)
const url = imgMatch[0];
const textWithoutUrl = text.replace(url, '').trim();
html += `<div style="margin-bottom:8px;">
<img src="${url}" style="max-width:100%; border-radius:8px; display:block;" alt="Uploaded Image" onerror="this.style.display='none'">
</div>`;
if (textWithoutUrl) {
html += `<div>${formatMarkdown(textWithoutUrl)}</div>`;
}
} else {
// Always show the actual text from the response (personalized by LLM)
html += `<div>${formatMarkdown(text)}</div>`;
}
}
// Handle draft_ui: Message + Card appear as ONE UNIT
// When updating, the entire unit moves to bottom with new message
if (debugInfo && debugInfo.draft_ui) {
const isUpdate = debugInfo.replace_last_message === true ||
(debugInfo.metadata && debugInfo.metadata.replace_last_message === true);
// Find and remove the ENTIRE message div that contains the card unit
// This prevents empty leftover divs in chat history
const existingCardUnit = document.querySelector('.listing-card-unit');
if (existingCardUnit) {
// Find the parent message div (the one with class 'message')
const parentMessageDiv = existingCardUnit.closest('.message');
if (parentMessageDiv) {
parentMessageDiv.remove();
console.log('[UI] Entire old message div with card removed');
} else {
existingCardUnit.remove();
console.log('[UI] Old card unit removed (no parent found)');
}
}
// For draft with card: Don't add text separately, it will be part of the card unit
// Remove the text we just added - it will be inside the card unit instead
html = `<div class="meta">${role === 'user' ? 'You' : 'AIDA'}</div>`;
// Create combined Message + Card unit
html += renderDraftWithMessage(debugInfo.draft_ui, text);
console.log('[UI] Card unit created with message:', isUpdate ? 'UPDATE' : 'INITIAL');
}
// Handle search results: Render as cards
if (debugInfo && debugInfo.action === 'search_results' && debugInfo.search_results && debugInfo.search_results.length > 0) {
html += renderSearchResults(debugInfo.search_results);
console.log('[UI] Search results cards rendered:', debugInfo.search_results.length);
}
// Handle my listings: Render as cards with Edit/Delete buttons
if (debugInfo && debugInfo.action === 'my_listings' && debugInfo.my_listings && debugInfo.my_listings.length > 0) {
html += renderMyListings(debugInfo.my_listings);
console.log('[UI] My listings cards rendered:', debugInfo.my_listings.length);
}
div.innerHTML = html;
history.appendChild(div);
history.scrollTop = history.scrollHeight;
}
// NEW: Render card WITH message as ONE unit
function renderDraftWithMessage(draft, message) {
const images = (draft.images && draft.images.length > 0) ? draft.images : ['https://via.placeholder.com/400x200?text=No+Image'];
const cardId = 'draft-' + Date.now();
let amenitiesHtml = '';
if (draft.amenities && draft.amenities.length > 0) {
amenitiesHtml = '<div class="amenities">' + draft.amenities.map(a => `<span class="pill">${a}</span>`).join('') + '</div>';
}
// Build image carousel HTML
const imagesHtml = images.map((img, idx) =>
`<img src="${img}" class="hero ${idx === 0 ? '' : 'hidden'}" alt="Listing Image ${idx + 1}" data-index="${idx}">`
).join('');
// Build dots HTML (only if more than 1 image)
let dotsHtml = '';
if (images.length > 1) {
const dots = images.map((_, idx) =>
`<span class="carousel-dot ${idx === 0 ? 'active' : ''}" onclick="switchImage('${cardId}', ${idx})" data-index="${idx}"></span>`
).join('');
dotsHtml = `<div class="carousel-dots">${dots}</div>`;
}
return `
<div class="listing-card-unit">
<div class="card-message">${formatMarkdown(message)}</div>
<div class="listing-draft" id="${cardId}">
<div class="draft-image-container">
${imagesHtml}
${dotsHtml}
</div>
<div class="content">
<h3>${draft.title}</h3>
<p>${draft.description}</p>
<div class="details">
<span class="pill">📍 ${draft.details.location}</span>
<span class="pill">💰 ${draft.details.price}</span>
<span class="pill">🛏️ ${draft.details.bedrooms} Bedroom</span>
<span class="pill">🚿 ${draft.details.bathrooms} Bathroom</span>
<span class="pill">🏷️ ${draft.details.listing_type}</span>
</div>
${amenitiesHtml}
</div>
</div>
</div>`;
}
// Update an existing draft card in-place
function updateDraftCard(cardElement, draft) {
const heroImage = (draft.images && draft.images.length > 0) ? draft.images[0] : 'https://via.placeholder.com/400x200?text=No+Image';
// Update hero image
const heroImg = cardElement.querySelector('img.hero');
if (heroImg) heroImg.src = heroImage;
// Update title
const titleEl = cardElement.querySelector('h3');
if (titleEl) titleEl.textContent = draft.title;
// Update description
const descEl = cardElement.querySelector('p');
if (descEl) descEl.textContent = draft.description;
// Update details pills
const detailsDiv = cardElement.querySelector('.details');
if (detailsDiv && draft.details) {
detailsDiv.innerHTML = `
<span class="pill">📍 ${draft.details.location}</span>
<span class="pill">💰 ${draft.details.price}</span>
<span class="pill">🛏️ ${draft.details.bedrooms} Bedroom</span>
<span class="pill">🚿 ${draft.details.bathrooms} Bathroom</span>
<span class="pill">🏷️ ${draft.details.listing_type}</span>
${draft.status === 'published' ? '<span class="pill" style="background:#dcfce7; color:#166534; border:1px solid #86efac;">✅ Published</span>' : ''}
`;
}
// Update amenities
const amenitiesDiv = cardElement.querySelector('.amenities');
if (amenitiesDiv && draft.amenities) {
amenitiesDiv.innerHTML = draft.amenities.map(a => `<span class="pill">${a}</span>`).join('');
}
// Add a subtle highlight animation to show the update
cardElement.style.transition = 'box-shadow 0.3s ease';
cardElement.style.boxShadow = '0 0 0 3px rgba(37, 99, 235, 0.5)';
setTimeout(() => {
cardElement.style.boxShadow = '0 4px 6px -1px rgba(0, 0, 0, 0.1)';
}, 500);
}
function renderDraft(draft) {
const heroImage = (draft.images && draft.images.length > 0) ? draft.images[0] : 'https://via.placeholder.com/400x200?text=No+Image';
let amenitiesHtml = '';
if (draft.amenities && draft.amenities.length > 0) {
amenitiesHtml = '<div class="amenities">' + draft.amenities.map(a => `<span class="pill">${a}</span>`).join('') + '</div>';
}
return `
<div class="listing-draft" id="listing-draft-preview">
<img src="${heroImage}" class="hero" alt="Listing Image">
<div class="content">
<h3>${draft.title}</h3>
<p>${draft.description}</p>
<div class="details">
<span class="pill">📍 ${draft.details.location}</span>
<span class="pill">💰 ${draft.details.price}</span>
<span class="pill">🛏️ ${draft.details.bedrooms} Bedroom</span>
<span class="pill">🚿 ${draft.details.bathrooms} Bathroom</span>
<span class="pill">🏷️ ${draft.details.listing_type}</span>
</div>
${amenitiesHtml}
</div>
</div>`;
}
// Render search results as cards (with hero images like draft UI)
function renderSearchResults(results) {
if (!results || results.length === 0) return '';
const cards = results.map((listing, cardIdx) => {
const title = listing.title || 'Untitled Property';
const description = listing.description || 'A beautiful property waiting to be explored.';
const location = listing.location || 'Unknown';
const price = listing.price ? listing.price.toLocaleString() : 'N/A';
const currency = listing.currency || 'XOF';
const priceType = listing.price_type || 'monthly';
const bedrooms = listing.bedrooms || '?';
const bathrooms = listing.bathrooms || '?';
const listingType = listing.listing_type || 'rent';
const relevance = listing._relevance_score;
const amenities = listing.amenities || [];
// Get all images or use placeholder
const images = (listing.images && listing.images.length > 0)
? listing.images
: ['https://images.unsplash.com/photo-1560518883-ce09059eeffa?w=400&h=200&fit=crop'];
const cardId = 'search-card-' + Date.now() + '-' + cardIdx;
// Truncate description to 2 lines
const shortDesc = description.length > 100
? description.substring(0, 100) + '...'
: description;
// Build amenities HTML (max 4)
let amenitiesHtml = '';
if (amenities.length > 0) {
const displayAmenities = amenities.slice(0, 4);
amenitiesHtml = '<div class="search-card-amenities">' +
displayAmenities.map(a => `<span class="amenity-pill">${a}</span>`).join('') +
(amenities.length > 4 ? `<span class="amenity-pill">+${amenities.length - 4}</span>` : '') +
'</div>';
}
// Relevance badge for hybrid search results
let relevanceBadge = '';
if (relevance) {
const percent = Math.round(relevance * 100);
relevanceBadge = `<span class="search-relevance-badge">⭐ ${percent}% match</span>`;
}
// Build image carousel HTML
const imagesHtml = images.map((img, idx) =>
`<img src="${img}" class="search-card-hero ${idx === 0 ? '' : 'hidden'}" alt="${title}" data-index="${idx}" onerror="this.src='https://via.placeholder.com/400x180?text=Property'">`
).join('');
// Build dots HTML (only if more than 1 image)
let dotsHtml = '';
if (images.length > 1) {
const dots = images.map((_, idx) =>
`<span class="carousel-dot ${idx === 0 ? 'active' : ''}" onclick="switchImage('${cardId}', ${idx})" data-index="${idx}"></span>`
).join('');
dotsHtml = `<div class="carousel-dots">${dots}</div>`;
}
return `
<div class="search-result-card" id="${cardId}">
<div class="search-card-image-container">
${imagesHtml}
<span class="search-card-type">${listingType}</span>
${relevanceBadge}
${dotsHtml}
</div>
<div class="search-card-content">
<h3 class="search-card-title">${title}</h3>
<p class="search-card-location">📍 ${location}</p>
<p class="search-card-desc">${shortDesc}</p>
<div class="search-card-details">
<span class="search-detail">🛏️ ${bedrooms} bed</span>
<span class="search-detail">🚿 ${bathrooms} bath</span>
</div>
${amenitiesHtml}
<div class="search-card-footer">
<span class="search-card-price">${currency} ${price}</span>
<span class="search-card-price-type">/${priceType}</span>
</div>
</div>
</div>`;
}).join('');
// Use scroll container for multiple, simple flex for single
const containerClass = results.length === 1 ? 'search-results-single' : 'search-results-scroll';
return `
<div class="search-results-container">
<div class="${containerClass}">
${cards}
</div>
</div>`;
}
// Render My Listings Cards with Edit/Delete buttons
function renderMyListings(listings) {
if (!listings || listings.length === 0) {
return '';
}
const cards = listings.map((listing, cardIdx) => {
const id = listing._id || listing.id || '';
const title = listing.title || 'Untitled';
const location = listing.location || 'Unknown Location';
const price = (listing.price || 0).toLocaleString();
const currency = listing.currency || 'XOF';
const priceType = listing.price_type || 'monthly';
const images = (listing.images && listing.images.length > 0)
? listing.images
: ['https://via.placeholder.com/400x140?text=Property'];
const cardId = 'my-listing-' + Date.now() + '-' + cardIdx;
// Build image carousel HTML
const imagesHtml = images.map((img, idx) =>
`<img src="${img}" alt="${title}" class="${idx === 0 ? '' : 'hidden'}" data-index="${idx}" onerror="this.src='https://via.placeholder.com/400x140?text=Property'">`
).join('');
// Build dots HTML (only if more than 1 image)
let dotsHtml = '';
if (images.length > 1) {
const dots = images.map((_, idx) =>
`<span class="carousel-dot ${idx === 0 ? 'active' : ''}" onclick="switchImage('${cardId}', ${idx})" data-index="${idx}"></span>`
).join('');
dotsHtml = `<div class="carousel-dots">${dots}</div>`;
}
return `
<div class="my-listing-card" id="${cardId}" data-listing-id="${id}">
<div class="my-listing-card-image">
${imagesHtml}
${dotsHtml}
</div>
<div class="my-listing-card-content">
<h4 class="my-listing-card-title">${title}</h4>
<p class="my-listing-card-location">📍 ${location}</p>
<p class="my-listing-card-price">${currency} ${price}/${priceType}</p>
<div class="my-listing-card-actions">
<button class="my-listing-btn my-listing-btn-edit" onclick="editListing('${id}')">✏️ Edit</button>
<button class="my-listing-btn my-listing-btn-delete" onclick="deleteListing('${id}', this)">🗑️ Delete</button>
</div>
</div>
</div>`;
}).join('');
return `
<div class="my-listings-container">
<div class="my-listings-scroll">
${cards}
</div>
</div>`;
}
// Delete listing function
async function deleteListing(listingId, buttonElement) {
if (!confirm('Are you sure you want to delete this listing?')) {
return;
}
buttonElement.disabled = true;
buttonElement.innerText = 'Deleting...';
try {
const res = await fetch(`${API_BASE}/listings/${listingId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
});
if (res.ok) {
// Remove the card from UI
const card = buttonElement.closest('.my-listing-card');
if (card) {
card.style.opacity = '0.5';
card.style.transform = 'scale(0.95)';
setTimeout(() => card.remove(), 300);
}
addMessage('assistant', '✅ Listing deleted successfully!');
} else {
const error = await res.json();
addMessage('assistant', `❌ Failed to delete: ${error.detail || 'Unknown error'}`);
buttonElement.disabled = false;
buttonElement.innerText = '🗑️ Delete';
}
} catch (error) {
addMessage('assistant', `❌ Error: ${error.message}`);
buttonElement.disabled = false;
buttonElement.innerText = '🗑️ Delete';
}
}
// Edit listing function - triggers edit flow via chat
async function editListing(listingId) {
console.log('editListing called with ID:', listingId);
console.log('authToken present:', !!authToken, 'length:', authToken?.length);
if (!authToken) {
addMessage('assistant', '🔒 Please log in to edit listings.');
return;
}
// Send the edit command to the chat API
const editMessage = `edit listing ${listingId}`;
console.log('Sending edit request with token:', authToken.substring(0, 20) + '...');
// Get user details from DOM inputs (set during login)
const currentUserId = document.getElementById('user-id').value;
const currentUserRole = document.getElementById('user-role').value;
// Use the same session-id source as sendMessage for consistency
const sessionId = document.getElementById('session-id').value || currentSessionId;
// Show user message
addMessage('user', `✏️ Edit listing`);
try {
const res = await fetch(`${API_BASE}/ai/ask`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({
message: editMessage,
session_id: sessionId,
user_id: currentUserId,
user_role: currentUserRole,
user_name: userName,
user_location: userLocation
})
});
const data = await res.json();
// Sync session_id from response to keep edit context
if (data.session_id) {
currentSessionId = data.session_id;
document.getElementById('session-id').value = data.session_id;
console.log('Session ID synced from response:', data.session_id);
}
if (data.text) {
addMessage('assistant', data.text, data);
} else {
addMessage('assistant', '❌ Failed to load listing for editing.');
}
} catch (error) {
addMessage('assistant', `❌ Error: ${error.message}`);
}
}
// Auth Functions
async function login() {
// Visual feedback that the function started
const loginBtn = document.querySelector('button[onclick="login()"]');
const originalText = loginBtn.innerText;
loginBtn.innerText = "Logging in...";
loginBtn.disabled = true;
const identifier = document.getElementById('auth-identifier').value;
const password = document.getElementById('auth-password').value;
updateDebug({ status: "Attempting login...", identifier: identifier });
try {
const res = await fetch(`${API_BASE}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identifier, password })
});
const data = await res.json();
updateDebug(data);
if (res.ok && data.success && data.data && data.data.token) {
const token = data.data.token;
const user = data.data.user;
const userId = user.id || user._id || 'unknown';
const userRole = user.role || 'renter';
// Extract personalization data
const name = user.firstName || user.name || user.fullName || '';
const location = user.location || user.city || user.address?.city || '';
setAuth(token, userId, userRole, name, location);
// alert("Login Successful!");
} else {
alert('Login failed: ' + (data.message || 'Unknown error'));
}
} catch (e) {
console.error("Login Error:", e);
updateDebug({ error: e.message, hint: "Is the backend running on port 8000?" });
alert('Login error: ' + e.message + "\n\nIs the backend server running?");
} finally {
loginBtn.innerText = originalText;
loginBtn.disabled = false;
}
}
function setAuth(token, userId, userRole, name = '', location = '') {
authToken = token;
userName = name;
userLocation = location;
document.getElementById('access-token').value = token;
document.getElementById('user-id').value = userId;
// Auto-fill the user role dropdown
if (userRole) {
document.getElementById('user-role').value = userRole;
}
// Log personalization data
console.log('[Auth] User personalization:', { name: userName, location: userLocation });
document.getElementById('login-form').classList.add('hidden');
document.getElementById('auth-success').classList.remove('hidden');
}
function logout() {
authToken = '';
document.getElementById('login-form').classList.remove('hidden');
document.getElementById('auth-success').classList.add('hidden');
document.getElementById('access-token').value = '';
document.getElementById('user-id').value = '';
}
// API Functions
async function checkHealth() {
try {
const res = await fetch(`${API_BASE}/health`);
const data = await res.json();
const statusEl = document.getElementById('connection-status');
if (res.ok) {
statusEl.textContent = 'Connected';
statusEl.classList.add('success');
} else {
statusEl.textContent = 'Error';
statusEl.classList.add('error');
}
} catch (e) {
document.getElementById('connection-status').textContent = 'Offline';
}
}
async function sendMessage() {
const input = document.getElementById('message-input');
const text = input.value.trim();
const hasImage = pendingUploadFile !== null;
if (!text && !hasImage) return;
// Use manual token if provided
const manualToken = document.getElementById('manual-token').value.trim();
const effectiveToken = manualToken || authToken;
input.value = '';
// Show user message immediately
if (hasImage) {
// Show text + "Uploading image..." status or similar
let displayMsg = text;
const previewSrc = document.getElementById('image-preview').src;
displayMsg += `<br><img src="${previewSrc}" style="max-height:150px; border-radius:8px; margin-top:5px; opacity: 0.7;">`;
displayMsg += `<div style="font-size:0.8em; color:#666;">Uploading image to Cloudflare...</div>`;
addMessage('user', displayMsg, null, true);
} else {
addMessage('user', text);
}
// Get session info
const sessionId = document.getElementById('session-id').value;
const userId = document.getElementById('user-id').value || undefined;
const userRole = document.getElementById('user-role').value;
const userNameVal = userName || undefined;
const userLocVal = userLocation || undefined;
// Show typing indicator
const typingEl = document.getElementById('typing-indicator');
// ... (rest of typing indicator logic handled in UI usually, but we'll adapt)
// ===================================
// PATH A: Image Upload Flow
// ===================================
if (hasImage) {
try {
// Prepare FormData for Cloudflare Worker
const formData = new FormData();
formData.append('file', pendingUploadFile);
formData.append('message', text); // Attach user command
formData.append('user_id', userId || 'anon');
formData.append('session_id', sessionId);
formData.append('operation', 'add'); // Default to add, can be improved later
// Clear pending image
const fileToUpload = pendingUploadFile; // Keep ref
clearImage();
// Upload to Cloudflare Worker
const cfRes = await fetch(CF_WORKER_URL, {
method: 'POST',
body: formData // No headers needed for FormData
});
const cfData = await cfRes.json();
// Whether success or error, send result to AIDA to handle
// The Worker returns {success: true/false, ...} which matches AIDA's expectation
const aidaRes = await fetch(`${API_BASE}/ai/image-upload-result`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(effectiveToken ? { 'Authorization': `Bearer ${effectiveToken}` } : {})
},
body: JSON.stringify(cfData)
});
const aidaData = await aidaRes.json();
handleAidaResponse(aidaData);
} catch (e) {
console.error("Upload Error:", e);
addMessage('assistant', `❌ Upload Error: ${e.message}. Is the Cloudflare Worker URL correct?`);
}
return;
}
// ===================================
// PATH B: Standard Text Message Flow
// ===================================
const payload = {
message: text,
session_id: sessionId,
user_id: userId,
user_role: userRole,
user_name: userNameVal,
user_location: userLocVal
};
const headers = {
'Content-Type': 'application/json'
};
if (effectiveToken) {
headers['Authorization'] = `Bearer ${effectiveToken}`;
}
updateDebug({ status: 'Sending...', payload });
const chatHistory = document.getElementById('chat-history');
// Move typing indicator to inside chat history temporarily or just toggle it
// Better to append a temporary element
const tempTypingId = 'temp-typing-' + Date.now();
const typingHtml = `
<div id="${tempTypingId}" class="message ai" style="display:flex; align-items:center; gap:8px;">
<div class="meta">AIDA</div>
<div style="display:flex; gap:4px; align-items:center;">
<span>Thinking</span>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
</div>
</div>`;
// Append temporary typing indicator
const tempDiv = document.createElement('div');
tempDiv.innerHTML = typingHtml;
chatHistory.appendChild(tempDiv.firstElementChild);
chatHistory.scrollTop = chatHistory.scrollHeight;
try {
const res = await fetch(`${API_BASE}/ai/ask`, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
});
const data = await res.json();
updateDebug(data);
// Remove typing indicator
const typingNode = document.getElementById(tempTypingId);
if (typingNode) typingNode.remove();
if (data.metadata && data.metadata.replace_last_message) {
console.log('[UI] Replace last message signal received');
if (data.draft_ui) {
const existingCardUnit = document.querySelector('.listing-card-unit');
if (existingCardUnit) {
const parentMessageDiv = existingCardUnit.closest('.message');
if (parentMessageDiv) {
parentMessageDiv.remove();
} else {
existingCardUnit.remove();
}
}
}
}
// Use the shared handler
handleAidaResponse(data);
} catch (e) {
// Remove typing indicator on error
const typingNode = document.getElementById(tempTypingId);
if (typingNode) typingNode.remove();
updateDebug({ error: e.message });
addMessage('ai', 'Error: ' + e.message);
}
}
// Shared Response Handler
function handleAidaResponse(data) {
// Remove any temp typing indicators
const indicators = document.querySelectorAll('[id^="temp-typing-"]');
indicators.forEach(el => el.remove());
// Sync session_id from response to keep context (especially for edit mode)
if (data.session_id) {
currentSessionId = data.session_id;
document.getElementById('session-id').value = data.session_id;
}
if (data.metadata && data.metadata.replace_last_message) {
// Logic already handled in sendMessage mostly for removing, but let's ensure addMessage works
// Just use addMessage
const text = data.text || data.message || '';
addMessage('ai', text, data);
} else {
// Standard append
if (data.text) {
addMessage('ai', data.text, data);
} else if (data.message) {
addMessage('ai', data.message, data);
} else {
addMessage('ai', JSON.stringify(data), data);
}
}
}
function newConversation() {
currentSessionId = generateUUID();
document.getElementById('session-id').value = currentSessionId;
// Clear chat history
const history = document.getElementById('chat-history');
history.innerHTML = `
<div class="message ai">
<div class="meta">System</div>
New conversation started! Session ID: ${currentSessionId}
</div>`;
updateDebug({ status: 'New conversation started', session_id: currentSessionId });
}
// Image Carousel Navigation
function switchImage(cardId, targetIndex) {
const card = document.getElementById(cardId);
if (!card) return;
// Find all images in this card
const images = card.querySelectorAll('img[data-index]');
const dots = card.querySelectorAll('.carousel-dot');
// Hide all images and show the target one
images.forEach((img, idx) => {
if (idx === targetIndex) {
img.classList.remove('hidden');
} else {
img.classList.add('hidden');
}
});
// Update dot states
dots.forEach((dot, idx) => {
if (idx === targetIndex) {
dot.classList.add('active');
} else {
dot.classList.remove('active');
}
});
}
</script>
</body>
</html> |