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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x | import * as vscode from 'vscode';
import { LiveShareManager } from './LiveSharePanel';
import { AgentPanelProvider } from './AgentPanel';
import { HomeScreenPanel } from './HomeScreenPanel';
import { TasksPanel } from './TasksPanel';
import { ProfilePanel } from './ProfilePanel';
import { BASE_URL } from '../api/types/endpoints';
import { getAuthContext, setAuthContext, handleSignOut, signInOrUpMenu } from '../services/auth-service';
/**
* Main orchestrator panel that manages and displays five sub-panels:
* - Home Screen (authentication, welcome, user info)
* - Live Share (collaboration sessions, team messaging)
* - Agent Panel (team management, AI chat bot)
* - Tasks Panel (Jira task integration)
* - Profile (user profile and preferences)
*/
export class CollabAgentPanelProvider implements vscode.WebviewViewProvider {
/** The unique identifier for this webview view type */
public static readonly viewType = 'collabAgent.teamActivity';
/** The webview view instance for displaying the panel */
private _view?: vscode.WebviewView;
/** Live Share manager instance for Live Share functionality */
private _liveShareManager: LiveShareManager;
/** Agent panel provider instance for agent functionality */
private _agentPanel: AgentPanelProvider;
/** Home screen panel instance for home functionality */
private _homeScreen: HomeScreenPanel;
/** Tasks panel instance for Jira task integration */
private _tasksPanel: TasksPanel;
/** Profile panel instance for user profile management */
private _profilePanel: ProfilePanel;
/** Interval to monitor auth state changes */
private _authMonitorInterval: any | undefined;
/** Cached last known auth state */
private _lastAuthState: boolean | undefined;
/**
* Creates a new MainPanel orchestrator instance.
*
* @param _extensionUri - The URI of the extension for loading resources
* @param _context - The extension context for state management
*/
constructor(private readonly _extensionUri: vscode.Uri, private readonly _context: vscode.ExtensionContext) {
this._liveShareManager = new LiveShareManager(this._context);
this._agentPanel = new AgentPanelProvider(this._extensionUri, this._context);
this._homeScreen = new HomeScreenPanel(this._extensionUri, this._context);
this._tasksPanel = new TasksPanel(this._context);
this._profilePanel = new ProfilePanel(this._extensionUri, this._context);
}
/**
* Resolves the webview view when it becomes visible.
* Sets up the webview HTML, message handlers, and initializes Live Share.
*
* @param webviewView - The webview view to resolve
* @param context - The resolution context
* @param _token - Cancellation token (unused)
*/
public async resolveWebviewView(
webviewView: vscode.WebviewView,
context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
) {
console.log("MainPanel: resolveWebviewView called");
this._view = webviewView;
webviewView.webview.options = {
enableScripts: true,
localResourceRoots: [this._extensionUri]
};
webviewView.webview.html = await this._getHtmlForWebview(webviewView.webview);
console.log("MainPanel: HTML set, webview should be ready");
// Set up sub-panels with the webview for delegation
this._liveShareManager.setView(webviewView);
this._agentPanel.setWebviewForDelegation(webviewView);
this._tasksPanel.setWebview(webviewView);
await this._liveShareManager.initializeLiveShare();
await this._agentPanel.refreshTeamsList(); // Initialize agent teams
await this._tasksPanel.initializePanel(); // Initialize tasks panel
this.startAuthMonitor();
webviewView.webview.onDidReceiveMessage(
async (message: any) => {
console.log('MainPanel received message:', message);
// Delegate Live Share commands to LiveShareManager
if (this.isLiveShareCommand(message.command)) {
await this.handleLiveShareMessage(message);
return;
}
// Delegate Agent commands to AgentPanel
if (this.isAgentCommand(message.command)) {
await this.handleAgentMessage(message);
return;
}
// Delegate Tasks commands to TasksPanel
if (this.isTasksCommand(message.command)) {
await this.handleTasksMessage(message);
return;
}
// Delegate Profile commands to Profile handlers
if (this.isProfileCommand(message.command)) {
await this.handleProfileMessage(message);
return;
}
// Handle Home/Auth commands directly in MainPanel
switch (message.command) {
case 'loginOrSignup':
await this.handleLoginOrSignup();
return;
case 'installLiveShare':
await this.handleInstallLiveShare();
return;
default:
console.log('Unknown command received in MainPanel:', message.command);
}
},
undefined,
[]
);
}
/** Check if a command is related to Live Share functionality */
private isLiveShareCommand(command: string): boolean {
return [
'startLiveShare',
'joinLiveShare',
'joinLiveShareWithLink',
'endLiveShare',
'leaveLiveShare',
'sendTeamMessage',
'manualSetInviteLink',
'manualClearInviteLink',
'requestStoredLink',
'manualPasteInviteLink'
].includes(command);
}
/** Check if a command is related to Agent functionality */
private isAgentCommand(command: string): boolean {
return [
'createTeam',
'joinTeam',
'switchTeam',
'refreshTeams',
'deleteTeam',
'leaveTeam',
'aiQuery',
'addFileSnapshot',
// 'generateSummary' removed - edge function now handles automatic summarization
'loadActivityFeed',
'broadcastSnapshot',
'broadcastBlockedBySession'
].includes(command);
}
/** Check if a command is related to Tasks functionality */
private isTasksCommand(command: string): boolean {
return [
'tasksWebviewReady',
'connectJira',
'connectJiraWithCredentials',
'disconnectJira',
'refreshTasks',
'retryTasks',
'loadSprint',
'loadBacklog',
'transitionIssue',
'reassignIssue',
'updateStoryPoints',
'updatePriority',
'fetchAssignableUsers',
'createTask',
'getAISuggestions',
'assignTaskFromTimeline',
'reassignIssueFromTimeline'
].includes(command);
}
/** Check if a command is related to Profile functionality */
private isProfileCommand(command: string): boolean {
return [
'saveProfile',
'loadProfile',
'deleteAccount'
].includes(command);
}
/** Delegate Live Share message to LiveShareManager */
private async handleLiveShareMessage(message: any) {
switch (message.command) {
case 'startLiveShare':
this._liveShareManager.startLiveShareSession();
break;
case 'joinLiveShare':
this._liveShareManager.joinLiveShareSession();
break;
case 'joinLiveShareWithLink':
this._liveShareManager.joinLiveShareSessionWithLink(message.link);
break;
case 'endLiveShare':
this._liveShareManager.endLiveShareSession();
break;
case 'leaveLiveShare':
this._liveShareManager.leaveLiveShareSession();
break;
case 'sendTeamMessage':
this._liveShareManager.sendTeamMessage(message.text);
break;
case 'manualSetInviteLink':
this._liveShareManager.setManualInviteLink(message.link);
break;
case 'manualClearInviteLink':
this._liveShareManager.clearManualInviteLink();
break;
case 'requestStoredLink':
this._liveShareManager.sendStoredLinkToWebview();
break;
case 'manualPasteInviteLink':
this._liveShareManager.pasteInviteLinkFromClipboard();
break;
}
}
/** Delegate Agent message to AgentPanel */
private async handleAgentMessage(message: any) {
console.log('Agent command delegated:', message.command);
switch (message.command) {
case 'createTeam':
await this._agentPanel.createTeam();
break;
case 'joinTeam':
await this._agentPanel.joinTeam();
break;
case 'switchTeam':
await this._agentPanel.switchTeam();
break;
case 'refreshTeams':
await this._agentPanel.refreshTeamsList();
break;
case 'deleteTeam':
await (this._agentPanel as any).handleDeleteTeam?.();
// If private, call public via message delegation pattern
if (!(this._agentPanel as any).handleDeleteTeam) {
// Fallback: send message to AgentPanel's own handler via webview
this._view?.webview.postMessage({ command: 'deleteTeam' });
}
break;
case 'leaveTeam':
await (this._agentPanel as any).handleLeaveTeam?.();
if (!(this._agentPanel as any).handleLeaveTeam) {
this._view?.webview.postMessage({ command: 'leaveTeam' });
}
break;
case 'aiQuery':
await this._agentPanel.processAiQuery(message.text);
break;
case 'addFileSnapshot':
await (this._agentPanel as any).addFileSnapshot?.(message.payload);
break;
// generateSummary case removed - edge function now handles automatic summarization
case 'loadActivityFeed':
await (this._agentPanel as any).loadActivityFeed?.(message.teamId, message.limit);
break;
case 'broadcastSnapshot':
await (this._agentPanel as any).broadcastSnapshot?.();
break;
case 'broadcastBlockedBySession':
vscode.window.showWarningMessage('Cannot broadcast changes while in an active Live Share session. Please end the session first.');
break;
default:
console.log('Unknown agent command:', message.command);
}
}
/** Delegate Tasks message to TasksPanel */
private async handleTasksMessage(message: any) {
console.log('Tasks command delegated:', message.command);
switch (message.command) {
case 'tasksWebviewReady':
// Webview is ready, refresh panel state
await this._tasksPanel.updatePanelState();
break;
case 'connectJira':
await this._tasksPanel.handleConnectJira();
break;
case 'connectJiraWithCredentials':
await this._tasksPanel.handleConnectJiraWithCredentials(message.jiraUrl, message.jiraEmail, message.jiraToken);
break;
case 'disconnectJira':
await this._tasksPanel.handleDisconnectJira();
break;
case 'refreshTasks':
await this._tasksPanel.handleRefreshTasks();
break;
case 'retryTasks':
await this._tasksPanel.handleRefreshTasks();
break;
case 'loadSprint':
await this._tasksPanel.handleLoadSprint(message.sprintId);
break;
case 'loadBacklog':
await this._tasksPanel.handleLoadBacklog();
break;
case 'transitionIssue':
await this._tasksPanel.handleTransitionIssue(message.issueKey, message.targetStatus);
break;
case 'reassignIssue':
await this._tasksPanel.handleReassignIssue(message.issueKey, message.accountId);
break;
case 'updateStoryPoints':
await this._tasksPanel.handleUpdateStoryPoints(message.issueKey, message.storyPoints);
break;
case 'updatePriority':
await this._tasksPanel.handleUpdatePriority(message.issueKey, message.priorityName);
break;
case 'fetchAssignableUsers':
await this._tasksPanel.handleFetchAssignableUsers();
break;
case 'createTask':
await this._tasksPanel.handleCreateTask(message.taskData);
break;
case 'getAISuggestions':
await this._tasksPanel.handleGetAISuggestions();
break;
case 'assignTaskFromTimeline':
await this.handleAssignTaskFromTimeline(message.taskKey, message.activityId);
break;
case 'reassignIssueFromTimeline':
await this.handleReassignIssueFromTimeline(message.issueKey, message.accountId, message.activityId, message.displayName);
break;
default:
console.log('Unknown tasks command:', message.command);
}
}
/** Delegate Profile message to Profile handlers */
private async handleProfileMessage(message: any) {
console.log('Profile command received:', message.command);
switch (message.command) {
case 'saveProfile':
await this.handleSaveProfile(message.profileData);
break;
case 'loadProfile':
await this.handleLoadProfile();
break;
case 'deleteAccount':
await this.handleDeleteAccount();
break;
default:
console.log('Unknown profile command:', message.command);
}
}
private async handleSaveProfile(profileData: any) {
try {
const authResult = await getAuthContext();
if (!authResult || !authResult.context || !authResult.context.isAuthenticated) {
vscode.window.showErrorMessage('You must be logged in to save your profile.');
return;
}
const user = authResult.context;
// Sanitize and limit skills to prevent abuse
const sanitizeSkillArray = (arr: string[], maxCount: number = 18, maxLength: number = 30): string[] => {
if (!Array.isArray(arr)) return [];
return arr
.slice(0, maxCount) // Max 18 skills
.map(skill => String(skill).trim().substring(0, maxLength)) // Max 30 chars each
.filter(skill => skill.length > 0); // Remove empty strings
};
const payload = {
user_id: user.id,
name: (profileData.name || '').substring(0, 100), // Max 100 chars for name
interests: sanitizeSkillArray(profileData.interests || []),
custom_skills: sanitizeSkillArray(profileData.custom_skills || [])
};
const token = user.auth_token || user.id || 'no-token-available';
const response = await fetch(`${BASE_URL}/api/profile`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(payload)
});
if (response.ok) {
const result = await response.json();
vscode.window.showInformationMessage('Profile saved successfully!');
this._view?.webview.postMessage({
command: 'profileSaved',
success: true,
profile: result.profile
});
} else {
const error = await response.text();
vscode.window.showErrorMessage(`Failed to save profile: ${error}`);
this._view?.webview.postMessage({
command: 'profileSaved',
success: false,
error: error
});
}
} catch (err) {
console.error('Error saving profile:', err);
vscode.window.showErrorMessage('Error saving profile. Please try again.');
this._view?.webview.postMessage({
command: 'profileSaved',
success: false,
error: String(err)
});
}
}
private async handleLoadProfile() {
try {
const authResult = await getAuthContext();
if (!authResult || !authResult.context || !authResult.context.isAuthenticated) {
console.log('User not authenticated, cannot load profile');
this._view?.webview.postMessage({
command: 'profileLoadError',
error: 'Not authenticated'
});
return;
}
let user = authResult.context;
// Migration fix: If auth_token is missing, try to get it from Supabase session
if (!user.auth_token) {
console.log('Auth token missing, attempting to refresh from Supabase session...');
const { getSupabase } = require('../auth/supabaseClient');
const supabase = getSupabase();
const { data: sessionData } = await supabase.auth.getSession();
const token = sessionData?.session?.access_token;
if (token) {
console.log('Found token in Supabase session, refreshing user data...');
const { getUserByID } = require('../api/user-api');
const { user: refreshedUser, error: refreshError } = await getUserByID(token);
if (!refreshError && refreshedUser) {
await setAuthContext(refreshedUser);
user = refreshedUser;
console.log('User context refreshed with auth_token');
} else {
console.error('Failed to refresh user data:', refreshError);
this._view?.webview.postMessage({
command: 'profileLoadError',
error: 'Failed to refresh authentication'
});
return;
}
} else {
console.error('No token found in Supabase session');
this._view?.webview.postMessage({
command: 'profileLoadError',
error: 'Auth token missing - please sign out and sign in again'
});
return;
}
}
const response = await fetch(`${BASE_URL}/api/profile?user_id=${user.id}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${user.auth_token}`
}
});
if (response.ok) {
const result = await response.json();
console.log('Profile loaded successfully');
this._view?.webview.postMessage({
command: 'profileLoaded',
profile: result.profile
});
} else {
const errorText = await response.text();
console.error('Failed to load profile:', errorText);
this._view?.webview.postMessage({
command: 'profileLoadError',
error: errorText
});
}
} catch (err) {
console.error('Error loading profile:', err);
this._view?.webview.postMessage({
command: 'profileLoadError',
error: err instanceof Error ? err.message : 'Unknown error'
});
}
}
private async handleDeleteAccount() {
try {
console.log('[DELETE ACCOUNT] Starting deletion');
const authResult = await getAuthContext();
if (!authResult || !authResult.context || !authResult.context.isAuthenticated) {
vscode.window.showErrorMessage('You must be logged in to delete your account.');
return;
}
const user = authResult.context;
const { getSupabase } = require('../auth/supabaseClient');
const supabase = getSupabase();
const { data: sessionData } = await supabase.auth.getSession();
const token = sessionData?.session?.access_token;
if (!token) {
vscode.window.showErrorMessage('Authentication token missing. Please sign out and sign in again.');
return;
}
console.log('[DELETE ACCOUNT] Calling backend:', `${BASE_URL}/api/account/delete`);
const response = await fetch(`${BASE_URL}/api/account/delete`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const result = await response.json();
console.log('[DELETE ACCOUNT] Success:', result);
await handleSignOut();
vscode.window.showInformationMessage('Your account has been successfully deleted.');
this._view?.webview.postMessage({ command: 'accountDeleted', success: true });
await new Promise(resolve => setTimeout(resolve, 500));
if (this._view) {
this._view.webview.html = await this._getHtmlForWebview(this._view.webview);
}
} else {
const errorData = await response.text();
console.error('[DELETE ACCOUNT] Error:', errorData);
let errorMessage = 'Failed to delete account.';
try {
const errorJson = JSON.parse(errorData);
errorMessage = errorJson.error || errorMessage;
} catch { }
vscode.window.showErrorMessage(`Failed to delete account: ${errorMessage}`);
this._view?.webview.postMessage({ command: 'accountDeleted', success: false, error: errorMessage });
}
} catch (err) {
console.error('[DELETE ACCOUNT] Exception:', err);
vscode.window.showErrorMessage('Error deleting account. Please try again.');
this._view?.webview.postMessage({ command: 'accountDeleted', success: false, error: String(err) });
}
}
/** Handle login/signup authentication */
private async handleLoginOrSignup() {
try {
await signInOrUpMenu();
// Small delay to allow auth state to persist
await new Promise(resolve => setTimeout(resolve, 300));
// Refresh the panel HTML to reflect logged-in status
if (this._view) {
this._view.webview.html = await this._getHtmlForWebview(this._view.webview);
}
} catch (err) {
let msg = 'Failed to start login/signup flow.';
if (err && typeof err === 'object') {
if ('message' in err && typeof (err as any).message === 'string') {
msg += ' ' + (err as any).message;
} else {
msg += ' ' + JSON.stringify(err);
}
} else if (typeof err === 'string') {
msg += ' ' + err;
}
vscode.window.showErrorMessage(msg);
}
}
/** Handle assign task from timeline - fetch assignable users and show modal */
private async handleAssignTaskFromTimeline(taskKey: string, activityId: string) {
try {
// Get current team ID
const currentTeamId = this._context.globalState.get<string>('collabAgent.currentTeam');
if (!currentTeamId) {
vscode.window.showErrorMessage('No team selected. Please select a team first.');
return;
}
// Fetch assignable users from Jira
const { JiraService } = require('../services/jira-service');
const jiraService = JiraService.getInstance();
const users = await jiraService.fetchAssignableUsers(currentTeamId);
// Send users to webview to show modal
this._view?.webview.postMessage({
command: 'showAssignableUsersModal',
users: users,
taskKey: taskKey,
activityId: activityId
});
} catch (error) {
console.error('Failed to fetch assignable users from timeline:', error);
vscode.window.showErrorMessage(
`Failed to fetch assignable users: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/** Handle reassign issue from timeline - reassign task and update UI */
private async handleReassignIssueFromTimeline(issueKey: string, accountId: string, activityId: string, displayName?: string) {
try {
// Get current team ID
const currentTeamId = this._context.globalState.get<string>('collabAgent.currentTeam');
if (!currentTeamId) {
vscode.window.showErrorMessage('No team selected. Please select a team first.');
return;
}
// Call the Tasks Panel's reassign handler
await this._tasksPanel.handleReassignIssue(issueKey, accountId);
// Update the activity feed record to mark it as assigned
const authResult = await getAuthContext();
if (authResult?.context?.isAuthenticated) {
try {
const response = await fetch(`${BASE_URL}/api/activity/mark-assigned`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
activity_id: activityId,
is_assigned: true,
assigned_to: displayName || 'Unknown User'
})
});
if (!response.ok) {
console.error('Failed to update activity feed assignment status');
}
} catch (dbError) {
console.error('Error updating activity feed:', dbError);
// Don't fail the whole operation if this fails
}
}
// Notify webview that assignment was successful
this._view?.webview.postMessage({
command: 'taskAssignedFromTimeline',
activityId: activityId,
success: true,
displayName: displayName
});
} catch (error) {
console.error('Failed to reassign issue from timeline:', error);
// Notify webview that assignment failed
this._view?.webview.postMessage({
command: 'taskAssignedFromTimeline',
activityId: activityId,
success: false
});
vscode.window.showErrorMessage(
`Failed to assign task: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/** Handle Live Share extension installation */
private async handleInstallLiveShare() {
await vscode.commands.executeCommand('workbench.extensions.installExtension', 'ms-vsliveshare.vsliveshare');
vscode.window.showInformationMessage('Live Share extension installation triggered. Reloading to finalize installation...');
// Inform webview before reload
this._view?.webview.postMessage({ command: 'liveShareInstalling' });
// Small delay to allow message to render
await new Promise(resolve => setTimeout(resolve, 500));
await vscode.commands.executeCommand('workbench.action.reloadWindow');
}
/** Starts monitoring auth state and refreshes panel on changes */
private startAuthMonitor() {
this.stopAuthMonitor();
this._authMonitorInterval = setInterval(async () => {
try {
const result = await getAuthContext();
const isAuthed = !!(result && result.context && result.context.isAuthenticated);
if (this._lastAuthState === undefined) {
this._lastAuthState = isAuthed;
} else if (this._lastAuthState !== isAuthed) {
this._lastAuthState = isAuthed;
if (this._view) {
// Send auth state update to webview for immediate UI response
this._view.webview.postMessage({
command: 'updateAuthState',
authenticated: isAuthed
});
// Rebuild HTML to update Home tab login status
this._view.webview.html = await this._getHtmlForWebview(this._view.webview);
}
}
} catch {
// ignore transient errors
}
}, 2000);
}
/** Stops monitoring auth state */
private stopAuthMonitor() {
if (this._authMonitorInterval) {
clearInterval(this._authMonitorInterval);
this._authMonitorInterval = undefined;
}
}
/**
* Updates team activity information (delegated to Live Share manager).
*
* @param activity - The activity data to update
*/
public updateTeamActivity(activity: any) {
this._liveShareManager.updateTeamActivity(activity);
}
/**
* Disposes of the panel provider and cleans up resources.
* Stops monitoring intervals and clears references to sub-panels.
*/
dispose() {
this._liveShareManager.dispose();
// AgentPanel doesn't have dispose method yet
// if (this._agentPanel.dispose) this._agentPanel.dispose();
this.stopAuthMonitor();
this._view = undefined;
}
/**
* Generates the HTML content for the webview panel.
*
* @param webview - The webview instance for generating resource URIs
* @returns The complete HTML string for the panel
*/
private _getHtmlForWebview(webview: vscode.Webview) {
// Build HTML from external template and dynamic sections
return (async () => {
// Dynamically check Live Share install status
let liveShareInstalled = false;
try {
liveShareInstalled = !!vscode.extensions.getExtension('ms-vsliveshare.vsliveshare');
} catch {}
// Dynamically check login status
let loggedIn = false;
let userInfo = undefined;
try {
const result = await getAuthContext();
if (result && result.context && result.context.isAuthenticated) {
loggedIn = true;
userInfo = { email: result.context.email, username: result.context.first_name };
}
} catch {}
// Get HTML content from sub-panels
const homeHtml = await this._homeScreen.getHtml(webview, liveShareInstalled, loggedIn, userInfo);
const agentHtml = this._agentPanel.getInnerHtml();
const tasksHtml = this._tasksPanel.getHtml();
const profileHtml = await this._profilePanel.getHtml(webview);
// Get Live Share panel content
const fs = require('fs');
const liveShareContentPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'liveSharePanel.html').fsPath;
let liveShareHtml = '';
try {
liveShareHtml = fs.readFileSync(liveShareContentPath, 'utf8');
} catch (e) {
console.warn('Failed to read liveSharePanel.html:', e);
liveShareHtml = '<div>Failed to load Live Share panel.</div>';
}
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'liveSharePanel.js'));
const tasksScriptUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'tasksPanel.js'));
const mainStyleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'mainPanel.css'));
const liveShareStyleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'liveSharePanel.css'));
const agentStyleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'agentPanel.css'));
const tasksStyleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'tasksPanel.css'));
const profileStyleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, 'media', 'profilePanel.css'));
const nonce = Date.now().toString();
// Load main panel template
const templatePath = vscode.Uri.joinPath(this._extensionUri, 'media', 'mainPanel.html').fsPath;
let template = '';
try {
template = fs.readFileSync(templatePath, 'utf8');
} catch (e) {
console.warn('Failed to read liveSharePanel.html, falling back to inline HTML:', e);
return `<html><body>Failed to load template.</body></html>`;
}
const html = template
.replace('{{MAIN_STYLE_URI}}', mainStyleUri.toString())
.replace('{{LIVESHARE_STYLE_URI}}', liveShareStyleUri.toString())
.replace('{{AGENT_STYLE_URI}}', agentStyleUri.toString())
.replace('{{TASKS_STYLE_URI}}', tasksStyleUri.toString())
.replace('{{PROFILE_STYLE_URI}}', profileStyleUri.toString())
.replace('{{SCRIPT_URI}}', scriptUri.toString())
.replace('{{TASKS_SCRIPT_URI}}', tasksScriptUri.toString())
.replace(/\{\{NONCE\}\}/g, nonce)
.replace('{{IS_AUTHENTICATED}}', loggedIn.toString())
.replace('{{LIVESHARE_INSTALLED}}', liveShareInstalled.toString())
.replace('{{HOME_HTML}}', homeHtml)
.replace('{{LIVESHARE_HTML}}', liveShareHtml)
.replace('{{AGENT_HTML}}', agentHtml)
.replace('{{TASKS_HTML}}', tasksHtml)
.replace('{{PROFILE_HTML}}', profileHtml);
return html;
})();
}
}
|