All files / src/views LiveSharePanel.ts

45.4% Statements 722/1590
29.91% Branches 35/117
67.56% Functions 25/37
45.4% Lines 722/1590

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 15911x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x                                                             14x 14x 14x 14x 14x 14x 14x 14x     14x 14x 14x 14x 14x 14x 14x 14x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x               2x 14x 14x 14x 14x 14x 14x 1x     1x 1x     1x 1x 1x 1x                         1x 1x     1x 1x 1x     1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x     1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                     1x 14x 14x 14x 14x 14x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 14x 14x 14x 14x 14x 1x 1x                                                             1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x                                                                     1x     1x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x                                       1x     1x 14x 14x 14x 14x 14x 14x 14x 14x                                                         14x 14x 14x 14x 14x                                                                                                                                                                                                                                                     14x 14x 14x 14x 14x 14x                                                         14x 14x 14x 14x 14x 14x 2x 2x 2x 2x 2x                                           2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                     2x 2x 2x 2x 2x   2x 2x 14x 14x 14x 14x 14x 14x 1x 1x 1x       1x 1x 1x 1x 1x 1x                                     1x 14x 14x 14x 14x 14x 14x 2x 2x 2x           2x 2x 2x 2x 2x     2x 14x 14x 14x 14x 14x 4x 2x 2x 2x 4x 14x 14x 14x 14x 14x 14x 14x 1x           1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x                     1x 1x 1x 14x 14x 14x 14x 14x 14x                                     14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x                                                                                                                               1x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x                     1x                                                                                                   1x 14x 14x 14x 14x 14x 14x 14x 8x 4x 4x 4x 4x 8x 3x 3x 14x 14x 14x 14x 14x 14x                                                                                                                       14x 14x 14x 14x 14x 14x                                                                                     14x 14x 14x 14x 14x 14x                                                                 14x 14x 14x 14x 14x 14x 14x                             14x 14x 14x 14x 14x 14x 14x                 14x 14x 14x 14x 14x 2x 2x 2x 2x 1x 2x 2x 2x 2x 2x   2x 2x     2x 14x 14x 14x 14x 14x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 14x 14x 14x 14x 14x 14x                                         14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x                                     1x                           1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x                                                 14x  
import { SessionSyncService } from '../services/session-sync-service';
import { GitService } from '../services/git-service';
import * as vscode from 'vscode';
// Live Share is optional; only require if present to avoid activation failure
let vsls: typeof import('vsls') | undefined;
try {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    vsls = require('vsls');
} catch {
    vsls = undefined;
}
import { getCachedDisplayName, getOrInitDisplayName } from '../services/profile-service';
import { insertLiveShareActivity, insertLiveShareSessionEnd } from '../services/team-activity-service';
import { getCurrentUser } from '../auth/supabaseClient';
import { getCurrentUserId } from '../services/auth-service';
 
/**
 * Provides Live Share functionality for the Collab Agent extension.
 * Manages Live Share sessions, participant monitoring, and session communication.
 */
 
export class LiveShareManager {
    //Live Share API instance (optional)
    private _liveShareApi?: any | null = null;
 
    //Current session invite link for persistence and display
    private _sessionLink: string | undefined;
 
    //Flag to track if initial session check has been completed
    private _initialSessionCheckDone = false;
 
    private _sessionSyncService: SessionSyncService;
    private _gitService?: GitService;
 
    //Git diff captured at session start (baseline for comparison)
    private _sessionStartDiff?: string;
 
    //Key for persisting manual invite links in global state
    private readonly _persistedLinkKey = 'collabAgent.manualInviteLink';
 
    //Key for current team in global state (matches AgentPanel)
    private readonly _teamStateKey = 'collabAgent.currentTeam';
 
    //Interval timer for monitoring participant changes
    private participantMonitoringInterval?: NodeJS.Timeout;
 
    //Timestamp when the current session started
    private sessionStartTime?: Date;
 
    //Current session ID for tracking
    private currentSessionId?: string;
 
    //Session baseline snapshot ID (for "View Initial Snapshot" button)
    private sessionBaselineSnapshotId?: string;
 
    //Interval timer for pushing duration updates to the UI
    private _durationUpdateInterval?: NodeJS.Timeout;
 
    //Reference to the webview view for sending messages
    private _view?: vscode.WebviewView;
 
    // Back-compat for older tests: cache of announced participant names
    private _participantNameMap: Map<string, string> = new Map();
 
    
 
    /**
     * Creates a new LiveShareManager instance.
     * 
     * @param _context - The extension context for state management
     */
    constructor(private readonly _context: vscode.ExtensionContext) {
        this._sessionSyncService = new SessionSyncService();
 
        // Initialize git service
        try {
            this._gitService = new GitService();
        } catch (error) {
            console.log('[LiveShareManager] Git service not available:', error);
        }
 
        // Set up callback for real time participant updates from Supabase
        this._sessionSyncService.setOnParticipantChange((participants) => {
            console.log('[LiveShareManager] Received participant update from Supabase:', participants);
            
            // Convert to UI format
            const participantList = participants.map(p => ({
                name: p.github_username || 'Unknown',
                email: '',
                role: p.peer_number === 1 ? 'Host' : 'Guest'
            }));

            // Update UI
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateParticipants',
                    participants: participantList,
                    count: participantList.length
                });

                // Also update session status with correct count
                const session = this._liveShareApi?.session;
                if (session) {
                    this._view.webview.postMessage({
                        command: 'updateSessionStatus',
                        status: session.role === (vsls?.Role?.Host) ? 'hosting' : 'joined',
                        link: this._sessionLink || '',
                        participants: participantList.length,
                        role: session.role,
                        duration: this.getSessionDuration()
                    });
                }
            }
        });
    }
 
    /**
     * Sets the webview reference for UI updates
     * @param view - The webview view instance
     */
    public setView(view: vscode.WebviewView) {
        this._view = view;
    }
 
    /**
     * Initializes the Live Share API and sets up event listeners.
     * Retries on failure with exponential backoff.
     * 
     * @returns Promise that resolves to true if initialization succeeds, false otherwise
     */
    public async initializeLiveShare(): Promise<boolean> {
        await new Promise(resolve => setTimeout(resolve, 1000));
        if (!vsls || typeof vsls.getApi !== 'function') {
            console.log('Live Share module not available. Skipping initialization.');
            return false;
        }
        this._liveShareApi = await vsls.getApi();
        if (this._liveShareApi) {
            console.log('Live Share API initialized successfully.');
 
            this.setupLiveShareEventListeners();
 
            // Clean up any orphaned pinned events from previous sessions
            await this.cleanupOrphanedPinnedEvents();
 
            return true;
        } else {
            console.log('Live Share extension not available.');
            setTimeout(() => {
                console.log('Retrying Live Share initialization...');
                this.initializeLiveShare();
            }, 3000);
            return false;
        }
    }
 
    /**
     * Sets up event listeners for Live Share session and peer changes.
     * Monitors session state, participant changes, and activities.
     */
    private setupLiveShareEventListeners() {
        if (!this._liveShareApi) {
            return;
        }
        try {
            this._liveShareApi.onDidChangeSession((sessionChangeEvent: any) => {
                console.log('Live Share session changed:', sessionChangeEvent);
                this.handleSessionChange(sessionChangeEvent);
            });
 
            if (typeof (this._liveShareApi as any).onDidChangePeers === 'function') {
                (this._liveShareApi as any).onDidChangePeers(async (peerChangeEvent: any) => {
                    console.log('Live Share peers changed:', peerChangeEvent);
                    
                    // Load participants from Supabase instead of using Live Share API
                    const session = this._liveShareApi?.session;
                    if (session?.id) {
                        console.log('[onDidChangePeers] Loading participants from Supabase for session:', session.id);
                        
                        // Wait a moment for the guest to announce their presence in Supabase
                        await new Promise(resolve => setTimeout(resolve, 1000));
                        
                        await this.loadParticipantsFromSupabase(session.id);
                    }
                });
            } else {
                console.warn('Live Share API does not expose onDidChangePeers in this environment. Falling back to polling only.');
            }
 
            this.monitorSessionState();
        } catch (error) {
            console.error('Error setting up Live Share event listeners:', error);
        }
    }
 
    /**
     * Handles Live Share session state changes (start, join, end).
     * Updates UI, manages participant monitoring, and handles session timing.
     *
     * @param sessionChangeEvent - The session change event from Live Share API
     */
    private async handleSessionChange(sessionChangeEvent: any) {
        const session = sessionChangeEvent.session;
        console.log('[DEBUG] handleSessionChange START - session exists:', !!session, 'session.id:', session?.id);
        console.log('handleSessionChange called with session:', session);
        console.log('handleSessionChange called with session:', session);
        console.log('Session change event details:', {
            changeType: sessionChangeEvent.changeType,
            session: session ? {
                id: session.id,
                role: session.role,
                peerNumber: session.peerNumber,
                user: session.user
            } : null
        });
        
        if (session) {
            console.log('Session active:', {
                id: session.id,
                role: session.role,
                uri: session.uri?.toString(),
                peerNumber: session.peerNumber,
                user: session.user
            });
 
            if (!this.sessionStartTime || ['joined','started','start','starting'].includes(String(sessionChangeEvent.changeType).toLowerCase())) {
                this.sessionStartTime = new Date();
                console.log('Session start time set to (local clock):', this.sessionStartTime, 'changeType:', sessionChangeEvent.changeType);
            }
 
            if (session.id) {
                console.log('[DEBUG] About to call announcePresenceViaSupabase');
 
                // Store current session ID for later use
                this.currentSessionId = session.id;
 
                // IMPORTANT: Pause automatic snapshot tracking and save pending local changes
                const isHost = session.role === (vsls?.Role?.Host);
                const baselineSnapshotId = await this.pauseAutomaticSnapshotting(isHost, session.id);
 
                // Store the baseline snapshot ID for later use (linking to session event)
                if (baselineSnapshotId) {
                    this.sessionBaselineSnapshotId = baselineSnapshotId;
                    console.log('[LiveShareManager] Stored baseline snapshot ID:', this.sessionBaselineSnapshotId);
                }
 
                // DISABLED: Git stash was causing file deletion issues
                // We now use SnapshotManager's createSessionBaseline() instead
                // which captures the workspace state without modifying any files
                /*
                if (this._gitService) {
                    this._gitService.createSessionSnapshot().then(stashName => {
                        if (stashName) {
                            console.log('[LiveShareManager] Created git stash session snapshot');
                        }
                    }).catch(err => {
                        console.error('[LiveShareManager] Failed to create git stash session snapshot:', err);
                    });
                }
                */
 
                // Announce presence via Supabase
                this.announcePresenceViaSupabase(session);
 
                console.log('[DEBUG] About to call loadParticipantsFromSupabase');
                // Load all participants from Supabase
                this.loadParticipantsFromSupabase(session.id);
 
                // Track Live Share event in team activity feed
                const eventType = isHost ? 'live_share_started' : 'live_share_joined';
                // For hosts, pass the baseline snapshot ID to link the initial workspace snapshot
                const snapshotIdToPass = (isHost && baselineSnapshotId) ? baselineSnapshotId : undefined;
                this.insertLiveShareEvent(eventType, session.id, snapshotIdToPass);
            }
 
 
            const isHost = session.role === (vsls?.Role?.Host);
            let status = 'joined';
            
            if (isHost) {
                status = 'hosting';
            } else if (session.role === (vsls?.Role?.Guest)) {
                status = 'joined';
            }
            
            const sessionLink = session.uri?.toString() || this._sessionLink || '';
            if (sessionLink) {
                this._sessionLink = sessionLink;
            }
            let participantCount = (this._liveShareApi?.peers?.length || 0) + 1;
            // For guests, never show less than 2 because a host must exist
            if (!isHost) {
                const sessionPeerNum = typeof (session as any).peerNumber === 'number' ? (session as any).peerNumber : undefined;
                const candidate = sessionPeerNum && sessionPeerNum >= 2 ? sessionPeerNum : participantCount;
                participantCount = Math.max(2, candidate);
            }
            
            console.log('Sending updateSessionStatus message:', {
                status: status,
                link: sessionLink,
                participants: participantCount,
                role: session.role,
                duration: this.getSessionDuration(),
                isHost: isHost
            });
            
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: status,
                    link: sessionLink,
                    participants: participantCount,
                    role: session.role,
                    duration: this.getSessionDuration()
                });
            }
 
            // Start monitoring participants if we're in a session
            this.startParticipantMonitoring();
        } else {
            console.log('Session ended - clearing session start time');

            // Track session end in activity feed with participant details
            // IMPORTANT: Await this before cleanup so backend can query participants
            await this.insertLiveShareSessionEndEvent();

            // IMPORTANT: Resume automatic snapshot tracking after session ends
            await this.resumeAutomaticSnapshotting();

            this._sessionSyncService.leaveSession();
            this.sessionStartTime = undefined;
            this.currentSessionId = undefined;
            this.sessionBaselineSnapshotId = undefined;
            this.stopDurationUpdater();
            this.clearManualInviteLink();
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'ended',
                    link: '',
                    participants: 0
                });

                this._view.webview.postMessage({
                    command: 'updateParticipants',
                    participants: [],
                    count: 0
                });

                setTimeout(() => {
                    if (this._view) {
                        this._view.webview.postMessage({
                            command: 'updateSessionStatus',
                            status: 'none',
                            link: '',
                            participants: 0
                        });
                    }
                }, 2000);
            }
            this.stopParticipantMonitoring();
        }
    }
 
    /**
 * Announce your presence in the session via Supabase
 */
    private async announcePresenceViaSupabase(session: any) {
        console.log('[DEBUG] announcePresenceViaSupabase called with session.id:', session.id);
        try {
            const displayName = getCachedDisplayName();
            if (!displayName) {
                console.log('[SessionSync] No display name cached, getting from Supabase...');
                const result = await getOrInitDisplayName(true);
                if (result.displayName) {
                    await this._sessionSyncService.joinSession(
                        session.id,
                        result.displayName,
                        session.peerNumber || 0
                    );
                }
            } else {
                await this._sessionSyncService.joinSession(
                    session.id,
                    displayName,
                    session.peerNumber || 0
                );
            }
        } catch (err) {
            console.error('[SessionSync] Failed to announce presence:', err);
        }
    }
 
    /**
     * Load all participants from Supabase and update UI
     */
    private async loadParticipantsFromSupabase(sessionId: string) {
        try {
            const participants = await this._sessionSyncService.getParticipants(sessionId);
            console.log('[SessionSync] Loaded participants from Supabase:', participants);

            // Convert to UI format
            const participantList = participants.map(p => ({
                name: p.github_username || 'Unknown',
                email: '',
                role: p.peer_number === 1 ? 'Host' : 'Guest'
            }));

            // Update UI
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateParticipants',
                    participants: participantList,
                    count: participantList.length
                });

                // Also update session status with correct count
                const session = this._liveShareApi?.session;
                if (session) {
                    this._view.webview.postMessage({
                        command: 'updateSessionStatus',
                        status: session.role === (vsls?.Role?.Host) ? 'hosting' : 'joined',
                        link: this._sessionLink || '',
                        participants: participantList.length,
                        role: session.role,
                        duration: this.getSessionDuration()
                    });
                }
            }
        } catch (err) {
            console.error('[SessionSync] Failed to load participants:', err);
        }
    }
 
    /**
     * Inserts a Live Share event into the team activity feed
     * @param eventType - Type of event: 'live_share_started' | 'live_share_joined'
     * @param sessionId - Optional session ID for reference
     * @param snapshotId - Optional snapshot ID for the initial workspace snapshot (for started events)
     */
    private async insertLiveShareEvent(
        eventType: 'live_share_started' | 'live_share_joined',
        sessionId?: string,
        snapshotId?: string
    ) {
        try {
            // Get current team ID
            const teamId = this._context.globalState.get<string>(this._teamStateKey);
            if (!teamId) {
                console.log('[LiveShareManager] No active team, skipping activity insert');
                return;
            }

            // Get current user
            const user = await getCurrentUser();
            if (!user?.id) {
                console.log('[LiveShareManager] No authenticated user, skipping activity insert');
                return;
            }

            // Get display name
            let displayName = getCachedDisplayName();
            if (!displayName) {
                const result = await getOrInitDisplayName(true);
                displayName = result.displayName || 'Unknown User';
            }

            // Insert activity
            const result = await insertLiveShareActivity(
                teamId,
                user.id,
                eventType,
                displayName,
                sessionId,
                snapshotId,  // Pass snapshot ID for linking to initial snapshot
                this._sessionLink  // Pass session invite link
            );

            if (result.success) {
                console.log('[LiveShareManager] Live Share activity inserted successfully');

                // Notify webview to refresh activity feed
                if (this._view) {
                    this._view.webview.postMessage({
                        command: 'refreshActivityFeed'
                    });
                }
            } else {
                console.error('[LiveShareManager] Failed to insert activity:', result.error);
            }
        } catch (err) {
            console.error('[LiveShareManager] Exception inserting Live Share event:', err);
        }
    }
 
    /**
     * Cleans up orphaned pinned Live Share Started events
     * This happens when VS Code closes while a session is active
     * Unpins any "Live Share Started" events if there's no active session
     */
    private async cleanupOrphanedPinnedEvents() {
        try {
            // Only clean up if there's no active session
            if (this._liveShareApi?.session) {
                console.log('[LiveShareManager] Active session detected, skipping orphaned event cleanup');
                return;
            }
 
            // Get current team ID
            const teamId = this._context.globalState.get<string>(this._teamStateKey);
            if (!teamId) {
                console.log('[LiveShareManager] No active team, skipping orphaned event cleanup');
                return;
            }

            console.log('[LiveShareManager] Checking for orphaned pinned events...');

            // Call backend to unpin all Live Share Started events for this team
            const { cleanupOrphanedPinnedEvents } = await import('../services/team-activity-service.js');
            const result = await cleanupOrphanedPinnedEvents(teamId);

            if (result.success) {
                console.log('[LiveShareManager] Orphaned pinned events cleaned up successfully');

                // Refresh activity feed to show updated pin status
                if (this._view) {
                    this._view.webview.postMessage({
                        command: 'refreshActivityFeed'
                    });
                }
            } else {
                console.error('[LiveShareManager] Error cleaning up orphaned events:', result.error);
            }
        } catch (error) {
            console.error('[LiveShareManager] Exception cleaning up orphaned events:', error);
        }
    }
 
    /**
     * Updates an existing Live Share Started event with the session invite link
     * This is called when the user captures the invite link from clipboard
     * @param sessionId - The session ID to update
     * @param sessionLink - The session invite link
     */
    private async updateLiveShareEventWithLink(sessionId: string, sessionLink: string) {
        try {
            // Get current team ID
            const teamId = this._context.globalState.get<string>(this._teamStateKey);
            if (!teamId) {
                console.log('[LiveShareManager] No active team, skipping activity update');
                return;
            }

            // Call backend to update the event
            const { updateLiveShareActivityLink } = await import('../services/team-activity-service.js');
            const result = await updateLiveShareActivityLink(teamId, sessionId, sessionLink);

            if (result.success) {
                console.log('[LiveShareManager] Live Share activity updated with session link');

                // Notify webview to refresh activity feed so the Join button appears
                if (this._view) {
                    this._view.webview.postMessage({
                        command: 'refreshActivityFeed'
                    });
                }
            } else {
                console.error('[LiveShareManager] Error updating Live Share activity with link:', result.error);
            }
        } catch (error) {
            console.error('[LiveShareManager] Exception updating Live Share activity with link:', error);
        }
    }
 
    /**
     * Inserts a Live Share session end event with participant details into the team activity feed
     */
    private async insertLiveShareSessionEndEvent() {
        try {
            // Only insert if we have session tracking data
            if (!this.sessionStartTime || !this.currentSessionId) {
                console.log('[LiveShareManager] No session data, skipping session end event');
                return;
            }

            // Get current team ID
            const teamId = this._context.globalState.get<string>(this._teamStateKey);
            if (!teamId) {
                console.log('[LiveShareManager] No active team, skipping activity insert');
                return;
            }

            // Get current user
            const user = await getCurrentUser();
            if (!user?.id) {
                console.log('[LiveShareManager] No authenticated user, skipping activity insert');
                return;
            }

            // Get display name
            let displayName = getCachedDisplayName();
            if (!displayName) {
                const result = await getOrInitDisplayName(true);
                displayName = result.displayName || 'Unknown User';
            }

            // Calculate duration in minutes
            const now = new Date();
            const durationMs = now.getTime() - this.sessionStartTime.getTime();
            const durationMinutes = Math.floor(durationMs / 60000);

            // Check if current user is host
            const session = this._liveShareApi?.session;
            const isHost = session && session.role === (vsls?.Role?.Host);

            // Get git diff of changes made DURING the session
            let sessionChanges = '(no changes captured)';

            // IMPORTANT: Use SnapshotManager diff for hosts (workspace-based, no git commands)
            // Guests don't save session snapshots (only hosts do)
            if (isHost) {
                console.log('[LiveShareManager] Host session ending - using SnapshotManager diff');
                try {
                    const { snapshotManager } = await import('../extension.js');
                    sessionChanges = await snapshotManager.captureSessionChanges(user.id, teamId);

                    if (!sessionChanges || sessionChanges.trim().length === 0) {
                        console.log('[LiveShareManager] No changes detected during session');
                        sessionChanges = '(no changes during session)';
                    }

                    console.log('[LiveShareManager] Captured session changes from SnapshotManager, length:', sessionChanges.length);
                } catch (err) {
                    console.error('[LiveShareManager] Failed to get session changes from SnapshotManager:', err);
                    sessionChanges = `Error capturing changes: ${err}`;
                }
            } else {
                console.log('[LiveShareManager] Guest session ending - guests do not save session snapshots');
                sessionChanges = '(guest - no session snapshot)';
            }

            // Create the live_share_ended event with baseline snapshot ID (for "View Initial Snapshot" button)
            console.log('[LiveShareManager] Creating live_share_ended event...');
            console.log('[LiveShareManager] Baseline snapshot ID:', this.sessionBaselineSnapshotId);
            const result = await insertLiveShareSessionEnd(
                teamId,
                user.id,
                displayName,
                this.currentSessionId,
                durationMinutes,
                this.sessionBaselineSnapshotId  // Link to session baseline snapshot
            );
            console.log('[LiveShareManager] Event creation result:', result);

            // Then create the snapshot which will trigger edge function
            // Edge function will find the live_share_ended event and update it with AI summary
            console.log('[LiveShareManager] Checking if should create snapshot - gitService:', !!this._gitService, 'result.success:', result.success);

            // Always create snapshot if we have an event (even if git service failed)
            if (result.success) {
                console.log('[LiveShareManager] Creating snapshot with changes...');
                try {
                    const snapshotResult = await this.insertLiveShareSummary(
                        teamId,
                        user.id,
                        displayName,
                        this.currentSessionId,
                        sessionChanges
                    );

                    console.log('[LiveShareManager] Snapshot result:', snapshotResult);
                    if (snapshotResult.snapshotId) {
                        console.log('[LiveShareManager] Created snapshot with ID:', snapshotResult.snapshotId);
                        console.log('[LiveShareManager] Edge function will update the live_share_ended event with AI summary');
                    } else {
                        console.log('[LiveShareManager] No snapshot ID returned');
                    }
                } catch (err) {
                    console.error('[LiveShareManager] Failed to create snapshot:', err);
                }
            } else {
                console.log('[LiveShareManager] Skipping snapshot creation - event creation failed');
            }

            if (result.success) {
                console.log('[LiveShareManager] Live Share session end activity inserted successfully');

                // Notify webview to refresh activity feed
                if (this._view) {
                    this._view.webview.postMessage({
                        command: 'refreshActivityFeed'
                    });
                }
            } else {
                console.error('[LiveShareManager] Failed to insert session end activity:', result.error);
            }
        } catch (err) {
            console.error('[LiveShareManager] Exception inserting Live Share session end event:', err);
        }
    }
 
    /**
     * Inserts a Live Share summary with git diff into file_snapshots
     * @returns Object with snapshot ID
     */
    private async insertLiveShareSummary(
        teamId: string,
        userId: string,
        displayName: string,
        sessionId: string,
        changes: string
    ): Promise<{ snapshotId?: string }> {
        try {
            const { insertLiveShareSummary } = require('../services/team-activity-service');
            const result = await insertLiveShareSummary(
                teamId,
                userId,
                displayName,
                sessionId,
                changes
            );

            if (result.success) {
                console.log('[LiveShareManager] Live Share summary inserted successfully');
                return { snapshotId: result.snapshotId };
            } else {
                console.error('[LiveShareManager] Failed to insert summary:', result.error);
                return {};
            }
        } catch (err) {
            console.error('[LiveShareManager] Exception inserting Live Share summary:', err);
            return {};
        }
    }
 
    /**
     * Monitors the current Live Share session state and updates the UI accordingly.
     * Handles initial session detection and sets up periodic monitoring.
     */
    private monitorSessionState() {
        console.log('monitorSessionState: Checking session state...');
        console.log('monitorSessionState: _liveShareApi exists:', !!this._liveShareApi);
        console.log('monitorSessionState: _liveShareApi.session exists:', !!this._liveShareApi?.session);
        
        if (this._liveShareApi?.session) {
            const session = this._liveShareApi.session;
            console.log('monitorSessionState: Session details:', {
                id: session.id,
                role: session.role,
                isValid: !!(session.id && (session.role === (vsls?.Role?.Host) || session.role === (vsls?.Role?.Guest)))
            });
            
            if (session.id && (session.role === (vsls?.Role?.Host) || session.role === (vsls?.Role?.Guest))) {
                console.log('Found existing active session:', session);
                this.handleSessionChange({ session: session, changeType: 'existing' });
            } else {
                console.log('Found invalid or inactive session, clearing UI state');
                if (this._view) {
                    this._view.webview.postMessage({
                        command: 'updateSessionStatus',
                        status: 'none',
                        link: '',
                        participants: 0
                    });
                }
            }
        } else {
            console.log('No existing session found on initial check; show loading');
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'loading',
                    link: '',
                    participants: 0
                });
            }
            setTimeout(() => {
                if (!this._liveShareApi?.session) {
                    if (this._view) {
                        this._view.webview.postMessage({
                            command: 'updateSessionStatus',
                            status: 'none',
                            link: '',
                            participants: 0
                        });
                    }
                }
            }, 1500);
        }
        this._initialSessionCheckDone = true;
        
        setInterval(() => {
            this.periodicSessionCheck();
        }, 5000);
    }
    
    /**
     * Performs periodic checks of session state to catch changes
     * that might not trigger event listeners.
     */
    private periodicSessionCheck() {
        if (!this._liveShareApi) {
            return;
        }
        
        const hasSession = !!this._liveShareApi.session;
        const hasValidSession = hasSession && 
            this._liveShareApi.session.id && 
            (this._liveShareApi.session.role === (vsls?.Role?.Host) || this._liveShareApi.session.role === (vsls?.Role?.Guest));
        
        console.log('periodicSessionCheck:', { hasSession, hasValidSession, sessionId: this._liveShareApi.session?.id });
        
        if (!hasValidSession && this._view) {
            console.log('periodicSessionCheck: No valid session, ensuring UI shows none');
            this._view.webview.postMessage({
                command: 'updateSessionStatus',
                status: 'none',
                link: '',
                participants: 0
            });

            this._view.webview.postMessage({
                command: 'updateParticipants',
                participants: [],
                count: 0
            });

            this.sessionStartTime = undefined;
            this.currentSessionId = undefined;
            this.stopParticipantMonitoring();
        }
    }
 
    /**
     * Starts monitoring participants in the Live Share session.
     * Updates participant information every 2 seconds for responsive UI updates.
     */
    private startParticipantMonitoring() {
        this.stopParticipantMonitoring();
        
        this.participantMonitoringInterval = setInterval(async () => {
            // Use Supabase data instead of Live Share API
            const session = this._liveShareApi?.session;
            if (session?.id) {
                await this.loadParticipantsFromSupabase(session.id);
            }
        }, 2000);
 
        // Initial load
        const session = this._liveShareApi?.session;
        if (session?.id) {
            this.loadParticipantsFromSupabase(session.id);
        }
    }
 
    /**
     * Stops the participant monitoring interval timer.
     */
    private stopParticipantMonitoring() {
        if (this.participantMonitoringInterval) {
            clearInterval(this.participantMonitoringInterval);
            this.participantMonitoringInterval = undefined;
        }
    }
 
    /**
     * Sets a manual invite link as fallback when Live Share API doesn't expose the link.
     * 
     * @param link - The invite link to set, or undefined to clear
     */
    public async setManualInviteLink(link: string | undefined) {
        if (!link || !link.trim()) {
            if (this._view) {
                this._view.webview.postMessage({ command: 'manualLinkInvalid', reason: 'empty' });
            }
            return;
        }
        const trimmed = link.trim();
        this._sessionLink = trimmed;
        this._context.globalState.update(this._persistedLinkKey, this._sessionLink);
 
        // Update the existing Live Share Started event in the activity feed with the session link
        if (this.currentSessionId) {
            await this.updateLiveShareEventWithLink(this.currentSessionId, trimmed);
        }
 
        if (this._view) {
            this._view.webview.postMessage({
                command: 'manualLinkUpdated',
                link: this._sessionLink
            });
            const status = this._liveShareApi?.session?.role === (vsls?.Role?.Host) ? 'hosting' : (this._liveShareApi?.session ? 'joined' : 'none');
            this._view.webview.postMessage({
                command: 'updateSessionStatus',
                status,
                link: this._sessionLink,
                participants: (this._liveShareApi?.peers?.length || 0) + (this._liveShareApi?.session ? 1 : 0),
                role: this._liveShareApi?.session?.role,
                duration: this.getSessionDuration()
            });
        }
    }
 
    /**
     * Clears the manually set invite link and updates the UI.
     */
    public clearManualInviteLink() {
        this._sessionLink = undefined;
        this._context.globalState.update(this._persistedLinkKey, undefined);
        if (this._view) {
            this._view.webview.postMessage({ command: 'manualLinkCleared' });
            const status = this._liveShareApi?.session?.role === (vsls?.Role?.Host) ? 'hosting' : (this._liveShareApi?.session ? 'joined' : 'none');
            this._view.webview.postMessage({
                command: 'updateSessionStatus',
                status,
                link: '',
                participants: (this._liveShareApi?.peers?.length || 0) + (this._liveShareApi?.session ? 1 : 0),
                role: this._liveShareApi?.session?.role,
                duration: this.getSessionDuration()
            });
        }
    }
 
    /**
     * Sends any stored invite link from global state to the webview.
     * Used for restoring session state after extension reload.
     */
    public sendStoredLinkToWebview() {
        const stored = this._context.globalState.get<string | undefined>(this._persistedLinkKey);
        if (stored) {
            this._sessionLink = stored;
            if (this._view) {
                this._view.webview.postMessage({ command: 'storedLink', link: stored });
                if (this._liveShareApi?.session) {
                    const s = this._liveShareApi.session;
                    this._view?.webview.postMessage({
                        command: 'updateSessionStatus',
                        status: s.role === (vsls?.Role?.Host) ? 'hosting' : 'joined',
                        link: stored,
                        participants: (this._liveShareApi.peers?.length || 0) + 1,
                        role: s.role,
                        duration: this.getSessionDuration()
                    });
                }
            }
        }
    }
 
    /**
     * Attempts to paste an invite link from the system clipboard.
     * Shows appropriate error messages for invalid or empty clipboard content.
     */
    public async pasteInviteLinkFromClipboard() {
        try {
            const clip = await vscode.env.clipboard.readText();
            if (clip && clip.trim()) {
                const trimmed = clip.trim();
                this.setManualInviteLink(trimmed);
                if (this._view) {
                    this._view.webview.postMessage({ command: 'manualLinkPasted', link: trimmed });
                }
            } else {
                if (this._view) {
                    this._view.webview.postMessage({ command: 'manualLinkPasteInvalid' });
                }
                vscode.window.showWarningMessage('Clipboard is empty or does not contain text.');
            }
        } catch (err) {
            console.warn('Failed reading clipboard for invite link:', err);
            vscode.window.showErrorMessage('Could not read clipboard for invite link.');
        }
    } 
 
    /**
     * Ends the current Live Share session (host only).
     * Updates UI state and notifies participants.
     */
    public async endLiveShareSession() {
        try {
            console.log('Attempting to end Live Share session...');
            
            if (!this._liveShareApi) {
                console.log('Live Share API not available');
                vscode.window.showWarningMessage('Live Share API not available.');
                return;
            }

            if (!this._liveShareApi.session) {
                console.log('No active session found');
                vscode.window.showWarningMessage('No active Live Share session to end.');
                return;
            }

            console.log('Current session role:', this._liveShareApi.session.role);
            console.log('Host role constant:', vsls?.Role?.Host);
            
            if (this._liveShareApi.session.role !== (vsls?.Role?.Host)) {
                vscode.window.showWarningMessage('Only the session host can end the session.');
                return;
            }

            console.log('Calling end() on Live Share API...');

            // IMPORTANT: Generate the session summary BEFORE cleanup
            // so the backend can query participants from session_participants table
            await this.insertLiveShareSessionEndEvent();

            // Cleanup all participants from Supabase
            const sessionId = this._liveShareApi.session.id;
            if (sessionId) {
                await this._sessionSyncService.cleanupSession(sessionId);
            }

            // End the session
            await this._liveShareApi.end();
            console.log('Live Share end() completed');

            // Resume automatic snapshot tracking after session ends
            await this.resumeAutomaticSnapshotting();

            this.sessionStartTime = undefined;
            this.currentSessionId = undefined;
            this.sessionBaselineSnapshotId = undefined;
            this.stopParticipantMonitoring();
            this.stopDurationUpdater();
            this.clearManualInviteLink();
            
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'ended',
                    link: '',
                    participants: 0
                });

                this._view.webview.postMessage({
                    command: 'updateParticipants',
                    participants: [],
                    count: 0
                });
                
                // Reset button state
                this._view.webview.postMessage({
                    command: 'resetButtonState',
                    buttonType: 'end'
                });
            }
            
            vscode.window.showInformationMessage('Live Share session ended successfully.');
        } catch (error) {
            console.error('Error ending Live Share session:', error);
            vscode.window.showErrorMessage('Failed to end Live Share session: ' + error);
            
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'resetButtonState',
                    buttonType: 'end'
                });
            }
        }
    }
 
    /**
     * Leaves the current Live Share session (guest only).
     * Clears local session state and updates UI.
     */
    public async leaveLiveShareSession() {
        try {
            console.log('Attempting to leave Live Share session...');
            
            if (!this._liveShareApi) {
                console.log('Live Share API not available');
                vscode.window.showWarningMessage('Live Share API not available.');
                return;
            }

            if (!this._liveShareApi.session) {
                console.log('No active session found');
                vscode.window.showWarningMessage('No active Live Share session to leave.');
                return;
            }

            const session = this._liveShareApi.session;
            console.log('Current session role:', session.role);
            
            if (session.role === (vsls?.Role?.Host)) {
                vscode.window.showWarningMessage('Hosts cannot leave their own session. Use "End Session" instead.');
                return;
            }

            console.log('Calling end() on Live Share API to leave session...');

            // Remove participant record from Supabase before leaving
            await this._sessionSyncService.leaveSession();

            await this._liveShareApi.end();
            console.log('Live Share leave completed');

            // Resume automatic snapshot tracking after leaving session
            await this.resumeAutomaticSnapshotting();

            this.sessionStartTime = undefined;
            this.currentSessionId = undefined;
            this.sessionBaselineSnapshotId = undefined;
            this.stopParticipantMonitoring();
            this.stopDurationUpdater();
            this.clearManualInviteLink();
            
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'none',
                    link: '',
                    participants: 0
                });
                
                // Reset button state
                this._view.webview.postMessage({
                    command: 'resetButtonState',
                    buttonType: 'leave'
                });
            }
            
            vscode.window.showInformationMessage('Successfully left the Live Share session.');
        } catch (error) {
            console.error('Error leaving Live Share session:', error);
            vscode.window.showErrorMessage('Failed to leave Live Share session: ' + error);
            
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'resetButtonState',
                    buttonType: 'leave'
                });
            }
        }
    }
 
    /**
     * Calculates and formats the current session duration.
     * 
     * @returns Formatted duration string (e.g., "1h 30m" or "45m")
     */
    private getSessionDuration(): string {
        if (!this.sessionStartTime) return '';
        const now = new Date();
        const diffMs = now.getTime() - this.sessionStartTime.getTime();
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMins / 60);
        if (diffHours > 0) return `${diffHours}h ${diffMins % 60}m`;
        return `${diffMins}m`;
    }
 
    /**
     * Starts a new Live Share session as host.
     * Validates workspace state, creates session, and sets up monitoring.
     */
    public async startLiveShareSession() {
        if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
            vscode.window.showErrorMessage('Please open a project folder before starting a Live Share session.');
            return;
        }

        if (!this._liveShareApi) {
            vscode.window.showErrorMessage('Live Share API not available. Please install Live Share extension.');
            return;
        }

         const confirm = await vscode.window.showWarningMessage(
        'Warning: Closing this folder or opening another project folder will end the Live Share session for all participants.',
        { modal: true },
        'OK'
        );

        if (confirm !== 'OK') {
            // User cancelled, don't start session
            return;
        }

        try {
            vscode.window.showInformationMessage('Starting Live Share session...');

            const session = await this._liveShareApi.share();

            if (session && session.toString()) {
                const inviteLink = session.toString();
                this._sessionLink = inviteLink;
                vscode.window.showInformationMessage(`Live Share session started! Invite link ${inviteLink}`);
                if (!this.sessionStartTime) {
                    this.sessionStartTime = new Date();
                    console.log('Host sessionStartTime initialized at startLiveShareSession():', this.sessionStartTime);
                }
                // Start duration updates
                this.startDurationUpdater();

                vscode.window.showWarningMessage(
                    'Warning: Closing this folder or opening another project folder will end the Live Share session for all participants.',
                    { modal: true }
                );

                if (this._view) {
                    this._view.webview.postMessage({
                        command: 'updateSessionStatus',
                        status: 'hosting',
                        link: inviteLink
                    });
                }

            } else {
                console.warn('Live Share session creation failed or was cancelled - this may be due to Live Share extension issues');
                // Don't show intrusive error popup, just log the issue
            }
        } catch (error) {
            console.error('Error starting Live Share session:', error);
            vscode.window.showErrorMessage('Error starting Live Share session: ' + error);
        }
    }
 
    /**
     * Joins an existing Live Share session as guest.
     * Prompts for invite link and establishes connection.
     */
    public async joinLiveShareSession() {
        if (!this._liveShareApi) {
            vscode.window.showErrorMessage('Live Share API not available. Please install Live Share extension.');
            return;
        }

        try {
            const inviteLink = await vscode.window.showInputBox({
                prompt: 'Enter Live Share invite link',
                placeHolder: 'https://prod.liveshare.vsengsaas.visualstudio.com/join?...',
                validateInput: (value) => {
                    if (!value || value.trim().length === 0) {
                        return 'Please enter a valid invite link';
                    }
                    return null;
                }
            });

            if (!inviteLink) {
                return;
            }

            vscode.window.showInformationMessage('Joining Live Share session...');

            const inviteUri = vscode.Uri.parse(inviteLink.trim());
            await this._liveShareApi.join(inviteUri);
            this._sessionLink = inviteLink;
            vscode.window.showInformationMessage('Successfully joined Live Share session!');
            this.startDurationUpdater();

            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'joined',
                    link: inviteLink
                });
            }

        } catch (error) {
            console.error('Error joining Live Share session:', error);
            vscode.window.showErrorMessage('Error joining Live Share session: ' + error); 
        }
    }
 
    /**
     * Joins a Live Share session using a provided invite link
     * @param inviteLink - The Live Share session invite link
     */
    public async joinLiveShareSessionWithLink(inviteLink: string) {
        if (!this._liveShareApi) {
            vscode.window.showErrorMessage('Live Share API not available. Please install Live Share extension.');
            return;
        }

        if (!inviteLink || inviteLink.trim().length === 0) {
            vscode.window.showErrorMessage('Invalid invite link provided');
            return;
        }

        try {
            vscode.window.showInformationMessage('Joining Live Share session...');

            const inviteUri = vscode.Uri.parse(inviteLink.trim());
            await this._liveShareApi.join(inviteUri);
            this._sessionLink = inviteLink;
            vscode.window.showInformationMessage('Successfully joined Live Share session!');
            this.startDurationUpdater();

            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'joined',
                    link: inviteLink
                });
            }

        } catch (error) {
            console.error('Error joining Live Share session:', error);
            vscode.window.showErrorMessage('Error joining Live Share session: ' + error);
        }
    }
 
    /**
     * Sends a team message in the current Live Share session.
     *
     * @param message - The message text to send
     */
    public sendTeamMessage(message: string) {
        if (!this._liveShareApi?.session) {
            vscode.window.showWarningMessage('Start or join a Live Share session to use team chat.');
            return;
        }
        vscode.window.showInformationMessage(`Team message: ${message}`);
        if (this._view) {
            this._view.webview.postMessage({
                command: 'addMessage',
                message: message,
                sender: 'You',
                timestamp: new Date().toLocaleTimeString()
            });
        }
    }
 
    /**
     * Updates team activity information (host only).
     * 
     * @param activity - The activity data to update
     */
    public updateTeamActivity(activity: any) {
        if (this._liveShareApi?.session?.role !== (vsls?.Role?.Host)) return;
        if (this._view) {
            this._view.webview.postMessage({
                command: 'updateActivity',
                activity: activity
            });
        }
    }
 
    /**
     * Back-compat: Resolve a peer's display name using announced map or peer fields.
     */
    private resolvePeerDisplayName(peer: any): string {
        try {
            const key = (peer?.user?.emailAddress || peer?.user?.id || peer?.id || '').toLowerCase();
            const announced = key ? this._participantNameMap.get(key) : undefined;
            if (announced) return announced;
            return (
                peer?.user?.displayName ||
                peer?.displayName ||
                (peer as any)?.user?.loginName ||
                (peer as any)?.user?.userName ||
                peer?.user?.emailAddress ||
                'Unknown'
            );
        } catch {
            return 'Unknown';
        }
    }
 
    /**
     * Back-compat: Update participant info (host only) and notify shared service if present.
     */
    private async updateParticipantInfo() {
        if (!this._liveShareApi?.session) {
            return;
        }
        const session = this._liveShareApi.session;
        const isHost = session.role === (vsls?.Role?.Host);
        if (!isHost) return;
 
        try {
            const peers = (this._liveShareApi.peers || []).filter(Boolean);
            const participantCount = peers.length + 1;
 
            const participants: any[] = [];
            let selfName = getCachedDisplayName();
            if (!selfName) {
                try {
                    const r = await getOrInitDisplayName(true);
                    selfName = r.displayName;
                } catch {
                    selfName = undefined;
                }
            }
            participants.push({
                name: selfName || session.user?.displayName || 'You',
                email: session.user?.emailAddress || '',
                role: 'Host'
            });
            for (const peer of peers) {
                const resolvedName = this.resolvePeerDisplayName(peer);
                participants.push({
                    name: resolvedName,
                    email: peer?.user?.emailAddress || '',
                    role: 'Guest'
                });
            }
 
            // Notify any legacy shared service listeners
            const shared: any = (this as any)._sharedService;
            if (shared && typeof shared.notify === 'function') {
                shared.notify('participantUpdate', {
                    count: participantCount,
                    participants,
                    duration: this.getSessionDuration()
                });
            }
 
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'updateParticipants',
                    participants,
                    count: participantCount
                });
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'hosting',
                    link: this._sessionLink || '',
                    participants: participantCount,
                    role: session.role,
                    duration: this.getSessionDuration()
                });
            }
        } catch {
            // swallow in tests
        }
    }
 
    /**
     * Starts the duration updater interval (host only).
     * Periodically updates the session duration in the UI.
     */
    private startDurationUpdater() {
        this.stopDurationUpdater();
    if (!this._liveShareApi || !this._liveShareApi.session || this._liveShareApi.session.role !== (vsls?.Role?.Host)) return;
        this._durationUpdateInterval = setInterval(() => {
            if (!this._liveShareApi || !this._liveShareApi.session || this._liveShareApi.session.role !== (vsls?.Role?.Host)) {
                this.stopDurationUpdater();
                return;
            }
            if (this.sessionStartTime && this._view) {
                const session = this._liveShareApi.session;
                this._view.webview.postMessage({
                    command: 'updateSessionStatus',
                    status: 'hosting',
                    link: this._sessionLink || '',
                    participants: (this._liveShareApi.peers?.length || 0) + 1,
                    role: session.role,
                    duration: this.getSessionDuration()
                });
            }
        }, 30000);
    }
 
    /**
     * Stops the duration updater interval timer.
     */
    private stopDurationUpdater() {
        if (this._durationUpdateInterval) {
            clearInterval(this._durationUpdateInterval);
            this._durationUpdateInterval = undefined;
        }
    }
 
    /**
     * Disposes of the Live Share manager and cleans up resources.
     * Stops monitoring intervals and clears references.
     */
    public dispose() {
        this.stopParticipantMonitoring();
        this.stopDurationUpdater();
        
        this._view = undefined;
        this._liveShareApi = undefined;
    }
 
    /**
     * Compatibility shim for older tests expecting a requestHostSessionStartTime method.
     * In the current architecture we sync via Supabase, but for tests (and
     * backwards compatibility) we still attempt to fetch the host start time
     * via Live Share shared service if available.
     */
    private async requestHostSessionStartTime() {
        try {
            // Only guests should request the host start time
            if (!this._liveShareApi || !this._liveShareApi.session || this._liveShareApi.session.role !== (vsls?.Role?.Guest)) {
                return;
            }
            const anyApi: any = this._liveShareApi as any;
            if (typeof anyApi.getSharedService === 'function') {
                const proxy = await anyApi.getSharedService('collabAgentSessionInfo');
                if (proxy && proxy.isServiceAvailable && typeof proxy.request === 'function') {
                    const info = await proxy.request('getSessionInfo');
                    if (info && info.startTime) {
                        const hostStart = new Date(info.startTime);
                        if (!isNaN(hostStart.getTime())) {
                            this.sessionStartTime = hostStart;
                        }
                    }
                }
            }
        } catch {
            // Non-fatal for tests; ignore
        }
    }
 
    /**
     * Pauses automatic snapshot tracking when a Live Share session starts.
     * Saves any pending local changes before pausing.
     * If host, also creates a session baseline snapshot.
     * Returns the baseline snapshot ID if host, null otherwise.
     *
     * CRITICAL WORKFLOW FOR HOSTS:
     * 1. Create session baseline FIRST (captures current state with pending changes)
     * 2. Save pending changes as automatic snapshot (for AI summary in activity feed)
     * 3. Pause automatic tracking
     */
    private async pauseAutomaticSnapshotting(isHost: boolean, sessionId?: string): Promise<string | null> {
        try {
            // Import the snapshot manager
            const { snapshotManager } = await import('../extension.js');

            // Get current user and team
            const userId = await getCurrentUserId();
            if (!userId) {
                console.log('[LiveShareManager] No user ID, skipping snapshot pause');
                return null;
            }

            const teamId = this._context.globalState.get<string>(this._teamStateKey);
            if (!teamId) {
                console.log('[LiveShareManager] No team ID, skipping snapshot pause');
                return null;
            }

            let baselineSnapshotId: string | null = null;

            // STEP 1: If host, create session baseline FIRST (before saving pending changes)
            // This ensures the baseline includes the pending work
            if (isHost && sessionId) {
                console.log('[LiveShareManager] Host: Step 1 - Creating session baseline (with pending changes)');
                baselineSnapshotId = await snapshotManager.createSessionBaseline(userId, teamId, sessionId);
                console.log('[LiveShareManager] Session baseline snapshot ID:', baselineSnapshotId);
            }

            // STEP 2: Save pending changes and pause automatic tracking
            // For hosts: This saves the pending changes as an automatic snapshot (gets AI summary)
            // For guests: Same behavior
            console.log('[LiveShareManager] Step 2 - Saving pending changes and pausing tracking');
            await snapshotManager.pauseAutomaticTracking(userId, teamId);

            console.log('[LiveShareManager] Automatic tracking paused successfully');
            return baselineSnapshotId;
        } catch (err) {
            console.error('[LiveShareManager] Failed to pause automatic tracking:', err);
            return null;
        }
    }
 
    /**
     * Resumes automatic snapshot tracking after a Live Share session ends.
     * Takes a new initial snapshot to set a fresh baseline.
     */
    private async resumeAutomaticSnapshotting() {
        try {
            // Import the snapshot manager
            const { snapshotManager } = await import('../extension.js');

            // Get current user and team
            const userId = await getCurrentUserId();
            if (!userId) {
                console.log('[LiveShareManager] No user ID, skipping snapshot resume');
                return;
            }

            const teamId = this._context.globalState.get<string>(this._teamStateKey);
            const projectName = vscode.workspace.workspaceFolders?.[0]?.name ?? 'untitled-workspace';

            console.log('[LiveShareManager] Resuming automatic snapshot tracking');

            // Resume automatic tracking (this also takes a new baseline snapshot)
            await snapshotManager.resumeAutomaticTracking(userId, projectName, teamId);

            console.log('[LiveShareManager] Automatic tracking resumed successfully');
        } catch (err) {
            console.error('[LiveShareManager] Failed to resume automatic tracking:', err);
        }
    }
}