@milabench/bujang 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +108 -2
  2. package/dist/api.d.ts +151 -0
  3. package/dist/components/AutocompleteInput.d.ts +15 -0
  4. package/dist/components/MonacoEditor.d.ts +11 -0
  5. package/dist/components/toaster.d.ts +2 -0
  6. package/dist/components/tooltip.d.ts +11 -0
  7. package/dist/constants.d.ts +3 -0
  8. package/dist/context.d.ts +44 -0
  9. package/dist/hooks/useColorMode.d.ts +4 -0
  10. package/dist/hooks/usePageTitle.d.ts +2 -0
  11. package/dist/index.d.ts +26 -0
  12. package/dist/index.js +5036 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/paths.d.ts +26 -0
  15. package/dist/routes.d.ts +22 -0
  16. package/dist/theme.css +72 -0
  17. package/dist/toast.d.ts +18 -0
  18. package/dist/types.d.ts +474 -0
  19. package/dist/views/AgentActivityView.d.ts +8 -0
  20. package/dist/views/JobDetails.d.ts +2 -0
  21. package/dist/views/JobLogs.d.ts +4 -0
  22. package/dist/views/JobSubmit.d.ts +22 -0
  23. package/dist/views/JobSubmitView.d.ts +2 -0
  24. package/dist/views/JobsView.d.ts +4 -0
  25. package/dist/views/LogDisplay.d.ts +11 -0
  26. package/dist/views/PipelinesView.d.ts +2 -0
  27. package/dist/views/ScheduledJobsView.d.ts +2 -0
  28. package/package.json +70 -4
  29. package/src/api.ts +602 -0
  30. package/src/components/AutocompleteInput.tsx +253 -0
  31. package/src/components/MonacoEditor.tsx +163 -0
  32. package/src/components/toaster.tsx +38 -0
  33. package/src/components/tooltip.tsx +52 -0
  34. package/src/constants.ts +3 -0
  35. package/src/context.tsx +106 -0
  36. package/src/hooks/useColorMode.ts +31 -0
  37. package/src/hooks/usePageTitle.ts +21 -0
  38. package/src/index.ts +33 -0
  39. package/src/paths.ts +71 -0
  40. package/src/routes.tsx +55 -0
  41. package/src/theme.css +72 -0
  42. package/src/toast.ts +35 -0
  43. package/src/types.ts +542 -0
  44. package/src/views/AgentActivityView.tsx +262 -0
  45. package/src/views/JobDetails.tsx +675 -0
  46. package/src/views/JobLogs.tsx +987 -0
  47. package/src/views/JobSubmit.tsx +1272 -0
  48. package/src/views/JobSubmitView.tsx +69 -0
  49. package/src/views/JobsView.tsx +736 -0
  50. package/src/views/LogDisplay.tsx +171 -0
  51. package/src/views/PipelinesView.tsx +1318 -0
  52. package/src/views/ScheduledJobsView.tsx +735 -0
@@ -0,0 +1,987 @@
1
+ import React, { useEffect, useState, useMemo, useCallback } from 'react';
2
+ import { useParams, useNavigate, Link } from 'react-router-dom';
3
+ import { useBujang } from '../context';
4
+ import { usePageTitle } from '../hooks/usePageTitle';
5
+ import { Tooltip } from '../components/tooltip';
6
+ import {
7
+ Box,
8
+ Heading,
9
+ Text,
10
+ VStack,
11
+ HStack,
12
+ Button,
13
+ Card,
14
+ Spinner,
15
+ Alert,
16
+ Badge,
17
+ Flex,
18
+ Dialog,
19
+ Input,
20
+ Wrap,
21
+ WrapItem,
22
+ Field,
23
+ } from '@chakra-ui/react';
24
+ import { toaster } from '../toast';
25
+ import { LuArrowLeft, LuRefreshCw, LuX, LuDownload, LuInfo, LuExternalLink, LuClock, LuPencil } from 'react-icons/lu';
26
+ import { useQuery, useQueryClient } from '@tanstack/react-query';
27
+ import { getSlurmJobStdoutFull, getSlurmJobStderrFull, getSlurmJobStdoutSize, getSlurmJobStderrSize, getSlurmJobStatusSimple, getSshJobStatus, getSlurmJobAccounting, rerunSlurmJob, cancelSlurmJob, saveSlurmJob, getSlurmJobInfo, getSlurmJobCluster, getSlurmClusterStatus, earlySyncJob, getSlurmJobScript, getSlurmTemplates, getSlurmProfiles } from '../api';
28
+ import { JobSubmissionForm } from './JobSubmit';
29
+ import type { JobSubmissionInitialData } from './JobSubmit';
30
+ import { LogDisplay } from './LogDisplay';
31
+ import { NO_JOB_ID } from '../constants';
32
+ import type { SlurmJobDetail, ApiError } from '../types';
33
+
34
+ type JobLogsViewProps = Record<string, never>;
35
+
36
+ const getStatusColor = (status: string) => {
37
+ switch (status?.toLowerCase()) {
38
+ case 'running':
39
+ case 'r':
40
+ return 'green';
41
+ case 'pending':
42
+ case 'pd':
43
+ return 'yellow';
44
+ case 'completed':
45
+ case 'cd':
46
+ return 'blue';
47
+ case 'failed':
48
+ case 'f':
49
+ return 'red';
50
+ case 'cancelled':
51
+ case 'ca':
52
+ return 'gray';
53
+ default:
54
+ return 'gray';
55
+ }
56
+ };
57
+
58
+ function isStateTerminal(state: string) {
59
+ return [
60
+ "COMPLETED",
61
+ "FAILED",
62
+ "CANCELLED",
63
+ "TIMEOUT",
64
+ "NODE_FAIL",
65
+ "OUT_OF_MEMORY"
66
+ ].includes(state?.toUpperCase());
67
+ }
68
+
69
+ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
70
+ const params = useParams<{ slurmJobId: string; jrJobId: string }>();
71
+ const params_SlurmJobId = params["slurmJobId"];
72
+ const jrJobId = params["jrJobId"];
73
+
74
+ const [slurmJobId, setSlurmJobId] = useState(params_SlurmJobId);
75
+ const [jobStatus, setJobStatus] = useState<string | null>(null);
76
+ const [isJobTerminal, setIsJobTerminal] = useState(false);
77
+ const [shouldPoll, setShouldPoll] = useState(true);
78
+ const [countdown, setCountdown] = useState(30);
79
+ const [realtimeUpdateTrigger, setRealtimeUpdateTrigger] = useState(0);
80
+
81
+ // Keep slurmJobId in sync with URL parameters (important for rerun navigation)
82
+ useEffect(() => {
83
+ if (params_SlurmJobId !== slurmJobId) {
84
+ console.log('URL parameter changed, updating slurmJobId from', slurmJobId, 'to', params_SlurmJobId);
85
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- resets several state slots (job status, polling, realtime trigger) together in response to route navigation, not a pure derivation of a single value.
86
+ setSlurmJobId(params_SlurmJobId);
87
+ // Reset state when navigating to a new job
88
+ setJobStatus(null);
89
+ setIsJobTerminal(false);
90
+ setShouldPoll(true);
91
+ setRealtimeUpdateTrigger(0);
92
+ }
93
+ }, [params_SlurmJobId, slurmJobId]);
94
+
95
+ usePageTitle(`Job Logs - ${slurmJobId || 'Unknown'}`);
96
+
97
+ const navigate = useNavigate();
98
+ const { paths, pushJobData } = useBujang();
99
+ const queryClient = useQueryClient();
100
+
101
+ // Rerun state
102
+ const [isRerunning, setIsRerunning] = useState(false);
103
+
104
+ // Cancel state
105
+ const [isCancelling, setIsCancelling] = useState(false);
106
+
107
+ // Save job state
108
+ const [isSaving, setIsSaving] = useState(false);
109
+ const [commitMessage, setCommitMessage] = useState('');
110
+ const [commitMessageError, setCommitMessageError] = useState('');
111
+ const [isSaveModalOpen, setIsSaveModalOpen] = useState(false);
112
+ const onSaveModalOpen = () => setIsSaveModalOpen(true);
113
+ const onSaveModalClose = () => setIsSaveModalOpen(false);
114
+
115
+ // Push data state
116
+ const [isPushing, setIsPushing] = useState(false);
117
+
118
+ // Early sync state
119
+ const [isEarlySync, setIsEarlySync] = useState(false);
120
+
121
+ // Edit & Resubmit state
122
+ const [isEditModalOpen, setIsEditModalOpen] = useState(false);
123
+ const [editInitialData, setEditInitialData] = useState<JobSubmissionInitialData | undefined>(undefined);
124
+ const [isLoadingEditData, setIsLoadingEditData] = useState(false);
125
+
126
+ // Helper function to format file size
127
+ const formatFileSize = (bytes: number): string => {
128
+ if (bytes === 0) return '0 B';
129
+ const k = 1024;
130
+ const sizes = ['B', 'KB', 'MB', 'GB'];
131
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
132
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
133
+ };
134
+
135
+ // Primary job status query - this is our main data source
136
+ const {
137
+ data: jobStatusData,
138
+ isLoading: statusLoading,
139
+ error: statusError,
140
+ refetch: refetchStatus
141
+ } = useQuery({
142
+ queryKey: ['slurm-job-status-simple', jrJobId, slurmJobId],
143
+ queryFn: () => {
144
+ if (!jrJobId) {
145
+ throw new Error('Missing job IDs');
146
+ }
147
+ // no slurm job id: a pipeline step running over ssh (data mover), its state is in its job folder
148
+ if (!slurmJobId || slurmJobId === '-') {
149
+ return getSshJobStatus(jrJobId);
150
+ }
151
+ return getSlurmJobStatusSimple(jrJobId, slurmJobId);
152
+ },
153
+ enabled: !!jrJobId && shouldPoll,
154
+ refetchInterval: shouldPoll ? 30000 : false, // Refresh every 30 seconds when polling
155
+ refetchIntervalInBackground: true,
156
+ staleTime: 5000, // Consider data fresh for 5 seconds to avoid excessive requests
157
+ });
158
+
159
+ // Update local state when job status changes
160
+ useEffect(() => {
161
+ if (jobStatusData?.status) {
162
+ const newStatus = jobStatusData.status;
163
+ const wasTerminal = isJobTerminal;
164
+ const nowTerminal = isStateTerminal(newStatus);
165
+
166
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- synchronizes local state with data arriving asynchronously from the polling useQuery above.
167
+ setJobStatus(newStatus);
168
+ setIsJobTerminal(nowTerminal);
169
+
170
+ // Only trigger final log refresh if job just became terminal (transition from non-terminal to terminal)
171
+ // Don't trigger if job was already terminal or if this is the first status load
172
+ if (!wasTerminal && nowTerminal && jobStatus !== null) {
173
+ setShouldPoll(false);
174
+ toaster.create({
175
+ title: 'Job Finished',
176
+ description: `Job status changed to ${newStatus}. Logs will perform final refresh in 2 seconds.`,
177
+ type: 'info',
178
+ duration: 5000,
179
+ });
180
+
181
+ // Trigger final log refresh after 2 seconds
182
+ setTimeout(() => {
183
+ queryClient.invalidateQueries({ queryKey: ['slurm-job-logs'] });
184
+ }, 2000);
185
+ } else if (nowTerminal) {
186
+ // Job is already terminal, just stop polling without final refresh
187
+ setShouldPoll(false);
188
+ }
189
+ }
190
+ }, [jobStatusData, isJobTerminal, jobStatus, queryClient]);
191
+
192
+ // Cluster the job was submitted to, it never changes
193
+ const { data: jobClusterData } = useQuery({
194
+ queryKey: ['slurm-job-cluster', jrJobId],
195
+ queryFn: () => getSlurmJobCluster(jrJobId!),
196
+ enabled: !!jrJobId,
197
+ staleTime: Infinity,
198
+ });
199
+
200
+ // Backup job info query for additional details (non-polling)
201
+ const {
202
+ data: jobInfoData,
203
+ isLoading: jobInfoLoading,
204
+ } = useQuery({
205
+ queryKey: ['slurm-job-info', jrJobId, slurmJobId],
206
+ queryFn: () => {
207
+ const useJobId = slurmJobId && slurmJobId !== '-' ? slurmJobId : undefined;
208
+ return getSlurmJobInfo(jrJobId!, useJobId);
209
+ },
210
+ enabled: !!jrJobId && !!jobStatus, // Only load after we have status
211
+ staleTime: 60 * 1000, // Cache for 60 seconds
212
+ });
213
+
214
+ // Cluster status query to show stale badge when offline
215
+ const { data: clusterStatus } = useQuery({
216
+ queryKey: ['slurm-cluster-status'],
217
+ queryFn: getSlurmClusterStatus,
218
+ refetchOnWindowFocus: false,
219
+ staleTime: 30000,
220
+ refetchInterval: 60000,
221
+ retry: false,
222
+ });
223
+
224
+ // Accounting data query - only fetch when job is terminal for accurate duration
225
+ const { data: accountingData } = useQuery({
226
+ queryKey: ['slurm-job-accounting', jrJobId, slurmJobId],
227
+ queryFn: () => {
228
+ if (!jrJobId || !slurmJobId || slurmJobId === '-') {
229
+ throw new Error('Missing job IDs');
230
+ }
231
+ return getSlurmJobAccounting(jrJobId, slurmJobId);
232
+ },
233
+ enabled: !!jrJobId && !!slurmJobId && slurmJobId !== '-' && isJobTerminal,
234
+ staleTime: 300000, // Cache for 5 minutes since accounting data doesn't change
235
+ refetchOnWindowFocus: false,
236
+ });
237
+
238
+ // Helper function to check if job can be cancelled (only running or pending jobs)
239
+ const canCancelJob = (status: string | null) => {
240
+ if (!status) return false;
241
+ const lowerStatus = status.toLowerCase();
242
+ return lowerStatus === 'running' || lowerStatus === 'pending' || lowerStatus === 'r' || lowerStatus === 'pd';
243
+ };
244
+
245
+ // Helper function to format elapsed seconds to duration string
246
+ const formatElapsedSeconds = (seconds: number): string => {
247
+ const days = Math.floor(seconds / 86400);
248
+ const hours = Math.floor((seconds % 86400) / 3600);
249
+ const minutes = Math.floor((seconds % 3600) / 60);
250
+ const remainingSeconds = seconds % 60;
251
+
252
+ if (days > 0) {
253
+ return `${days}-${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
254
+ } else {
255
+ return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
256
+ }
257
+ };
258
+
259
+ // Helper function to get job duration (uses realtimeUpdateTrigger for real-time updates)
260
+ const getJobDuration = useCallback((jobData: SlurmJobDetail | undefined) => {
261
+ if (!jobData) return 'Unknown';
262
+
263
+ // For terminal jobs, prioritize accounting data elapsed time if available
264
+ if (isJobTerminal && accountingData?.time?.elapsed) {
265
+ return formatElapsedSeconds(accountingData.time.elapsed);
266
+ }
267
+
268
+ // If job has explicit elapsed time, use it
269
+ if (jobData.elapsed) {
270
+ return jobData.elapsed;
271
+ }
272
+
273
+ // Calculate duration from timestamps (real-time for running jobs)
274
+ const currentTime = Math.floor(Date.now() / 1000);
275
+
276
+ // Check if job has started
277
+ if (jobData.start_time?.set && jobData.start_time.number > 0) {
278
+ const startTime = jobData.start_time.number;
279
+ let endTime = currentTime;
280
+
281
+ // For finished jobs, use end_time if available
282
+ if (isJobTerminal && jobData.end_time?.set && jobData.end_time.number > 0) {
283
+ endTime = jobData.end_time.number;
284
+ }
285
+ // For running jobs, use current time for real-time updates
286
+ // (realtimeUpdateTrigger ensures this recalculates every second)
287
+
288
+ const durationSeconds = endTime - startTime;
289
+ return formatElapsedSeconds(durationSeconds);
290
+ }
291
+
292
+ // Check job state for pending jobs
293
+ if (jobStatus?.toLowerCase() === 'pending' || jobStatus?.toLowerCase() === 'pd') {
294
+ return 'Pending (not started)';
295
+ }
296
+
297
+ // If job has a time field, use it as fallback
298
+ if (jobData.time) {
299
+ return jobData.time;
300
+ }
301
+
302
+ return 'Not started';
303
+ }, [isJobTerminal, accountingData, jobStatus]);
304
+
305
+ // Memoized job duration that updates in real-time for running jobs
306
+ const currentJobDuration = useMemo(() => {
307
+ return getJobDuration(jobInfoData);
308
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- realtimeUpdateTrigger is not read in the body, but it is intentionally kept as a dependency: it ticks every second (see the timer effect below) purely to force this memo to recompute so the duration reflects the current wall-clock time.
309
+ }, [jobInfoData, getJobDuration, realtimeUpdateTrigger]);
310
+
311
+ // Countdown timer effect
312
+ useEffect(() => {
313
+ if (!shouldPoll) {
314
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- part of the timer-subscription effect below (resets the countdown shown by the interval); not a pure render-time derivation.
315
+ setCountdown(0);
316
+ return;
317
+ }
318
+
319
+ const timer = setInterval(() => {
320
+ setCountdown((prev) => {
321
+ if (prev <= 1) {
322
+ return 30; // Reset to 30 seconds
323
+ }
324
+ return prev - 1;
325
+ });
326
+ }, 1000);
327
+
328
+ return () => clearInterval(timer);
329
+ }, [shouldPoll]);
330
+
331
+ // Real-time duration timer for running jobs
332
+ useEffect(() => {
333
+ // Only update for running jobs (not pending, not terminal)
334
+ const isRunning = jobStatus && !isJobTerminal &&
335
+ !['pending', 'pd'].includes(jobStatus.toLowerCase());
336
+
337
+ if (!isRunning) {
338
+ return;
339
+ }
340
+
341
+ const timer = setInterval(() => {
342
+ setRealtimeUpdateTrigger(prev => prev + 1);
343
+ }, 1000);
344
+
345
+ return () => clearInterval(timer);
346
+ }, [jobStatus, isJobTerminal]);
347
+
348
+ const handleBack = () => {
349
+ navigate(-1);
350
+ };
351
+
352
+ const handleRefresh = () => {
353
+ refetchStatus();
354
+ queryClient.invalidateQueries({ queryKey: ['slurm-job-logs'] });
355
+ queryClient.invalidateQueries({ queryKey: ['slurm-cluster-status'] });
356
+ setCountdown(30);
357
+ toaster.create({
358
+ title: 'Status Refreshed',
359
+ description: 'Job status and logs have been refreshed.',
360
+ type: 'success',
361
+ duration: 2000,
362
+ });
363
+ };
364
+
365
+ const handleRerun = async () => {
366
+ if (!jrJobId) return;
367
+
368
+ setIsRerunning(true);
369
+ try {
370
+ const result = await rerunSlurmJob(jrJobId);
371
+
372
+ if (result.success) {
373
+ toaster.create({
374
+ title: 'Job Rerun Successfully',
375
+ description: `New job submitted with ID: ${result.job_id}. Job runner ID: ${result.jr_job_id}`,
376
+ type: 'success',
377
+ duration: 5000,
378
+ });
379
+
380
+ // Invalidate old queries to ensure fresh data for the new job
381
+ queryClient.invalidateQueries({ queryKey: ['slurm-job-status-simple'] });
382
+ queryClient.invalidateQueries({ queryKey: ['slurm-job-info'] });
383
+
384
+ // Navigate to the new job logs after a short delay
385
+ setTimeout(() => {
386
+ navigate(paths.jobLogs(result.job_id || NO_JOB_ID, result.jr_job_id || NO_JOB_ID));
387
+ }, 2000);
388
+ } else {
389
+ toaster.create({
390
+ title: 'Rerun Failed',
391
+ description: result.error || 'Failed to rerun job',
392
+ type: 'error',
393
+ duration: 5000,
394
+ });
395
+ }
396
+ } catch (error) {
397
+ toaster.create({
398
+ title: 'Rerun Failed',
399
+ description: (error as ApiError).message || 'An unexpected error occurred',
400
+ type: 'error',
401
+ duration: 5000,
402
+ });
403
+ } finally {
404
+ setIsRerunning(false);
405
+ }
406
+ };
407
+
408
+ const handleCancel = async () => {
409
+ if (!slurmJobId || slurmJobId === '-') {
410
+ toaster.create({
411
+ title: 'Cannot Cancel Job',
412
+ description: 'No Slurm job ID available for cancellation',
413
+ type: 'error',
414
+ duration: 3000,
415
+ });
416
+ return;
417
+ }
418
+
419
+ setIsCancelling(true);
420
+ try {
421
+ const result = await cancelSlurmJob(slurmJobId);
422
+
423
+ if (result.success) {
424
+ toaster.create({
425
+ title: 'Job Cancelled Successfully',
426
+ description: result.message || `Job ${slurmJobId} has been cancelled`,
427
+ type: 'success',
428
+ duration: 5000,
429
+ });
430
+
431
+ // Refresh status to show updated state
432
+ refetchStatus();
433
+ } else {
434
+ toaster.create({
435
+ title: 'Cancel Failed',
436
+ description: result.error || 'Failed to cancel job',
437
+ type: 'error',
438
+ duration: 5000,
439
+ });
440
+ }
441
+ } catch (error) {
442
+ toaster.create({
443
+ title: 'Cancel Failed',
444
+ description: (error as ApiError).message || 'An unexpected error occurred',
445
+ type: 'error',
446
+ duration: 5000,
447
+ });
448
+ } finally {
449
+ setIsCancelling(false);
450
+ }
451
+ };
452
+
453
+ const handleSaveClick = () => {
454
+ setCommitMessage('');
455
+ setCommitMessageError('');
456
+ onSaveModalOpen();
457
+ };
458
+
459
+ const handleSave = async () => {
460
+ if (!jrJobId) return;
461
+
462
+ // Validate commit message
463
+ if (!commitMessage.trim()) {
464
+ setCommitMessageError('Commit message is required');
465
+ return;
466
+ }
467
+
468
+ setIsSaving(true);
469
+ try {
470
+ const result = await saveSlurmJob(jrJobId, commitMessage.trim());
471
+
472
+ // Since the API returns an empty object on success, we check for the absence of error
473
+ if (!result.error) {
474
+ toaster.create({
475
+ title: 'Job Saved Successfully',
476
+ description: `Job ${jrJobId} has been saved with commit message: "${commitMessage.trim()}"`,
477
+ type: 'success',
478
+ duration: 5000,
479
+ });
480
+
481
+ onSaveModalClose();
482
+ setCommitMessage('');
483
+ } else {
484
+ toaster.create({
485
+ title: 'Save Failed',
486
+ description: result.error || 'Failed to save job',
487
+ type: 'error',
488
+ duration: 5000,
489
+ });
490
+ }
491
+ } catch (error) {
492
+ toaster.create({
493
+ title: 'Save Failed',
494
+ description: (error as ApiError).message || 'An unexpected error occurred',
495
+ type: 'error',
496
+ duration: 5000,
497
+ });
498
+ } finally {
499
+ setIsSaving(false);
500
+ }
501
+ };
502
+
503
+ const handlePushData = async () => {
504
+ if (!jrJobId || !pushJobData) return;
505
+
506
+ setIsPushing(true);
507
+ try {
508
+ const result = await pushJobData(jrJobId);
509
+
510
+ if (result.status === 'OK') {
511
+ toaster.create({
512
+ title: 'Data Pushed Successfully',
513
+ description: `Job data for ${jrJobId} has been pushed successfully.`,
514
+ type: 'success',
515
+ duration: 5000,
516
+ });
517
+ } else {
518
+ toaster.create({
519
+ title: 'Push Failed',
520
+ description: 'Failed to push job data',
521
+ type: 'error',
522
+ duration: 5000,
523
+ });
524
+ }
525
+ } catch (error) {
526
+ toaster.create({
527
+ title: 'Push Failed',
528
+ description: (error as ApiError).message || 'An unexpected error occurred',
529
+ type: 'error',
530
+ duration: 5000,
531
+ });
532
+ } finally {
533
+ setIsPushing(false);
534
+ }
535
+ };
536
+
537
+ const handleEarlySync = async () => {
538
+ if (!jrJobId || !slurmJobId || slurmJobId === '-') {
539
+ toaster.create({
540
+ title: 'Cannot Sync',
541
+ description: 'Job ID or Slurm Job ID is missing',
542
+ type: 'error',
543
+ duration: 3000,
544
+ });
545
+ return;
546
+ }
547
+
548
+ setIsEarlySync(true);
549
+ try {
550
+ const result = await earlySyncJob(jrJobId, slurmJobId);
551
+
552
+ if (result.status === 'ok') {
553
+ toaster.create({
554
+ title: 'Early Sync Successful',
555
+ description: 'Job results have been synced early from the compute node.',
556
+ type: 'success',
557
+ duration: 5000,
558
+ });
559
+
560
+ // Refresh the logs after sync
561
+ queryClient.invalidateQueries({ queryKey: ['slurm-job-logs'] });
562
+ } else {
563
+ toaster.create({
564
+ title: 'Early Sync Failed',
565
+ description: 'Could not sync job results early. Job may not be running or compute node unavailable.',
566
+ type: 'warning',
567
+ duration: 5000,
568
+ });
569
+ }
570
+ } catch (error) {
571
+ toaster.create({
572
+ title: 'Early Sync Failed',
573
+ description: (error as ApiError).message || 'An unexpected error occurred',
574
+ type: 'error',
575
+ duration: 5000,
576
+ });
577
+ } finally {
578
+ setIsEarlySync(false);
579
+ }
580
+ };
581
+
582
+ // Lazy-loaded templates & profiles for the edit modal
583
+ const { data: templateNames } = useQuery<string[]>({
584
+ queryKey: ['slurm-templates'],
585
+ queryFn: getSlurmTemplates,
586
+ enabled: isEditModalOpen,
587
+ refetchOnWindowFocus: false,
588
+ staleTime: 600000,
589
+ });
590
+
591
+ const { data: profiles } = useQuery({
592
+ queryKey: ['slurm-profiles'],
593
+ queryFn: getSlurmProfiles,
594
+ enabled: isEditModalOpen,
595
+ // ssh profiles (data movers) only run as pipeline steps
596
+ select: (ps) => ps.filter((p) => p.executor !== 'ssh'),
597
+ refetchOnWindowFocus: false,
598
+ staleTime: 300000,
599
+ });
600
+
601
+ const handleEditResubmit = async () => {
602
+ if (!jrJobId) return;
603
+
604
+ setIsLoadingEditData(true);
605
+ try {
606
+ const data = await getSlurmJobScript(jrJobId);
607
+ if (data.error) {
608
+ toaster.create({
609
+ title: 'Failed to Load Job Data',
610
+ description: data.error,
611
+ type: 'error',
612
+ duration: 5000,
613
+ });
614
+ return;
615
+ }
616
+ setEditInitialData({
617
+ script: data.script,
618
+ job_name: data.job_name,
619
+ sbatch_args: data.sbatch_args,
620
+ });
621
+ setIsEditModalOpen(true);
622
+ } catch (error) {
623
+ toaster.create({
624
+ title: 'Failed to Load Job Data',
625
+ description: (error as ApiError).message || 'Could not retrieve job script data',
626
+ type: 'error',
627
+ duration: 5000,
628
+ });
629
+ } finally {
630
+ setIsLoadingEditData(false);
631
+ }
632
+ };
633
+
634
+ const handleEditModalClose = () => {
635
+ setIsEditModalOpen(false);
636
+ setEditInitialData(undefined);
637
+ };
638
+
639
+ if (!jrJobId) {
640
+ return (
641
+ <Box p={6}>
642
+ <Alert.Root status="error">
643
+ <Alert.Indicator />
644
+ <Alert.Content>
645
+ <Alert.Title>Invalid Job ID</Alert.Title>
646
+ <Alert.Description>
647
+ No JR job ID provided in the URL.
648
+ </Alert.Description>
649
+ </Alert.Content>
650
+ </Alert.Root>
651
+ </Box>
652
+ );
653
+ }
654
+
655
+ return (
656
+ <Box p={6} className="job-logs-view" h="100%" display="flex" flexDirection="column">
657
+ <VStack align="stretch" gap={3} h="100%" flex="1" minH={0}>
658
+ {/* Header */}
659
+ <HStack justify="space-between">
660
+ <HStack gap={3}>
661
+ <Heading size="lg" mb={2}>Job Logs</Heading>
662
+ {clusterStatus?.status === 'offline' && (
663
+ <Tooltip
664
+ content={`Logs may be stale - cluster is offline${clusterStatus.reason ? `: ${clusterStatus.reason}` : ''}`}
665
+ >
666
+ <Badge
667
+ colorScheme="orange"
668
+ variant="solid"
669
+ fontSize="sm"
670
+ px={3}
671
+ py={1}
672
+ borderRadius="full"
673
+ cursor="help"
674
+ >
675
+ Stale Data
676
+ </Badge>
677
+ </Tooltip>
678
+ )}
679
+ </HStack>
680
+ <HStack gap={3}>
681
+ <Button
682
+ variant="outline"
683
+ onClick={handleRefresh}
684
+ loading={statusLoading}
685
+ >
686
+ <LuRefreshCw />
687
+ Refresh Now
688
+ </Button>
689
+ <HStack gap={0}>
690
+ <Button
691
+ variant="outline"
692
+ colorScheme="green"
693
+ onClick={handleRerun}
694
+ loading={isRerunning}
695
+ borderRightRadius={0}
696
+ >
697
+ <LuRefreshCw />
698
+ Rerun Job
699
+ </Button>
700
+ <Button
701
+ variant="outline"
702
+ colorScheme="green"
703
+ onClick={handleEditResubmit}
704
+ loading={isLoadingEditData}
705
+ borderLeftRadius={0}
706
+ borderLeft="none"
707
+ px={2}
708
+ title="Edit job before resubmitting"
709
+ >
710
+ <LuPencil />
711
+ </Button>
712
+ </HStack>
713
+ <Button
714
+ variant="outline"
715
+ colorScheme="orange"
716
+ onClick={handleEarlySync}
717
+ loading={isEarlySync}
718
+ disabled={!slurmJobId || slurmJobId === '-' || isJobTerminal}
719
+ >
720
+ <LuClock />
721
+ Early Sync
722
+ </Button>
723
+ {pushJobData && (
724
+ <Button
725
+ variant="outline"
726
+ colorScheme="blue"
727
+ onClick={handlePushData}
728
+ loading={isPushing}
729
+ disabled={!isJobTerminal}
730
+ > <LuExternalLink />
731
+ Push Data
732
+ </Button>
733
+ )}
734
+ {canCancelJob(jobStatus) && (
735
+ <Button
736
+ variant="outline"
737
+ colorScheme="red"
738
+ onClick={handleCancel}
739
+ loading={isCancelling}
740
+ >
741
+ <LuX />
742
+ Cancel Job
743
+ </Button>
744
+ )}
745
+ <Button
746
+ variant="outline"
747
+ colorScheme="purple"
748
+ onClick={handleSaveClick}
749
+ loading={isSaving}
750
+ >
751
+ <LuDownload />
752
+ Save Job
753
+ </Button>
754
+ <Button
755
+ asChild
756
+ variant="outline"
757
+ colorScheme="blue"
758
+ disabled={!slurmJobId || slurmJobId === '-'}
759
+ >
760
+ <Link to={paths.jobDetails(slurmJobId || NO_JOB_ID, jrJobId || NO_JOB_ID)}>
761
+ <HStack gap={2} as="span">
762
+ <LuInfo />
763
+ <Text>Job Details</Text>
764
+ </HStack>
765
+ </Link>
766
+ </Button>
767
+ <Button onClick={handleBack} variant="ghost">
768
+ <LuArrowLeft />
769
+ Back
770
+ </Button>
771
+ </HStack>
772
+ </HStack>
773
+
774
+ {/* Job Quick Info */}
775
+ <Card.Root bg="var(--color-bg-card)" padding="10px" border="1px solid" borderColor="var(--color-border)">
776
+ <Card.Body>
777
+ <Wrap gap={4} rowGap={2} align="center">
778
+ {jobClusterData?.cluster && (
779
+ <WrapItem>
780
+ <Badge colorPalette="blue" title={jobClusterData.login}>
781
+ {jobClusterData.cluster}
782
+ </Badge>
783
+ </WrapItem>
784
+ )}
785
+ <WrapItem>
786
+ <Text fontSize="sm" color="var(--color-text)">
787
+ <strong>ID:</strong> {jrJobId}
788
+ </Text>
789
+ </WrapItem>
790
+ {slurmJobId && (
791
+ <WrapItem>
792
+ <Text fontSize="sm" color="var(--color-text)">
793
+ <strong>Slurm Job ID:</strong> {slurmJobId}
794
+ </Text>
795
+ </WrapItem>
796
+ )}
797
+ <WrapItem>
798
+ <Text fontSize="sm" color="var(--color-text)">
799
+ <strong>Job Duration:</strong> {
800
+ jobInfoLoading
801
+ ? <><Spinner size="xs" mr={1} />Loading...</>
802
+ : currentJobDuration
803
+ }
804
+ </Text>
805
+ </WrapItem>
806
+
807
+ {/* Additional job details from job data */}
808
+ {jobInfoData?.gres_detail && (
809
+ <WrapItem>
810
+ <Text fontSize="sm" color="var(--color-text)">
811
+ <strong>GRES:</strong> {jobInfoData.gres_detail}
812
+ </Text>
813
+ </WrapItem>
814
+ )}
815
+ {jobInfoData?.cpus?.number && (
816
+ <WrapItem>
817
+ <Text fontSize="sm" color="var(--color-text)">
818
+ <strong>CPUs:</strong> {jobInfoData.cpus.number}
819
+ </Text>
820
+ </WrapItem>
821
+ )}
822
+ {jobInfoData?.job_resources?.allocated_nodes?.[0]?.memory_allocated && (
823
+ <WrapItem>
824
+ <Text fontSize="sm" color="var(--color-text)">
825
+ <strong>RAM:</strong> {Math.round(jobInfoData.job_resources.allocated_nodes[0].memory_allocated / 1024)} GB
826
+ </Text>
827
+ </WrapItem>
828
+ )}
829
+ {jobInfoData?.nodes && (
830
+ <WrapItem>
831
+ <Text fontSize="sm" color="var(--color-text)">
832
+ <strong>Nodes:</strong> {jobInfoData.nodes}
833
+ </Text>
834
+ </WrapItem>
835
+ )}
836
+
837
+ {jobStatus && (
838
+ <WrapItem>
839
+ <Badge colorScheme={getStatusColor(jobStatus)}>
840
+ {jobStatus}
841
+ </Badge>
842
+ </WrapItem>
843
+ )}
844
+ {statusLoading && (
845
+ <WrapItem>
846
+ <Badge colorScheme="gray">
847
+ <Spinner size="xs" mr={1} />
848
+ Checking Status...
849
+ </Badge>
850
+ </WrapItem>
851
+ )}
852
+ {statusError && (
853
+ <WrapItem>
854
+ <Badge colorScheme="red">
855
+ Status Error
856
+ </Badge>
857
+ </WrapItem>
858
+ )}
859
+ {shouldPoll && countdown > 0 && (
860
+ <WrapItem>
861
+ <Text fontSize="xs" color="var(--color-text-muted)">
862
+ Next refresh in {countdown}s
863
+ </Text>
864
+ </WrapItem>
865
+ )}
866
+ </Wrap>
867
+ </Card.Body>
868
+ </Card.Root>
869
+
870
+ {/* Logs Display - the logs are local files, show them even when the status could not be fetched */}
871
+ {(jobStatus || !statusLoading) && (
872
+ <Flex gap={6} direction={{ base: 'column', lg: 'row' }} className="log-holder" flex="1" minH={0} display="flex">
873
+ <LogDisplay
874
+ logType="stdout"
875
+ jrJobId={jrJobId!}
876
+ isJobFinished={isJobTerminal}
877
+ formatFileSize={formatFileSize}
878
+ fetchLogData={getSlurmJobStdoutFull}
879
+ getSlurmJobLogSize={getSlurmJobStdoutSize}
880
+ />
881
+
882
+ <LogDisplay
883
+ logType="stderr"
884
+ jrJobId={jrJobId!}
885
+ isJobFinished={isJobTerminal}
886
+ formatFileSize={formatFileSize}
887
+ fetchLogData={getSlurmJobStderrFull}
888
+ getSlurmJobLogSize={getSlurmJobStderrSize}
889
+ />
890
+ </Flex>
891
+ )}
892
+
893
+ {/* Loading state for logs */}
894
+ {!jobStatus && statusLoading && (
895
+ <Card.Root bg="var(--color-bg-card)" border="1px solid" borderColor="var(--color-border)" flex="1">
896
+ <Card.Body>
897
+ <VStack gap={4} justify="center" h="100%">
898
+ <Spinner size="xl" />
899
+ <Text>Loading job status...</Text>
900
+ </VStack>
901
+ </Card.Body>
902
+ </Card.Root>
903
+ )}
904
+
905
+ {/* Error state */}
906
+ {statusError && !jobStatus && (
907
+ <Alert.Root status="error">
908
+ <Alert.Indicator />
909
+ <Alert.Content>
910
+ <Alert.Title>Failed to load job status</Alert.Title>
911
+ <Alert.Description>
912
+ {statusError?.message || 'Unknown error occurred'}
913
+ </Alert.Description>
914
+ </Alert.Content>
915
+ </Alert.Root>
916
+ )}
917
+ </VStack>
918
+
919
+ {/* Save Job Modal */}
920
+ <Dialog.Root open={isSaveModalOpen} onOpenChange={(details) => setIsSaveModalOpen(details.open)}>
921
+ <Dialog.Backdrop />
922
+ <Dialog.Positioner>
923
+ <Dialog.Content>
924
+ <Dialog.Header>
925
+ <Dialog.Title>Save Job</Dialog.Title>
926
+ <Dialog.CloseTrigger />
927
+ </Dialog.Header>
928
+ <Dialog.Body>
929
+ <VStack align="stretch" gap={4}>
930
+ <Field.Root invalid={!!commitMessageError}>
931
+ <Field.Label>Commit Message</Field.Label>
932
+ <Input
933
+ value={commitMessage}
934
+ onChange={(e) => setCommitMessage(e.target.value)}
935
+ placeholder="Enter a commit message for this job"
936
+ onKeyDown={(e) => {
937
+ if (e.key === 'Enter' && !isSaving && commitMessage.trim()) {
938
+ handleSave();
939
+ }
940
+ }}
941
+ />
942
+ <Field.ErrorText>{commitMessageError}</Field.ErrorText>
943
+ </Field.Root>
944
+ </VStack>
945
+ </Dialog.Body>
946
+ <Dialog.Footer>
947
+ <Button variant="outline" mr={3} onClick={onSaveModalClose}>
948
+ Cancel
949
+ </Button>
950
+ <Button colorScheme="blue" onClick={handleSave} loading={isSaving}>
951
+ Save Job
952
+ </Button>
953
+ </Dialog.Footer>
954
+ </Dialog.Content>
955
+ </Dialog.Positioner>
956
+ </Dialog.Root>
957
+
958
+ {/* Edit & Resubmit Modal */}
959
+ <Dialog.Root
960
+ open={isEditModalOpen}
961
+ onOpenChange={(details) => {
962
+ if (!details.open) handleEditModalClose();
963
+ }}
964
+ size="cover"
965
+ >
966
+ <Dialog.Backdrop />
967
+ <Dialog.Positioner>
968
+ <Dialog.Content maxW="95vw" maxH="95vh" overflow="hidden" display="flex" flexDirection="column">
969
+ <Dialog.Header>
970
+ <Dialog.Title>Edit & Resubmit Job</Dialog.Title>
971
+ <Dialog.CloseTrigger />
972
+ </Dialog.Header>
973
+ <Dialog.Body flex="1" overflow="auto" p={0}>
974
+ <JobSubmissionForm
975
+ templates={templateNames}
976
+ profiles={profiles || []}
977
+ activeJobs={[]}
978
+ onClose={handleEditModalClose}
979
+ initialData={editInitialData}
980
+ />
981
+ </Dialog.Body>
982
+ </Dialog.Content>
983
+ </Dialog.Positioner>
984
+ </Dialog.Root>
985
+ </Box>
986
+ );
987
+ };