-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.ts
More file actions
1653 lines (1424 loc) · 64.2 KB
/
extension.ts
File metadata and controls
1653 lines (1424 loc) · 64.2 KB
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
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import { IconGenerator } from './utils/IconGenerator';
import { execAsync, GitCancelledError } from './utils/exec';
import { errorCatalog } from './exceptions/ErrorCatalog';
import { clientErrorCatalog } from './exceptions/ClientErrorCatalog';
import { ErrorPageWebviewProvider } from './ui/webviews/ErrorPageWebviewProvider';
import { ComputorSettingsManager } from './settings/ComputorSettingsManager';
import { ComputorApiService } from './services/ComputorApiService';
// GitLabTokenManager is dynamically imported in code blocks below
// import { GitLabTokenManager } from './services/GitLabTokenManager';
import { BearerTokenHttpClient } from './http/BearerTokenHttpClient';
import { ApiKeyHttpClient } from './http/ApiKeyHttpClient';
import { WebSocketService } from './services/WebSocketService';
import { BackendConnectionService } from './services/BackendConnectionService';
import { GitEnvironmentService } from './services/GitEnvironmentService';
import { ExtensionUpdateService } from './services/ExtensionUpdateService';
import { LecturerTreeDataProvider } from './ui/tree/lecturer/LecturerTreeDataProvider';
import { LecturerExampleTreeProvider } from './ui/tree/lecturer/LecturerExampleTreeProvider';
import { LecturerCommands } from './commands/LecturerCommands';
import { LecturerExampleCommands } from './commands/LecturerExampleCommands';
import { LecturerFsCommands } from './commands/LecturerFsCommands';
import { UserPasswordCommands } from './commands/UserPasswordCommands';
import { SignUpCommands } from './commands/SignUpCommands';
import { SettingsCommands } from './commands/SettingsCommands';
import { LogoutCommands } from './commands/LogoutCommands';
import { UserProfileWebviewProvider } from './ui/webviews/UserProfileWebviewProvider';
import { StudentCourseContentTreeProvider } from './ui/tree/student/StudentCourseContentTreeProvider';
import { StudentRepositoryManager } from './services/StudentRepositoryManager';
import { CourseSelectionService } from './services/CourseSelectionService';
import { StudentCommands } from './commands/StudentCommands';
import { TutorCommands } from './commands/TutorCommands';
import { TestResultsPanelProvider, TestResultsTreeDataProvider } from './ui/panels/TestResultsPanel';
import { TestResultService } from './services/TestResultService';
import { MessagesInputPanelProvider } from './ui/panels/MessagesInputPanel';
import { manageGitLabTokens } from './commands/manageGitLabTokens';
import { configureGit } from './commands/configureGit';
import { showGettingStarted } from './commands/showGettingStarted';
import { LoginWebviewProvider } from './ui/webviews/LoginWebviewProvider';
interface StoredAuth {
accessToken: string;
refreshToken?: string;
expiresAt?: string;
issuedAt?: string;
userId?: string;
}
const computorMarker = '.computor';
function getWorkspaceRoot(): string | undefined {
const ws = vscode.workspace.workspaceFolders;
if (!ws || ws.length === 0) return undefined;
return ws[0]?.uri.fsPath;
}
async function ensureBaseUrl(settings: ComputorSettingsManager): Promise<string | undefined> {
const current = await settings.getBaseUrl();
if (current) return current;
const url = await vscode.window.showInputBox({
title: 'Computor Backend URL',
prompt: 'Enter the Computor backend URL',
placeHolder: 'http://localhost:8000',
ignoreFocusOut: true,
validateInput: (value) => {
try { new URL(value); return undefined; } catch { return 'Enter a valid URL'; }
}
});
if (!url) return undefined;
await settings.setBaseUrl(url);
return url;
}
async function attemptSilentAutoLogin(
context: vscode.ExtensionContext,
baseUrl: string,
username: string,
password: string,
onProgress?: (message: string) => void
): Promise<boolean> {
try {
const client = new BearerTokenHttpClient(baseUrl, 5000);
await client.authenticateWithCredentials(username, password);
const tokenData = client.getTokenData();
const auth: StoredAuth = {
accessToken: tokenData.accessToken!,
refreshToken: tokenData.refreshToken || undefined,
expiresAt: tokenData.expiresAt?.toISOString(),
issuedAt: tokenData.issuedAt?.toISOString(),
userId: tokenData.userId || undefined
};
await ensureWorkspaceMarker(baseUrl);
const controller = new UnifiedController(context);
await controller.activate(client as any, onProgress);
backendConnectionService.startHealthCheck(baseUrl);
activeSession = {
deactivate: () => controller.dispose().then(async () => {
await vscode.commands.executeCommand('setContext', 'computor.lecturer.show', false);
await vscode.commands.executeCommand('setContext', 'computor.student.show', false);
await vscode.commands.executeCommand('setContext', 'computor.tutor.show', false);
await context.globalState.update('computor.tutor.selection', undefined);
backendConnectionService.stopHealthCheck();
}),
getActiveViews: () => controller.getActiveViews(),
getHttpClient: () => controller.getHttpClient()
};
await context.secrets.store('computor.auth', JSON.stringify(auth));
if (extensionUpdateService) {
extensionUpdateService.checkForUpdates().catch(err => {
console.warn('Extension update check failed:', err);
});
}
return true;
} catch (error: any) {
console.error('Auto-login failed:', error);
return false;
}
}
// Login webview provider instance (lazily initialized per context)
let loginWebviewProvider: LoginWebviewProvider | undefined;
function buildHttpClient(baseUrl: string, auth: StoredAuth): BearerTokenHttpClient {
const client = new BearerTokenHttpClient(baseUrl, 5000);
client.setTokenData({
accessToken: auth.accessToken,
refreshToken: auth.refreshToken,
expiresAt: auth.expiresAt ? new Date(auth.expiresAt) : undefined,
issuedAt: auth.issuedAt ? new Date(auth.issuedAt) : undefined,
userId: auth.userId
});
return client;
}
async function readMarker(file: string): Promise<{ backendUrl?: string; courseId?: string } | undefined> {
try {
if (!fs.existsSync(file)) return undefined;
const raw = await fs.promises.readFile(file, 'utf8');
return JSON.parse(raw);
} catch {
return undefined;
}
}
async function writeMarker(file: string, data: { backendUrl: string }): Promise<void> {
await fs.promises.writeFile(file, JSON.stringify(data, null, 2), 'utf8');
}
/**
* Result of auto-login attempt
*/
interface AutoLoginResult {
success: boolean;
shouldPromptManualLogin: boolean;
}
/**
* Handles automatic login when .computor file is detected in workspace.
* Consolidates duplicated auto-login logic from activation and workspace change handlers.
*/
/**
* Attempt login using a pre-minted API token from the COMPUTOR_AUTH_TOKEN env var.
* Returns true if successful, false otherwise.
*/
async function attemptApiTokenLogin(
context: vscode.ExtensionContext,
baseUrl: string,
apiToken: string,
onProgress?: (message: string) => void
): Promise<boolean> {
try {
const client = new ApiKeyHttpClient(baseUrl, apiToken, 'X-API-Token', '', 5000);
await ensureWorkspaceMarker(baseUrl);
const controller = new UnifiedController(context);
await controller.activate(client as any, onProgress);
backendConnectionService.startHealthCheck(baseUrl);
activeSession = {
deactivate: () => controller.dispose().then(async () => {
await vscode.commands.executeCommand('setContext', 'computor.lecturer.show', false);
await vscode.commands.executeCommand('setContext', 'computor.student.show', false);
await vscode.commands.executeCommand('setContext', 'computor.tutor.show', false);
await context.globalState.update('computor.tutor.selection', undefined);
backendConnectionService.stopHealthCheck();
}),
getActiveViews: () => controller.getActiveViews(),
getHttpClient: () => controller.getHttpClient()
};
if (extensionUpdateService) {
extensionUpdateService.checkForUpdates().catch(err => {
console.warn('Extension update check failed:', err);
});
}
return true;
} catch (error: any) {
console.error('API token login failed:', error);
return false;
}
}
async function handleComputorWorkspaceDetected(
context: vscode.ExtensionContext,
computorMarkerPath: string
): Promise<void> {
if (activeSession || isAuthenticating) {
return;
}
const settings = new ComputorSettingsManager(context);
// Priority 1: Try API token from environment variable (Coder workspace injection)
const apiToken = process.env.COMPUTOR_AUTH_TOKEN;
if (apiToken) {
const marker = await readMarker(computorMarkerPath);
const baseUrl = marker?.backendUrl || await settings.getBaseUrl();
if (baseUrl) {
const success = await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Computor',
cancellable: false
}, async (progress) => {
progress.report({ message: 'Connecting (workspace token)...' });
backendConnectionService.setBaseUrl(baseUrl);
const status = await backendConnectionService.checkBackendConnection(baseUrl);
if (!status.isReachable) {
return false;
}
progress.report({ message: 'Authenticating...' });
return await attemptApiTokenLogin(
context, baseUrl, apiToken,
(msg) => progress.report({ message: msg })
);
});
if (success) {
vscode.window.showInformationMessage(`Logged in (workspace token): ${baseUrl}`);
return;
}
console.warn('API token login failed, falling back to credential-based login');
}
}
// Priority 2: Stored credentials auto-login (existing flow)
const autoLoginEnabled = await settings.isAutoLoginEnabled();
const storedUsername = await context.secrets.get('computor.username');
const storedPassword = await context.secrets.get('computor.password');
if (autoLoginEnabled && storedUsername && storedPassword) {
const result = await performAutoLogin(context, computorMarkerPath, storedUsername, storedPassword);
if (!result.success && result.shouldPromptManualLogin) {
const action = await vscode.window.showWarningMessage(
'Auto-login failed. Would you like to login manually?',
'Login',
'Not Now'
);
if (action === 'Login') {
await unifiedLoginFlow(context);
}
}
} else if (autoLoginEnabled === false) {
// Auto-login is explicitly disabled - show prompt
const action = await vscode.window.showInformationMessage(
'Computor workspace detected. Would you like to login?',
'Login',
'Not Now'
);
if (action === 'Login') {
await unifiedLoginFlow(context);
}
}
// If autoLogin is true but no credentials are stored, do nothing (silent)
}
/**
* Performs the actual auto-login attempt with a single unified progress notification.
*/
async function performAutoLogin(
context: vscode.ExtensionContext,
computorMarkerPath: string,
username: string,
password: string
): Promise<AutoLoginResult> {
let loginFailed = false;
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Computor',
cancellable: false
}, async (progress) => {
try {
progress.report({ message: 'Connecting to backend...' });
const settings = new ComputorSettingsManager(context);
const marker = await readMarker(computorMarkerPath);
const baseUrl = marker?.backendUrl || await settings.getBaseUrl();
if (!baseUrl) {
loginFailed = true;
return;
}
backendConnectionService.setBaseUrl(baseUrl);
const connectionStatus = await backendConnectionService.checkBackendConnection(baseUrl);
if (!connectionStatus.isReachable) {
await backendConnectionService.showConnectionError(connectionStatus);
loginFailed = true;
return;
}
progress.report({ message: 'Authenticating...' });
const success = await attemptSilentAutoLogin(
context,
baseUrl,
username,
password,
(msg) => progress.report({ message: msg })
);
if (success) {
vscode.window.showInformationMessage(`Logged in: ${baseUrl}`);
} else {
loginFailed = true;
}
} catch (error: any) {
console.warn('Auto-login failed:', error);
loginFailed = true;
}
});
return {
success: !loginFailed,
shouldPromptManualLogin: loginFailed
};
}
async function ensureWorkspaceMarker(baseUrl: string): Promise<void> {
const root = getWorkspaceRoot();
if (!root) {
const action = await vscode.window.showErrorMessage('Login requires an open workspace.', 'Open Folder');
if (action === 'Open Folder') {
// Let the user select a folder to open as workspace
const folderUri = await vscode.window.showOpenDialog({
canSelectFolders: true,
canSelectFiles: false,
canSelectMany: false,
openLabel: 'Select Workspace Folder'
});
if (folderUri && folderUri.length > 0) {
// No longer storing pending login - will auto-detect .computor file instead
// Add the folder to the current workspace
// This will restart the extension if no workspace was open
const workspaceFolders = vscode.workspace.workspaceFolders || [];
vscode.workspace.updateWorkspaceFolders(
workspaceFolders.length,
0,
{ uri: folderUri[0]!, name: path.basename(folderUri[0]!.fsPath) }
);
// If we had existing workspace folders, the extension won't restart
// In that case, we can continue immediately
if (workspaceFolders.length > 0) {
// Give VS Code a moment to update
await new Promise(resolve => setTimeout(resolve, 100));
// Recursively call to handle the marker with the new workspace
await ensureWorkspaceMarker(baseUrl);
return;
}
// Extension will restart
return;
}
}
return;
}
const file = path.join(root, computorMarker);
const existing = await readMarker(file);
// Update marker with backend URL if different or missing
if (!existing || existing.backendUrl !== baseUrl) {
await writeMarker(file, { backendUrl: baseUrl });
}
}
class UnifiedController {
private context: vscode.ExtensionContext;
private api?: ComputorApiService;
private httpClient?: BearerTokenHttpClient;
private disposables: vscode.Disposable[] = [];
private activeViews: string[] = [];
private profileWebviewProvider?: UserProfileWebviewProvider;
private messagesInputPanel?: MessagesInputPanelProvider;
private wsService?: WebSocketService;
constructor(context: vscode.ExtensionContext) {
this.context = context;
}
async activate(
client: ReturnType<typeof buildHttpClient>,
onProgress?: (message: string) => void
): Promise<void> {
const report = onProgress || (() => {});
this.httpClient = client;
const api = await this.setupApi(client);
this.profileWebviewProvider = new UserProfileWebviewProvider(this.context, api);
const profileCommand = vscode.commands.registerCommand('computor.user.profile', async () => {
if (!this.profileWebviewProvider) {
this.profileWebviewProvider = new UserProfileWebviewProvider(this.context, api);
} else {
this.profileWebviewProvider.setApiService(api);
}
await this.profileWebviewProvider.open();
});
this.disposables.push(profileCommand);
// Messages input panel (shared across all views)
this.messagesInputPanel = new MessagesInputPanelProvider(this.context.extensionUri, api);
this.disposables.push(
vscode.window.registerWebviewViewProvider(MessagesInputPanelProvider.viewType, this.messagesInputPanel)
);
// Initialize WebSocket service for real-time messaging
const settingsManager = new ComputorSettingsManager(this.context);
this.wsService = WebSocketService.getInstance(settingsManager);
this.wsService.setHttpClient(client);
this.messagesInputPanel.setWebSocketService(this.wsService);
// Connect WebSocket (fire-and-forget, will reconnect automatically on failure)
void this.wsService.connect();
// Check initial maintenance status (fire-and-forget)
void this.checkInitialMaintenanceStatus(api);
// Register WebSocket reconnect command
this.disposables.push(
vscode.commands.registerCommand('computor.websocket.reconnect', async () => {
if (this.wsService) {
await this.wsService.reconnect();
}
})
);
// Get available views for this user across all courses
// This is a lightweight check to determine which role views to show
report('Loading user views...');
const availableViews = await this.getAvailableViews(api);
if (availableViews.length === 0) {
throw new Error('No views available for your account.');
}
report('Validating Git environment...');
await GitEnvironmentService.getInstance().validateGitEnvironment();
// Validate and register course provider accounts BEFORE initializing views
// This ensures tokens are ready before ANY git operations
report('Validating course access...');
await this.validateCourseProviderAccess(api, onProgress);
// NOW initialize views - git operations will work because tokens are validated
report('Initializing views...');
await this.initializeViews(api, null, availableViews, onProgress);
// Focus on the highest priority view: lecturer > tutor > student
await this.focusHighestPriorityView(availableViews);
}
private async setupApi(client: ReturnType<typeof buildHttpClient>): Promise<ComputorApiService> {
const api = new ComputorApiService(this.context, client);
this.api = api;
// API service is now available via ComputorApiService.getInstance()
return api;
}
private async getAvailableViews(api: ComputorApiService): Promise<string[]> {
return await api.getUserViews();
}
private async validateCourseProviderAccess(
api: ComputorApiService,
onProgress?: (message: string) => void
): Promise<void> {
try {
const { CourseProviderValidationService } = await import('./services/CourseProviderValidationService');
const validationService = new CourseProviderValidationService(this.context, api);
await validationService.validateAllCourseProviders(onProgress);
console.log('[UnifiedController] Course provider validation complete');
} catch (error) {
console.warn('[UnifiedController] Failed to validate course provider access:', error);
}
}
private async initializeViews(
api: ComputorApiService,
courseId: string | null,
views: string[],
onProgress?: (message: string) => void
): Promise<void> {
void courseId; // No longer used - views show all courses
const report = onProgress || (() => {});
// Store the active views
this.activeViews = views;
// Initialize ALL available views - each will get its own activity bar container
// Each view will fetch and display all available courses
if (views.includes('student')) {
report('Setting up student view...');
await this.initializeStudentView(api, onProgress);
await vscode.commands.executeCommand('setContext', 'computor.student.show', true);
}
if (views.includes('tutor')) {
report('Setting up tutor view...');
await this.initializeTutorView(api);
await vscode.commands.executeCommand('setContext', 'computor.tutor.show', true);
}
if (views.includes('lecturer')) {
report('Setting up lecturer view...');
await this.initializeLecturerView(api);
await vscode.commands.executeCommand('setContext', 'computor.lecturer.show', true);
}
if (views.includes('user_manager')) {
report('Setting up user manager view...');
await this.initializeUserManagerView(api);
await vscode.commands.executeCommand('setContext', 'computor.user_manager.show', true);
}
// Set context keys for views that are NOT available to false
if (!views.includes('student')) {
await vscode.commands.executeCommand('setContext', 'computor.student.show', false);
}
if (!views.includes('tutor')) {
await vscode.commands.executeCommand('setContext', 'computor.tutor.show', false);
}
if (!views.includes('lecturer')) {
await vscode.commands.executeCommand('setContext', 'computor.lecturer.show', false);
}
if (!views.includes('user_manager')) {
await vscode.commands.executeCommand('setContext', 'computor.user_manager.show', false);
}
}
private async focusHighestPriorityView(views: string[]): Promise<void> {
// Priority: lecturer > tutor > student
let viewToFocus: string | null = null;
let commandToRun: string | null = null;
if (views.includes('lecturer')) {
viewToFocus = 'lecturer';
commandToRun = 'workbench.view.extension.computor-lecturer';
} else if (views.includes('tutor')) {
viewToFocus = 'tutor';
commandToRun = 'workbench.view.extension.computor-tutor';
} else if (views.includes('student')) {
viewToFocus = 'student';
commandToRun = 'workbench.view.extension.computor-student';
}
if (commandToRun) {
try {
await vscode.commands.executeCommand(commandToRun);
console.log(`Focused on ${viewToFocus} view after login`);
} catch (err) {
console.warn(`Failed to focus on ${viewToFocus} view:`, err);
}
}
}
private async initializeStudentView(
api: ComputorApiService,
onProgress?: (message: string) => void
): Promise<void> {
const report = onProgress || (() => {});
// Initialize student-specific components
const repositoryManager = new StudentRepositoryManager(this.context, api);
// Wire error page for corrupt git index detection
const errorPageProvider = new ErrorPageWebviewProvider(this.context);
errorPageProvider.registerActionHandler('REBUILD_INDEX', async (_errorCode, ctx) => {
if (!ctx?.repositoryPath) { return; }
try {
const indexPath = path.join(ctx.repositoryPath, '.git', 'index');
if (fs.existsSync(indexPath)) {
await fs.promises.unlink(indexPath);
}
await execAsync('git reset', { cwd: ctx.repositoryPath });
vscode.window.showInformationMessage('Git index rebuilt successfully. Please reload the window.', 'Reload Window').then(choice => {
if (choice === 'Reload Window') {
void vscode.commands.executeCommand('workbench.action.reloadWindow');
}
});
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
vscode.window.showErrorMessage(`Failed to rebuild git index: ${message}`);
}
});
errorPageProvider.registerActionHandler('OPEN_TERMINAL', async (_errorCode, ctx) => {
if (!ctx?.repositoryPath) { return; }
const terminal = vscode.window.createTerminal({ name: 'Repository', cwd: ctx.repositoryPath });
terminal.show();
});
repositoryManager.setCorruptIndexHandler((repoPath: string) => {
void errorPageProvider.showError('GIT_INDEX_CORRUPT', { repositoryPath: repoPath });
});
const statusBar = (await import('./ui/StatusBarService')).StatusBarService.initialize(this.context);
const courseSelectionService = CourseSelectionService.initialize(this.context, api, statusBar);
// Initialize tree view
const tree = new StudentCourseContentTreeProvider(api, courseSelectionService, repositoryManager, this.context);
if (this.wsService) tree.setWebSocketService(this.wsService);
this.disposables.push(vscode.window.registerTreeDataProvider('computor.student.courses', tree));
const treeView = vscode.window.createTreeView('computor.student.courses', { treeDataProvider: tree, showCollapseAll: true });
this.disposables.push(treeView);
const studentExpandListener = treeView.onDidExpandElement((event) => {
const element = event.element;
if (!element) return;
void tree.onTreeItemExpanded(element);
});
const studentCollapseListener = treeView.onDidCollapseElement((event) => {
const element = event.element;
if (!element) return;
void tree.onTreeItemCollapsed(element);
});
const studentSelectionListener = treeView.onDidChangeSelection((event) => {
const selected = event.selection[0];
if (!selected) return;
// Show test results automatically when an assignment is selected
if (selected.contextValue?.startsWith('studentCourseContent.assignment')) {
if ((selected as any).courseContent?.result) {
void vscode.commands.executeCommand('computor.showTestResults', selected);
} else {
// Clear results view when selecting an assignment without results
void vscode.commands.executeCommand('computor.results.clear');
}
}
});
const studentVisibilityListener = treeView.onDidChangeVisibility((event) => {
if (event.visible) {
// Clear results view when switching to student view
void vscode.commands.executeCommand('computor.results.clear');
}
});
this.disposables.push(studentExpandListener, studentCollapseListener, studentSelectionListener, studentVisibilityListener);
// No course pre-selection - tree will show all courses
// Load expanded states to determine which courses need immediate update
// Only previously expanded courses will have their repositories updated on startup
const settingsManager = new ComputorSettingsManager(this.context);
const expandedStates = await settingsManager.getStudentTreeExpandedStates();
// Extract course IDs from expanded states (format: "course-{courseId}")
const expandedCourseIds = new Set<string>();
for (const nodeId of Object.keys(expandedStates)) {
if (nodeId.startsWith('course-') && expandedStates[nodeId]) {
expandedCourseIds.add(nodeId.replace('course-', ''));
}
}
console.log(`[initializeStudentView] Expanded courses for startup update: ${Array.from(expandedCourseIds).join(', ') || '(none)'}`);
// Auto-setup repositories only for expanded courses (tokens already validated before this runs)
// Courses that were never expanded will be set up lazily when first expanded
if (expandedCourseIds.size > 0) {
// Use external progress if available, otherwise show own popup
const setupRepositories = async (progressReport: (msg: string) => void, cancellationToken?: vscode.CancellationToken) => {
progressReport('Preparing repositories...');
try {
await repositoryManager.autoSetupRepositories(undefined, progressReport, expandedCourseIds, cancellationToken);
} catch (e) {
if (e instanceof GitCancelledError) {
vscode.window.showInformationMessage('Repository setup was cancelled. Repositories will be set up when you expand a course.');
} else {
console.error('[initializeStudentView] Repository auto-setup failed:', e);
}
}
tree.refresh();
};
if (onProgress) {
await setupRepositories(report);
} else {
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Preparing course repositories...',
cancellable: true
}, async (progress, token) => {
await setupRepositories((msg) => progress.report({ message: msg }), token);
});
}
} else {
console.log('[initializeStudentView] No expanded courses, skipping initial repository setup');
}
// Student commands
const commands = new StudentCommands(this.context, tree, api, repositoryManager, this.messagesInputPanel, this.wsService);
commands.registerCommands();
// Results panel + tree
const panelProvider = new TestResultsPanelProvider(this.context.extensionUri);
this.disposables.push(vscode.window.registerWebviewViewProvider(TestResultsPanelProvider.viewType, panelProvider));
const resultsTree = new TestResultsTreeDataProvider([]);
resultsTree.setPanelProvider(panelProvider);
this.disposables.push(vscode.window.registerTreeDataProvider('computor.testResultsView', resultsTree));
TestResultService.getInstance().setApiService(api);
this.disposables.push(vscode.commands.registerCommand('computor.results.open', async (results: any, resultId?: string, artifacts?: any[]) => {
try {
if (resultId && artifacts && artifacts.length > 0) {
resultsTree.setResultArtifacts(resultId, artifacts);
} else {
resultsTree.clearResultArtifacts();
}
resultsTree.refresh(results || {});
await vscode.commands.executeCommand('computor.testResultsPanel.focus');
} catch (e) { console.error(e); }
}));
this.disposables.push(vscode.commands.registerCommand('computor.results.panel.update', (item: any) => {
resultsTree.setSelectedNodeId(item.id);
panelProvider.updateTestResults(item);
}));
this.disposables.push(vscode.commands.registerCommand('computor.results.clear', () => {
resultsTree.clearResultArtifacts();
resultsTree.refresh({});
panelProvider.clearResults();
}));
this.disposables.push(vscode.commands.registerCommand('computor.results.artifact.open', async (resultId: string, artifactInfo: any) => {
try {
await this.openResultArtifact(api, resultId, artifactInfo);
} catch (e) {
console.error('Failed to open artifact:', e);
vscode.window.showErrorMessage(`Failed to open artifact: ${e instanceof Error ? e.message : String(e)}`);
}
}));
}
private async openResultArtifact(api: ComputorApiService, resultId: string, artifactInfo: any): Promise<void> {
const fs = await import('fs');
const path = await import('path');
// Local artifacts from lecturer example testing: resultId is "local:<outputDir>"
if (resultId.startsWith('local:')) {
const outputDir = resultId.substring('local:'.length);
const filePath = path.join(outputDir, artifactInfo.filename);
if (fs.existsSync(filePath)) {
await this.openArtifactFile(filePath);
} else {
vscode.window.showErrorMessage(`Local artifact not found: ${artifactInfo.filename}`);
}
return;
}
const { WorkspaceStructureManager } = await import('./utils/workspaceStructure');
const JSZip = (await import('jszip')).default;
const wsManager = WorkspaceStructureManager.getInstance();
const artifactsDir = wsManager.getResultArtifactsPath(resultId);
const artifactFilePath = path.join(artifactsDir, artifactInfo.filename);
const artifactExists = await wsManager.resultArtifactsExist(resultId);
const fileExists = artifactExists && fs.existsSync(artifactFilePath);
if (fileExists) {
await this.openArtifactFile(artifactFilePath);
return;
}
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `Downloading artifact: ${artifactInfo.filename}`,
cancellable: false
}, async () => {
const buffer = await api.downloadResultArtifacts(resultId);
if (!buffer) {
throw new Error('Failed to download artifacts');
}
await fs.promises.mkdir(artifactsDir, { recursive: true });
const zip = await JSZip.loadAsync(buffer);
for (const [filename, zipEntry] of Object.entries(zip.files)) {
if (!zipEntry.dir) {
const content = await zipEntry.async('nodebuffer');
const filePath = path.join(artifactsDir, filename);
const fileDir = path.dirname(filePath);
await fs.promises.mkdir(fileDir, { recursive: true });
await fs.promises.writeFile(filePath, content);
}
}
});
if (fs.existsSync(artifactFilePath)) {
await this.openArtifactFile(artifactFilePath);
} else {
const files = await wsManager.getResultArtifactFiles(resultId);
if (files.length > 0) {
const firstFile = path.join(artifactsDir, files[0]!);
await this.openArtifactFile(firstFile);
} else {
vscode.window.showInformationMessage('Artifacts downloaded but no files found to open');
}
}
}
private async openArtifactFile(filePath: string): Promise<void> {
const fileUri = vscode.Uri.file(filePath);
const ext = filePath.toLowerCase().split('.').pop() || '';
const imageExtensions = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg', 'ico'];
const binaryExtensions = ['pdf', 'zip', 'tar', 'gz', 'rar', '7z', 'exe', 'dll', 'so', 'dylib', 'bin', 'dat'];
if (imageExtensions.includes(ext)) {
await vscode.commands.executeCommand('vscode.open', fileUri, { preview: false });
} else if (binaryExtensions.includes(ext)) {
await vscode.commands.executeCommand('revealFileInOS', fileUri);
vscode.window.showInformationMessage(`Binary file revealed in file explorer: ${filePath.split('/').pop()}`);
} else {
const doc = await vscode.workspace.openTextDocument(fileUri);
await vscode.window.showTextDocument(doc, { preview: false });
}
}
private async initializeTutorView(api: ComputorApiService): Promise<void> {
const { TutorFilterTreeProvider } = await import('./ui/tree/tutor/tutor-filter-tree-provider');
const { TutorCourseFilterItem, TutorGroupOptionItem, TutorMemberFilterItem, NO_GROUP_SENTINEL, formatMemberName } = await import('./ui/tree/tutor/tutor-filter-tree-items');
const { TutorSelectionService } = await import('./services/TutorSelectionService');
const { TutorStatusBarService } = await import('./ui/TutorStatusBarService');
const { TutorEditorDecorationService } = await import('./providers/TutorEditorDecorationService');
const selection = TutorSelectionService.initialize(this.context, api);
const editorDecorationService = TutorEditorDecorationService.initialize(this.context);
editorDecorationService.connectToSelectionService(selection);
// Register filter tree (replaces webview filter panel)
const filterTree = new TutorFilterTreeProvider(api, selection);
const filterTreeView = vscode.window.createTreeView('computor.tutor.filters', {
treeDataProvider: filterTree,
showCollapseAll: true
});
this.disposables.push(filterTreeView);
// Select course when expanding a course node
this.disposables.push(filterTreeView.onDidExpandElement(async (event) => {
if (event.element instanceof TutorCourseFilterItem) {
const course = event.element.course;
const currentCourseId = selection.getCurrentCourseId();
if (currentCourseId !== course.id) {
await selection.selectCourse(course.id, course.title || course.path || course.name || course.id);
filterTree.refresh();
}
}
}));
// Register filter interaction commands
this.disposables.push(vscode.commands.registerCommand('computor.tutor.selectGroup', async (item: InstanceType<typeof TutorGroupOptionItem>) => {
if (item.isNoGroup) {
await selection.selectGroup(NO_GROUP_SENTINEL, 'No Group');
} else {
await selection.selectGroup(item.groupId, item.groupLabel);
}
filterTree.refresh();
}));
this.disposables.push(vscode.commands.registerCommand('computor.tutor.selectMember', async (item: InstanceType<typeof TutorMemberFilterItem>) => {
const name = formatMemberName(item.member);
const memberGroupId = item.member.course_group_id ?? null;
const memberGroupLabel = memberGroupId
? filterTree.resolveGroupLabel(item.courseId, memberGroupId)
: null;
await selection.selectMember(item.member.id, name, memberGroupId, memberGroupLabel, item.member.user?.email, item.member.user?.username);
filterTree.refresh();
}));
// Register course content tree
const { TutorStudentTreeProvider } = await import('./ui/tree/tutor/TutorStudentTreeProvider');
const tree = new TutorStudentTreeProvider(api, selection);
if (this.wsService) tree.setWebSocketService(this.wsService);
this.disposables.push(vscode.window.registerTreeDataProvider('computor.tutor.courses', tree));
const treeView = vscode.window.createTreeView('computor.tutor.courses', { treeDataProvider: tree, showCollapseAll: true });
this.disposables.push(treeView);
const tutorCollapseListener = treeView.onDidCollapseElement((event) => {
tree.handleCollapse(event.element);
});
this.disposables.push(tutorCollapseListener);
const tutorSelectionListener = treeView.onDidChangeSelection((event) => {
const selected = event.selection[0];
if (!selected) return;
if (selected.contextValue?.startsWith('tutorStudentContent.assignment')) {
void vscode.commands.executeCommand('computor.tutor.checkout', selected, false);
if ((selected as any).content?.result) {
void vscode.commands.executeCommand('computor.showTestResults', { courseContent: (selected as any).content });
} else {
void vscode.commands.executeCommand('computor.results.clear');
}
}
});
const tutorVisibilityListener = treeView.onDidChangeVisibility((event) => {
if (event.visible) {
void vscode.commands.executeCommand('computor.results.clear');
}
});
this.disposables.push(tutorSelectionListener, tutorVisibilityListener);
// Status bar
const tutorStatus = TutorStatusBarService.initialize();
const updateStatus = async () => {
const courseLabel = selection.getCurrentCourseLabel() || selection.getCurrentCourseId();
const groupLabel = selection.getCurrentGroupLabel() || selection.getCurrentGroupId();
const memberLabel = selection.getCurrentMemberLabel() || selection.getCurrentMemberId();
tutorStatus.updateSelection(courseLabel, groupLabel, memberLabel);
};
this.disposables.push(selection.onDidChangeSelection(() => {
void updateStatus();
void vscode.commands.executeCommand('computor.results.clear');
}));
void updateStatus();
// Reset filters command
this.disposables.push(vscode.commands.registerCommand('computor.tutor.resetFilters', async () => {
const id = selection.getCurrentCourseId();
if (!id) {
return;
}
const label = selection.getCurrentCourseLabel();
await selection.selectCourse(id, label);
filterTree.refresh();
}));
const commands = new TutorCommands(this.context, tree, api, filterTree, this.messagesInputPanel, this.wsService);
commands.registerCommands();
}
private async initializeLecturerView(api: ComputorApiService): Promise<void> {
const tree = new LecturerTreeDataProvider(this.context, api);
if (this.wsService) tree.setWebSocketService(this.wsService);
this.disposables.push(vscode.window.registerTreeDataProvider('computor.lecturer.courses', tree));
const treeView = vscode.window.createTreeView('computor.lecturer.courses', {
treeDataProvider: tree,
showCollapseAll: true,
canSelectMany: false,
dragAndDropController: tree
});
this.disposables.push(treeView);
const lecturerExpandListener = treeView.onDidExpandElement((event) => {
const elementId = event.element?.id;
if (!elementId) return;
void tree.setNodeExpanded(elementId, true);
});
const lecturerCollapseListener = treeView.onDidCollapseElement((event) => {
const elementId = event.element?.id;
if (!elementId) return;
void tree.setNodeExpanded(elementId, false);
});
const lecturerVisibilityListener = treeView.onDidChangeVisibility((event) => {
if (event.visible) {
// Clear results view when switching to lecturer view
void vscode.commands.executeCommand('computor.results.clear');
}
});
this.disposables.push(lecturerExpandListener, lecturerCollapseListener, lecturerVisibilityListener);
const exampleTree = new LecturerExampleTreeProvider(this.context, api);
const exampleTreeView = vscode.window.createTreeView('computor.lecturer.examples', {
treeDataProvider: exampleTree,