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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 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 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 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 | import * as vscode from 'vscode';
import { createTeam, joinTeam, getUserTeams, deleteTeam as deleteTeamSvc, leaveTeam as leaveTeamSvc, getTeamMembers, type TeamWithMembership, type TeamMember } from '../services/team-service';
import { validateCurrentProject, getCurrentProjectInfo, getProjectDescription } from '../services/project-detection-service';
import { getCurrentUserId } from '../services/auth-service';
/**
* Provides the webview panel for Agent-specific features (separate from Live Share).
* Shows Team & Product Management and the Agent chat box.
*/
export class AgentPanelProvider implements vscode.WebviewViewProvider {
/** The unique identifier for this webview view type */
public static readonly viewType = 'collabAgent.agentPanel';
/** The webview view instance for displaying the panel */
private _view?: vscode.WebviewView;
/** Global state keys */
private readonly _teamStateKey = 'collabAgent.currentTeam';
/** Current teams cache */
private _userTeams: TeamWithMembership[] = [];
constructor(private readonly _extensionUri: vscode.Uri, private readonly _context: vscode.ExtensionContext) {
// Monitor workspace changes - clear team when no folder open
vscode.workspace.onDidChangeWorkspaceFolders(() => {
// When workspace changes, refresh team info (will clear team if no folders open)
setTimeout(() => {
console.log('Workspace folders changed, updating team info...');
this.postTeamInfo();
}, 500); // Small delay to let workspace settle
});
}
public async resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
) {
this._view = webviewView;
webviewView.webview.options = {
enableScripts: true,
localResourceRoots: [this._extensionUri]
};
// Initialize with team info from database FIRST (before setting HTML)
await this.refreshTeams();
// THEN set HTML (so team data is already loaded)
webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
// Listen for visibility changes - refresh team info when webview becomes visible
webviewView.onDidChangeVisibility(() => {
if (webviewView.visible) {
console.log('[AgentPanel] Webview became visible - refreshing team info');
this.postTeamInfo();
}
});
webviewView.webview.onDidReceiveMessage((message: any) => {
console.log('AgentPanel received message:', message);
switch (message.command) {
case 'webviewReady':
// Webview finished loading - send current team info
console.log('Webview ready - posting team info');
this.postTeamInfo();
break;
case 'createTeam':
console.log('Handling createTeam command');
this.handleCreateTeam();
break;
case 'joinTeam':
console.log('Handling joinTeam command');
this.handleJoinTeam();
break;
case 'switchTeam':
console.log('Handling switchTeam command');
this.handleSwitchTeam();
break;
case 'refreshTeams':
console.log('Handling refreshTeams command');
this.refreshTeams();
break;
case 'aiQuery':
console.log('Handling aiQuery command');
this.handleAiQuery(message.text);
break;
case 'deleteTeam':
console.log('Handling deleteTeam command');
this.handleDeleteTeam();
break;
case 'leaveTeam':
console.log('Handling leaveTeam command');
this.handleLeaveTeam();
break;
case 'addFileSnapshot':
console.log('Handling addFileSnapshot command');
this.addFileSnapshot(message.payload);
break;
// generateSummary handler removed - edge function now handles automatic summarization
case 'loadActivityFeed':
console.log('Handling loadActivityFeed command');
this.loadActivityFeed(message.teamId, message.limit);
case 'publishSnapshot':
console.log('Handling publishSnapshot command');
vscode.commands.executeCommand('collabAgent.publishSnapshot');
break;
default:
console.log('Unknown command received:', message.command);
break;
}
});
}
/**
* Refreshes teams from database and updates UI
*/
private async refreshTeams() {
const result = await getUserTeams();
if (result.error) {
vscode.window.showWarningMessage(`Could not load teams: ${result.error}`);
this._userTeams = [];
} else {
this._userTeams = result.teams || [];
}
// Auto-select the only team when user is only apart of one team and has folder relating to team open
try {
const currentTeamId = this._context.globalState.get<string>(this._teamStateKey);
const hasWorkspace = !!(vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0);
if (!currentTeamId && hasWorkspace && this._userTeams.length === 1) {
const onlyTeam = this._userTeams[0];
const validation = this.validateTeamProject(onlyTeam);
if (validation.isMatch) {
this._context.globalState.update(this._teamStateKey, onlyTeam.id);
}
}
} catch (e) {
}
this.postTeamInfo();
}
/**
* Posts current team info to webview
*/
private postTeamInfo() {
console.log('[AgentPanel] postTeamInfo() called');
console.log('[AgentPanel] _userTeams count:', this._userTeams.length);
const { getAuthContext } = require('../services/auth-service');
let userId: string | null = null;
try {
const ctx = getAuthContext();
// getAuthContext returns a Promise in services; but in constructor context we can't await
// So we'll handle async separately below
} catch {}
// IMPORTANT: If no workspace folder is open, clear current team
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
console.log('[AgentPanel] No workspace folders - clearing team');
// Clear the current team - user must open a project folder first
this._context.globalState.update(this._teamStateKey, undefined);
const teamInfo = {
name: null,
role: null,
joinCode: null,
id: null,
projectValidation: null
};
this._view?.webview.postMessage({
command: 'teamInfo',
teamInfo,
teams: this._userTeams.map(t => ({
id: t.id,
name: t.lobby_name,
role: t.role,
joinCode: t.join_code
}))
});
return;
}
// Get currently selected team from storage
const currentTeamId = this._context.globalState.get<string>(this._teamStateKey);
console.log('[AgentPanel] currentTeamId from globalState:', currentTeamId);
let currentTeam = this._userTeams.find(t => t.id === currentTeamId);
console.log('[AgentPanel] currentTeam found:', currentTeam ? currentTeam.lobby_name : 'NOT FOUND');
// Note: If a team is already loaded, we will auto-trigger the initial snapshot
// This prevents users from having to manually re-select an already-loaded team
// Validate current project if we have an active team
let projectValidation = null;
if (currentTeam) {
const validation = this.validateTeamProject(currentTeam);
projectValidation = {
isMatch: validation.isMatch,
message: validation.message,
details: validation.details
};
}
const teamInfo = currentTeam
? {
name: currentTeam.lobby_name,
role: currentTeam.role === 'admin' ? 'Admin' : 'Member',
joinCode: currentTeam.join_code,
id: currentTeam.id,
projectValidation: projectValidation
}
: { name: null, role: null, joinCode: null, id: null, projectValidation: null };
(async () => {
try {
const { getAuthContext } = require('../services/auth-service');
const res = await getAuthContext();
userId = res?.context?.id || null;
} catch {}
// Fetch team members if we have an active team
let teamMembers: TeamMember[] = [];
if (currentTeam) {
const membersResult = await getTeamMembers(currentTeam.id);
if (!membersResult.error && membersResult.members) {
teamMembers = membersResult.members;
} else if (membersResult.error) {
console.warn('[AgentPanel] Failed to fetch team members:', membersResult.error);
}
}
// Auto-trigger initial snapshot if team is loaded but no baseline exists
if (currentTeam && userId && projectValidation?.isMatch) {
const { snapshotManager } = require('../extension');
if (snapshotManager && !snapshotManager.hasBaselineSnapshot()) {
console.log('[AgentPanel] Team is loaded but no baseline snapshot exists - triggering initial snapshot automatically');
await this.takeInitialSnapshot(currentTeam.id);
}
}
console.log('[AgentPanel] Sending updateTeamInfo to webview:', {
command: 'updateTeamInfo',
team: teamInfo,
userId,
allTeamsCount: this._userTeams.length,
teamMembersCount: teamMembers.length
});
this._view?.webview.postMessage({
command: 'updateTeamInfo',
team: teamInfo,
userId,
allTeams: this._userTeams.map(t => ({
id: t.id,
name: t.lobby_name,
role: t.role === 'admin' ? 'Admin' : 'Member',
joinCode: t.join_code
})),
teamMembers: teamMembers
});
})();
}
// Public methods for MainPanel delegation
public setWebviewForDelegation(view: vscode.WebviewView) {
this._view = view;
}
public async createTeam() {
return await this.handleCreateTeam();
}
public async joinTeam() {
return await this.handleJoinTeam();
}
public async switchTeam() {
return await this.handleSwitchTeam();
}
public async refreshTeamsList() {
return await this.refreshTeams();
}
public async processAiQuery(text: string) {
return this.handleAiQuery(text);
}
/**
* Adds a file snapshot row via service and reports back to webview
*/
public async addFileSnapshot(payload: any) {
try {
const { addFileSnapshot } = require('../services/file-snapshot-service');
const result = await addFileSnapshot(payload);
if (result.success) {
this._view?.webview.postMessage({ command: 'fileSnapshotSaved', id: result.id });
} else {
this._view?.webview.postMessage({ command: 'fileSnapshotError', error: result.error || 'Failed to save snapshot' });
}
} catch (err) {
this._view?.webview.postMessage({ command: 'fileSnapshotError', error: String(err) });
}
}
/**
* Broadcasts a snapshot manually, bypassing automatic snapshot constraints
* Checks for initial snapshot, minimum line changes, and cooldown period
*/
public async broadcastSnapshot() {
try {
console.log('[AgentPanel] broadcastSnapshot called');
// Get current user ID
const userId = await getCurrentUserId();
if (!userId) {
vscode.window.showWarningMessage('Please sign in before broadcasting snapshots');
return;
}
// Get current team ID
const teamId = this._context.globalState.get<string>(this._teamStateKey);
if (!teamId) {
vscode.window.showWarningMessage('Please select a team before broadcasting snapshots');
return;
}
// Get project name
const projectName = vscode.workspace.workspaceFolders?.[0]?.name ?? "untitled-workspace";
// Call snapshotManager's broadcastSnapshot method
const { snapshotManager } = require('../extension');
if (!snapshotManager) {
vscode.window.showErrorMessage('Snapshot manager not initialized');
return;
}
const result = await snapshotManager.broadcastSnapshot(userId, projectName, teamId);
if (result.success) {
console.log('[AgentPanel] Broadcast successful:', result.message);
// Refresh the activity feed to show the new broadcast
await this.loadActivityFeed(teamId);
} else {
console.log('[AgentPanel] Broadcast failed:', result.message);
vscode.window.showWarningMessage(result.message);
}
} catch (err) {
console.error('[AgentPanel] Error broadcasting snapshot:', err);
vscode.window.showErrorMessage(`Failed to broadcast: ${String(err)}`);
}
}
// generateSummary method removed - edge function now handles automatic summarization
/**
* Loads recent activity for a team and posts back to webview.
*/
public async loadActivityFeed(teamId?: string, limit = 25) {
try {
const effectiveTeamId = teamId || this._context.globalState.get<string>(this._teamStateKey);
if (!effectiveTeamId) {
this._view?.webview.postMessage({ command: 'activityError', error: 'No team selected.' });
return;
}
const { fetchTeamActivity } = require('../services/team-activity-service');
const res = await fetchTeamActivity(effectiveTeamId, limit);
if (res.success) {
this._view?.webview.postMessage({ command: 'activityFeed', items: res.items || [] });
} else {
this._view?.webview.postMessage({ command: 'activityError', error: res.error || 'Failed to load activity' });
}
} catch (err) {
this._view?.webview.postMessage({ command: 'activityError', error: String(err) });
}
}
/**
* Handles team creation with database persistence
*/
private async handleCreateTeam() {
const name = await vscode.window.showInputBox({
prompt: 'Enter new team name',
placeHolder: 'My Team',
validateInput: (value) => {
if (!value || value.trim().length === 0) {
return 'Team name cannot be empty';
}
if (value.trim().length > 50) {
return 'Team name must be 50 characters or less';
}
return null;
}
});
if (!name?.trim()) return;
// Show progress
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Creating team...',
cancellable: false
}, async () => {
const result = await createTeam(name.trim());
if (result.error) {
vscode.window.showErrorMessage(`Failed to create team: ${result.error}`);
} else if (result.team && result.joinCode) {
vscode.window.showInformationMessage(
`Created team "${result.team.lobby_name}" with join code: ${result.joinCode}`,
'Copy Join Code'
).then(action => {
if (action === 'Copy Join Code') {
vscode.env.clipboard.writeText(result.joinCode!);
vscode.window.showInformationMessage('Join code copied to clipboard');
}
});
// Refresh teams and set new team as current
await this.refreshTeams();
if (result.team) {
await this._context.globalState.update(this._teamStateKey, result.team.id);
this.postTeamInfo();
}
}
});
}
/**
* Handles joining a team by join code
*/
private async handleJoinTeam() {
const joinCode = await vscode.window.showInputBox({
prompt: 'Enter 6-character team join code',
placeHolder: 'ABC123',
validateInput: (value) => {
if (!value || value.trim().length === 0) {
return 'Join code cannot be empty';
}
if (value.trim().length !== 6) {
return 'Join code must be exactly 6 characters';
}
if (!/^[A-Z0-9]+$/i.test(value.trim())) {
return 'Join code must contain only letters and numbers';
}
return null;
}
});
if (!joinCode?.trim()) return;
// First, validate project compatibility before joining
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Validating team...',
cancellable: false
}, async () => {
// Get team info first without joining
const teamLookupResult = await this.lookupTeamByJoinCode(joinCode.trim());
if (teamLookupResult.error) {
vscode.window.showErrorMessage(`Failed to find team: ${teamLookupResult.error}`);
return;
}
if (!teamLookupResult.team) {
vscode.window.showErrorMessage('Team not found with that join code');
return;
}
// Validate project match BEFORE joining
if (teamLookupResult.team.project_identifier) {
const validation = this.validateTeamProjectForJoin(teamLookupResult.team);
if (!validation.isMatch) {
const action = await vscode.window.showErrorMessage(
`Cannot join team "${teamLookupResult.team.lobby_name}"`,
{
modal: true,
detail: `${validation.message}\n\n${validation.details}\n\nYou must have the correct project folder open to join this team.`
},
'Open Correct Project',
'Cancel'
);
if (action === 'Open Correct Project') {
this.showProjectGuidance(teamLookupResult.team as TeamWithMembership);
}
return; // Don't proceed with join
}
}
// Project matches or team has no project requirement, proceed with join
const result = await joinTeam(joinCode.trim());
if (result.error) {
vscode.window.showErrorMessage(`Failed to join team: ${result.error}`);
} else if (result.alreadyMember && result.team) {
vscode.window.showInformationMessage(`You're already a member of team "${result.team.lobby_name}"`);
// Ensures selection is set to that team for convenience
await this.refreshTeams();
await this._context.globalState.update(this._teamStateKey, result.team.id);
this.postTeamInfo();
} else if (result.team) {
vscode.window.showInformationMessage(`Successfully joined team "${result.team.lobby_name}"`);
// Refresh teams and set new team as current
await this.refreshTeams();
await this._context.globalState.update(this._teamStateKey, result.team.id);
this.postTeamInfo();
}
});
}
/**
* Handles switching between user's teams
*/
private async handleSwitchTeam() {
if (this._userTeams.length === 0) {
vscode.window.showInformationMessage('You are not a member of any teams. Create or join a team first.');
return;
}
// Allow team selection even for single-team users
// This is necessary to trigger the initial snapshot and validate project match
const teamOptions = this._userTeams.map(team => ({
label: team.lobby_name,
description: `${team.role === 'admin' ? 'Admin' : 'Member'} • Code: ${team.join_code}`,
team: team
}));
const selected = await vscode.window.showQuickPick(teamOptions, {
placeHolder: this._userTeams.length === 1
? 'Select your team to activate snapshot tracking'
: 'Select a team to switch to'
});
if (selected) {
// Check if workspace folder is open
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
await vscode.window.showErrorMessage(
`Cannot switch to team "${selected.team.lobby_name}"`,
{
modal: true,
detail: 'You must open a project folder first.\n\nPlease open the Git repository folder for the team you want to switch to, then try again.'
},
'Open Folder',
'Cancel'
).then(action => {
if (action === 'Open Folder') {
vscode.commands.executeCommand('vscode.openFolder');
}
});
return;
}
// Debug: Log team data to see what's missing
console.log('Team data for switch:', {
name: selected.team.lobby_name,
project_identifier: selected.team.project_identifier,
project_repo_url: selected.team.project_repo_url,
project_name: selected.team.project_name
});
// Validate that the current project matches the team's project
const validation = this.validateTeamProject(selected.team);
if (!validation.isMatch) {
await vscode.window.showErrorMessage(
`Cannot switch to team "${selected.team.lobby_name}"`,
{
modal: true,
detail: validation.details
},
'Open Correct Project',
'Cancel'
).then(action => {
if (action === 'Open Correct Project') {
this.showProjectGuidance(selected.team);
}
});
return;
}
// Project matches - allow switch
const currentTeamId = this._context.globalState.get<string>(this._teamStateKey);
const isSameTeam = currentTeamId === selected.team.id;
await this._context.globalState.update(this._teamStateKey, selected.team.id);
if (isSameTeam) {
vscode.window.showInformationMessage(`Team "${selected.team.lobby_name}" activated - snapshot tracking enabled`);
} else {
vscode.window.showInformationMessage(`Successfully switched to team "${selected.team.lobby_name}"`);
}
this.postTeamInfo();
// Take initial snapshot for this team
await this.takeInitialSnapshot(selected.team.id);
}
}
/**
* Takes initial snapshot when team is selected
* This captures the baseline state of the workspace and enables automatic snapshot tracking
*/
private async takeInitialSnapshot(teamId: string) {
try {
const { getCurrentUserId } = require('../services/auth-service');
const userId = await getCurrentUserId();
if (!userId) {
console.warn('[AgentPanel] No user ID - skipping initial snapshot');
return;
}
const projectName = vscode.workspace.workspaceFolders?.[0]?.name ?? "untitled-workspace";
const { snapshotManager } = require('../extension');
if (snapshotManager) {
// Always take initial snapshot when team is selected/switched
// This creates a fresh baseline for automatic snapshot tracking
await snapshotManager.takeSnapshot(userId, projectName, teamId);
console.log(`[AgentPanel] Initial snapshot captured for team: ${teamId}`);
}
} catch (error) {
console.error('[AgentPanel] Failed to take initial snapshot:', error);
}
}
private handleAiQuery(text: string) {
const reply = `Agent received: "${text}"`;
this._view?.webview.postMessage({ command: 'aiResponse', text: reply });
}
/**
* Gets the inner HTML content for embedding in the main panel
* This loads from the external HTML file and extracts only the body content
*/
public getInnerHtml(): string {
const fs = require('fs');
const path = require('path');
try {
// Read HTML template from external file
const htmlPath = path.join(this._extensionUri.fsPath, 'media', 'agentPanel.html');
let htmlContent = fs.readFileSync(htmlPath, 'utf8');
// Extract just the body content (between <body> and </body>)
const bodyMatch = htmlContent.match(/<body>([\s\S]*)<script/);
if (bodyMatch && bodyMatch[1]) {
return bodyMatch[1].trim();
}
// Fallback if pattern doesn't match
console.error('[AgentPanel] Could not extract body content from agentPanel.html');
return '<div>Error loading panel content</div>';
} catch (error) {
console.error('[AgentPanel] Error reading agentPanel.html:', error);
return '<div>Error loading panel content</div>';
}
}
private _getHtmlForWebview(webview: vscode.Webview) {
const fs = require('fs');
const path = require('path');
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'agentPanel.js'));
const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'panel.css'));
const nonce = Date.now().toString();
// Read HTML template from external file
const htmlPath = path.join(this._extensionUri.fsPath, 'media', 'agentPanel.html');
let htmlContent = fs.readFileSync(htmlPath, 'utf8');
// Replace placeholders
htmlContent = htmlContent
.replace(/\{\{STYLE_URI\}\}/g, styleUri.toString())
.replace(/\{\{SCRIPT_URI\}\}/g, scriptUri.toString())
.replace(/\{\{NONCE\}\}/g, nonce);
return htmlContent;
}
/**
* STRICT validation for team switching - no exceptions allowed
*/
private validateTeamProjectForSwitch(team: TeamWithMembership): {
isMatch: boolean;
message: string;
details: string;
} {
// Check 1: No workspace folder open
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) {
return {
isMatch: false,
message: `No project folder open`,
details: `To switch to team "${team.lobby_name}", you must first open the team's Git repository folder in VS Code.\n\nRequired: ${team.project_repo_url || team.project_name || 'Team project'}\n\nPlease:\n1. Open the correct project folder\n2. Try switching teams again`
};
}
// Check 2: All teams require Git projects
if (!team.project_identifier || !team.project_repo_url) {
return {
isMatch: false,
message: `Team "${team.lobby_name}" requires Git repository`,
details: 'This team was created before Git requirements were enforced.\n\nAll teams must be linked to Git repositories.\nContact the team admin to recreate the team with a Git repository.'
};
}
// Check 3: Current folder must be Git-initialized
const currentProject = getCurrentProjectInfo();
if (!currentProject || !currentProject.isGitRepo) {
const folderName = currentProject?.projectName || 'Non-Git folder';
return {
isMatch: false,
message: `Current folder is not a Git repository`,
details: `Team "${team.lobby_name}" requires a Git repository, but your current folder is not Git-initialized.\n\nRequired: ${team.project_repo_url}\nCurrent: ${folderName}\n\nPlease:\n1. Close this folder\n2. Open the team's Git repository\n3. Try switching again`
};
}
// Check 4: Git repository hash must match exactly
const validation = validateCurrentProject(team.project_identifier, team.project_repo_url);
if (validation.isMatch) {
return {
isMatch: true,
message: `Project matches team "${team.lobby_name}"`,
details: `Current project: ${getProjectDescription(currentProject)}\nTeam project: ${team.project_repo_url}`
};
}
// Check 5: Project hash mismatch - wrong Git repository
const currentDesc = getProjectDescription(currentProject);
const teamDesc = team.project_repo_url || team.project_name || 'Unknown project';
return {
isMatch: false,
message: `Wrong Git repository open`,
details: `Team "${team.lobby_name}" requires a specific Git repository, but you have a different one open.\n\nCurrent: ${currentDesc}\nRequired: ${teamDesc}\n\nReason: ${validation.reason || 'Git repository fingerprints do not match'}\n\nPlease:\n1. Clone the correct repository: git clone ${team.project_repo_url}\n2. Open the cloned folder in VS Code\n3. Try switching teams again`
};
}
/**
* Validates if the current workspace project matches the team's project
*/
private validateTeamProject(team: TeamWithMembership): {
isMatch: boolean;
message: string;
details: string;
} {
// All teams now require Git projects - no project info means old team
if (!team.project_identifier || !team.project_repo_url) {
return {
isMatch: false,
message: `Team "${team.lobby_name}" requires Git repository`,
details: 'This team was created before Git requirements were enforced. Contact the team admin to recreate the team with a Git repository.'
};
}
const validation = validateCurrentProject(team.project_identifier, team.project_repo_url);
if (validation.isMatch) {
return {
isMatch: true,
message: `Project matches team "${team.lobby_name}"`,
details: validation.currentProject ?
`Current project: ${getProjectDescription(validation.currentProject)}` :
'Project validation successful'
};
}
// Project mismatch
const currentDesc = validation.currentProject ?
getProjectDescription(validation.currentProject) :
'No workspace open';
const teamDesc = team.project_repo_url || team.project_name || 'Unknown project';
return {
isMatch: false,
message: `Wrong Git repository open for team "${team.lobby_name}"`,
details: `Current: ${currentDesc}\nRequired: ${teamDesc}\n\n${validation.reason || 'Git repositories do not match'}\n\nPlease clone the correct repository and open it in VS Code.`
};
}
/**
* Shows guidance on how to open the correct project for the team
*/
private showProjectGuidance(team: TeamWithMembership) {
const teamRepoUrl = team.project_repo_url || 'the team repository';
vscode.window.showInformationMessage(
`To collaborate with team "${team.lobby_name}", you must have the correct Git repository cloned locally.`,
{
modal: true,
detail: `Team Repository: ${teamRepoUrl}\n\nRequired Steps:\n1. Clone the repository: git clone ${teamRepoUrl}\n2. Open the cloned folder in VS Code\n3. Switch back to this team\n\nTeam functionality only works with Git repositories.\nAll members must have the same repository cloned locally.`
},
'Open Folder',
'Copy Git URL',
'Got It'
).then(action => {
if (action === 'Open Folder') {
vscode.commands.executeCommand('vscode.openFolder');
} else if (action === 'Copy Git URL' && team.project_repo_url) {
vscode.env.clipboard.writeText(team.project_repo_url);
vscode.window.showInformationMessage('Git repository URL copied to clipboard');
}
});
}
/**
* Looks up a team by join code without joining it (for validation)
*/
private async lookupTeamByJoinCode(joinCode: string): Promise<{ team?: any; error?: string }> {
try {
const { getSupabase } = require('../auth/supabaseClient');
const supabase = await getSupabase();
console.log('Looking up team with join code via RPC:', joinCode.toUpperCase());
// Use secure RPC that bypasses RLS safely (SECURITY DEFINER)
const { data: teamData, error: teamError } = await supabase
.rpc('get_team_by_join_code', { p_join_code: joinCode.toUpperCase() })
.maybeSingle();
console.log('Team lookup result (rpc):', { teamData, teamError, searchCode: joinCode.toUpperCase() });
if (teamError || !teamData) {
return { error: `Invalid join code or team not found. Error: ${teamError?.message || 'No team found'}` };
}
return { team: teamData };
} catch (error) {
return { error: `Team lookup failed: ${error}` };
}
}
/**
* Validates project for join operation (stricter than switch validation)
*/
private validateTeamProjectForJoin(team: any): {
isMatch: boolean;
message: string;
details: string;
} {
// If team has no project information, allow join
if (!team.project_identifier) {
return {
isMatch: true,
message: 'Team has no specific project requirements',
details: 'This team is not linked to a specific project.'
};
}
const validation = validateCurrentProject(team.project_identifier, team.project_repo_url);
if (validation.isMatch) {
return {
isMatch: true,
message: `Project matches team "${team.lobby_name}"`,
details: validation.currentProject ?
`Current project: ${getProjectDescription(validation.currentProject)}` :
'Project validation successful'
};
}
// Strict validation for join - require exact match
const currentDesc = validation.currentProject ?
getProjectDescription(validation.currentProject) :
'No workspace open';
const teamDesc = team.project_repo_url || team.project_name || 'Unknown project';
return {
isMatch: false,
message: `Project mismatch detected`,
details: `Current: ${currentDesc}\nRequired: ${teamDesc}\n\nReason: ${validation.reason || 'Project fingerprints do not match'}`
};
}
/**
* Delete current team (admin only) with confirmation
*/
private async handleDeleteTeam() {
// Determine current team from global state
const currentTeamId = this._context.globalState.get<string>(this._teamStateKey);
if (!currentTeamId) {
vscode.window.showInformationMessage('No active team selected.');
return;
}
const currentTeam = this._userTeams.find(t => t.id === currentTeamId);
if (!currentTeam) {
vscode.window.showErrorMessage('Current team not found. Please refresh teams.');
return;
}
if (currentTeam.role !== 'admin') {
vscode.window.showErrorMessage('Only the Team Admin can delete this team.');
return;
}
const confirm = await vscode.window.showWarningMessage(
`Delete team "${currentTeam.lobby_name}"?`,
{
modal: true,
detail: 'This will permanently remove the team and all memberships. This action cannot be undone.'
},
'Yes, Delete',
'Cancel'
);
if (confirm !== 'Yes, Delete') return;
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `Deleting team "${currentTeam.lobby_name}"...`,
cancellable: false
}, async () => {
const res = await deleteTeamSvc(currentTeamId);
if (!res.success) {
vscode.window.showErrorMessage(res.error || 'Failed to delete team');
return;
}
// Clear current selection and refresh
await this._context.globalState.update(this._teamStateKey, undefined);
await this.refreshTeams();
vscode.window.showInformationMessage(`Team "${currentTeam.lobby_name}" was deleted.`);
});
}
/**
* Leave current team (member only) with confirmation
*/
private async handleLeaveTeam() {
const currentTeamId = this._context.globalState.get<string>(this._teamStateKey);
if (!currentTeamId) {
vscode.window.showInformationMessage('No active team selected.');
return;
}
const currentTeam = this._userTeams.find(t => t.id === currentTeamId);
if (!currentTeam) {
vscode.window.showErrorMessage('Current team not found. Please refresh teams.');
return;
}
if (currentTeam.role === 'admin') {
vscode.window.showErrorMessage('Admins cannot leave their own team. You can delete the team instead.');
return;
}
const confirm = await vscode.window.showWarningMessage(
`Leave team "${currentTeam.lobby_name}"?`,
{
modal: true,
detail: 'You will be removed from this team and lose access to it. You can rejoin later with a valid join code.'
},
'Yes, Leave',
'Cancel'
);
if (confirm !== 'Yes, Leave') return;
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `Leaving team "${currentTeam.lobby_name}"...`,
cancellable: false
}, async () => {
const res = await leaveTeamSvc(currentTeamId);
if (!res.success) {
vscode.window.showErrorMessage(res.error || 'Failed to leave team');
return;
}
await this._context.globalState.update(this._teamStateKey, undefined);
await this.refreshTeams();
vscode.window.showInformationMessage(`You have left team "${currentTeam.lobby_name}".`);
});
}
}
|