forked from alejandro5042/azdo-userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathazdo-pr-dashboard.user.js
More file actions
2406 lines (2081 loc) · 94.4 KB
/
azdo-pr-dashboard.user.js
File metadata and controls
2406 lines (2081 loc) · 94.4 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
// ==UserScript==
// @name More Awesome Azure DevOps (userscript)
// @version 3.8.1
// @author Alejandro Barreto (NI)
// @description Makes general improvements to the Azure DevOps experience, particularly around pull requests. Also contains workflow improvements for NI engineers.
// @license MIT
// @namespace https://github.com/alejandro5042
// @homepageURL https://alejandro5042.github.io/azdo-userscripts/
// @supportURL https://alejandro5042.github.io/azdo-userscripts/SUPPORT.html
// @updateURL https://rebrand.ly/update-azdo-pr-dashboard-user-js
// @contributionURL https://github.com/alejandro5042/azdo-userscripts
// @include https://dev.azure.com/*
// @include https://*.visualstudio.com/*
// @run-at document-body
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js#sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery-once/2.2.3/jquery.once.min.js#sha256-HaeXVMzafCQfVtWoLtN3wzhLWNs8cY2cH9OIQ8R9jfM=
// @require https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js#sha256-wCBClaCr6pJ7sGU5kfb3gQMOOcIZNzaWpWcj/lD9Vfk=
// @require https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js#sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps=
// @require https://cdn.jsdelivr.net/npm/sweetalert2@9.13.1/dist/sweetalert2.all.min.js#sha384-8oDwN6wixJL8kVeuALUvK2VlyyQlpEEN5lg6bG26x2lvYQ1HWAV0k8e2OwiWIX8X
// @require https://gist.githubusercontent.com/alejandro5042/af2ee5b0ad92b271cd2c71615a05da2c/raw/45da85567e48c814610f1627148feb063b873905/easy-userscripts.js#sha384-t7v/Pk2+HNbUjKwXkvcRQIMtDEHSH9w0xYtq5YdHnbYKIV7Jts9fSZpZq+ESYE4v
// @require https://unpkg.com/@popperjs/core@2.11.7#sha384-zYPOMqeu1DAVkHiLqWBUTcbYfZ8osu1Nd6Z89ify25QV9guujx43ITvfi12/QExE
// @require https://unpkg.com/tippy.js@6.3.7#sha384-AiTRpehQ7zqeua0Ypfa6Q4ki/ddhczZxrKtiQbTQUlJIhBkTeyoZP9/W/5ulFt29
// @require https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.8.0/build/highlight.min.js#sha384-g4mRvs7AO0/Ol5LxcGyz4Doe21pVhGNnC3EQw5shw+z+aXDN86HqUdwXWO+Gz2zI
// @require https://cdnjs.cloudflare.com/ajax/libs/js-yaml/3.14.0/js-yaml.min.js#sha512-ia9gcZkLHA+lkNST5XlseHz/No5++YBneMsDp1IZRJSbi1YqQvBeskJuG1kR+PH1w7E0bFgEZegcj0EwpXQnww==
// @resource linguistLanguagesYml https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml?v=1
// @grant GM_getResourceText
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_addValueChangeListener
// @grant GM_registerMenuCommand
// ==/UserScript==
(function () {
'use strict';
// All REST API calls should fail after a timeout, instead of going on forever.
$.ajaxSetup({ timeout: 5000 });
let currentUser;
let azdoApiBaseUrl;
// Some features only apply at National Instruments.
const atNI = /^ni\./i.test(window.location.hostname) || /^\/ni\//i.test(window.location.pathname);
function debug(...args) {
// eslint-disable-next-line no-console
console.log('[azdo-userscript]', args);
}
function error(...args) {
// eslint-disable-next-line no-console
console.error('[azdo-userscript]', args);
}
function main() {
eus.globalSession.onFirst(document, 'body', () => {
eus.registerCssClassConfig(document.body, 'Configure PR Status Location', 'pr-status-location', 'ni-pr-status-right-side', {
'ni-pr-status-default': 'Default',
'ni-pr-status-right-side': 'Right Side',
});
});
if (atNI) {
eus.registerCssClassConfig(document.body, 'Display Agent Arbitration Status', 'agent-arbitration-status', 'agent-arbitration-status-off', {
'agent-arbitration-status-on': 'On',
'agent-arbitration-status-off': 'Off',
});
eus.showTipOnce('release-2025-08-08', 'New in the AzDO userscript', `
<p>Highlights from the 2025-08-08 update!</p>
<ul>
<li>New: display the followers of a work item in the newer Boards view (#240).</li>
<li>Fix: navigating to the pull requests view from another AzDO page will now correctly show the organization pull requests page link. (#242)</li>
</ul>
<p>Comments, bugs, suggestions? File an issue on <a href="https://github.com/alejandro5042/azdo-userscripts" target="_blank">GitHub</a> 🧡</p>
`);
}
// Start modifying the page once the DOM is ready.
if (document.readyState !== 'loading') {
onReady();
} else {
document.addEventListener('DOMContentLoaded', onReady);
}
}
function onReady() {
// Find out who is our current user. In general, we should avoid using pageData because it doesn't always get updated when moving between page-to-page in AzDO's single-page application flow. Instead, rely on the AzDO REST APIs to get information from stuff you find on the page or the URL. Some things are OK to get from pageData; e.g. stuff like the user which is available on all pages.
const pageData = JSON.parse(document.getElementById('dataProviders').innerHTML).data;
currentUser = pageData['ms.vss-web.page-data'].user;
debug('init', pageData, currentUser);
const theme = pageData['ms.vss-web.theme-data'].requestedThemeId;
const isDarkTheme = /(dark|night|neptune)/i.test(theme);
// Because of CORS, we need to make sure we're querying the same hostname for our AzDO APIs.
azdoApiBaseUrl = `${window.location.origin}${pageData['ms.vss-tfs-web.header-action-data'].suiteHomeUrl}`;
// Invoke our new eus-style features.
watchPullRequestDashboard();
watchForWorkItemForms();
watchForNewDiffs(isDarkTheme);
watchForShowMoreButtons();
watchForBuildResultsPage();
if (atNI) {
watchForDiffHeaders();
watchFilesTree();
watchForKnownBuildErrors(pageData);
}
eus.onUrl(/\/pullrequest\//gi, (session, urlMatch) => {
if (atNI) {
watchForLVDiffsAndAddNIBinaryDiffButton(session);
watchForReviewerList(session);
// MOVE THIS HERE: conditionallyAddBypassReminderAsync();
}
watchForStatusCardAndMoveToRightSideBar(session);
addEditButtons(session);
addTrophiesToPullRequest(session, pageData);
fixImageUrls(session);
});
eus.onUrl(/\/(agentqueues|agentpools)(\?|\/)/gi, (session, urlMatch) => {
watchForAgentPage(session, pageData);
});
eus.onUrl(/\/(_build)(\?|$)/gi, (session, urlMatch) => {
watchForPipelinesPage(session, pageData);
});
eus.onUrl(/\/(_git)/gi, (session, urlMatch) => {
doEditAction(session);
watchForRepoBrowsingPages(session);
});
// Throttle page update events to avoid using up CPU when AzDO is adding a lot of elements during a short time (like on page load).
const onPageUpdatedThrottled = _.throttle(onPageUpdated, 400, { leading: false, trailing: true });
// Handle any existing elements, flushing it to execute immediately.
onPageUpdatedThrottled();
onPageUpdatedThrottled.flush();
// Call our event handler if we notice new elements being inserted into the DOM. This happens as the page is loading or updating dynamically based on user activity.
const targetNode = $('body > div.full-size')[0];
const observer = new MutationObserver(onPageUpdatedThrottled);
observer.observe(targetNode, { childList: true, subtree: true });
}
function watchForStatusCardAndMoveToRightSideBar(session) {
if (!document.body.classList.contains('ni-pr-status-right-side')) return;
addStyleOnce('pr-overview-sidebar-css', /* css */ `
/* Make the sidebar wider to accommodate the status moving there. */
.repos-overview-right-pane {
width: 550px;
}`);
session.onEveryNew(document, '.page-content .flex-column > .bolt-table-card', status => {
$(status).prependTo('.repos-overview-right-pane');
});
}
async function fetchJsonAndCache(key, secondsToCache, url, version = 1, fixer = x => x) {
let value;
const fullKey = `azdo-userscripts-${key}`;
const fullVersion = `1-${version}`;
let cached;
try {
cached = JSON.parse(localStorage[fullKey]);
} catch (e) {
cached = null;
}
if (cached && cached.version === fullVersion && dateFns.isFuture(dateFns.parse(cached.expiryDate))) {
value = cached.value;
} else {
localStorage.removeItem(fullKey);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Bad status ${response.status} for <${url}>`);
} else {
value = await response.json();
value = fixer(value);
}
const expirationDate = new Date(Date.now() + (secondsToCache * 1000));
localStorage[fullKey] = JSON.stringify({
version: fullVersion,
expiryDate: expirationDate.toISOString(),
value,
});
}
return value;
}
function watchForPipelinesPage(session, pageData) {
addStyleOnce('agent-css', /* css */ `
.pipeline-status-icon {
margin: 5px !important;
padding: 10px;
border-radius: 25px;
background: var(--search-selected-match-background);
color: var(--palette-error);
}
`);
const projectName = pageData['ms.vss-tfs-web.page-data'].project.name;
const urlParams = new URLSearchParams(window.location.search);
const urlDefinitionId = urlParams.get('definitionId');
if (urlDefinitionId) {
// Single Pipeline View
session.onEveryNew(document, '.ci-pipeline-details-header', pipelineTitleElement => {
setPipelineDefinitionDetails(projectName, urlDefinitionId, pipelineTitleElement, 'div.title-m');
});
} else {
// List of Pipelines View
session.onEveryNew(document, '.bolt-table-row', pipelineTitleElement => {
const href = pipelineTitleElement.href;
if (href) {
const pipelineHref = new URL(href);
const pipelineUrlParams = new URLSearchParams(pipelineHref.search);
const pipelineDefinitionId = pipelineUrlParams.get('definitionId');
setPipelineDefinitionDetails(projectName, pipelineDefinitionId, pipelineTitleElement, 'div.bolt-table-cell-content');
}
});
}
}
async function setPipelineDefinitionDetails(projectName, definitionId, pipelineTitleElement, classToAppendTo) {
const pipelineDetails = await fetchJsonAndCache(
`definitionId${definitionId}`,
0.5,
`${azdoApiBaseUrl}/${projectName}/_apis/build/definitions/${definitionId}`,
1,
);
const pipelineQueueStatus = pipelineDetails.queueStatus;
if (pipelineQueueStatus === 'enabled') {
return;
}
const userIcon = document.createElement('span');
userIcon.title = `Pipeline Status: ${pipelineQueueStatus.toUpperCase()}`;
userIcon.className = 'pipeline-status-icon fabric-icon';
userIcon.classList.add({ disabled: 'ms-Icon--Blocked', paused: 'ms-Icon--CirclePause' }[pipelineQueueStatus] || 'ms-Icon--Unknown');
const spanElement = $(pipelineTitleElement).find(classToAppendTo)[0];
spanElement.append(userIcon);
}
function watchForAgentPage(session, pageData) {
addStyleOnce('agent-css', /* css */ `
.agent-icon.offline {
width: 250px !important;
}
.disable-reason {
padding: 5px;
border-radius: 20px;
margin-right: 3px;
font-size: 12px;
text-decoration: none;
background: var(--search-selected-match-background);
}
input:read-only {
cursor: not-allowed;
color: #b1b1b1;
}
.agent-name-span {
width: calc(100% - 60px);
}
.capabilities-holder {
font-size: 20px;
text-align: left;
width: 40px;
margin-right: 20px;
overflow: hidden;
text-overflow: ellipsis;
}
`);
session.onEveryNew(document, '.pipelines-pool-agents.page-content.page-content-top', agentsTable => {
// Disable List Virtualization with 'CTRL + ALT + V'
document.dispatchEvent(new KeyboardEvent('keydown', {
bubbles: true,
composed: true,
key: 'v',
keyCode: 86,
code: 'KeyV',
which: 86,
altKey: true,
ctrlKey: true,
shiftKey: false,
metaKey: false,
}));
if (!document.getElementById('agentFilterInput')) {
const regexFilterString = new URL(window.location.href).searchParams.get('agentFilter') || '';
const agentFilterBarElement = `
<div style="padding-bottom: 16px">
<div class="vss-FilterBar bolt-filterbar-white depth-8 no-v-margin" role="search" id="testfilter">
<div class="vss-FilterBar--list">
<div class="vss-FilterBar--item vss-FilterBar--item-keyword-container">
<div class="flex-column flex-grow">
<div class="bolt-text-filterbaritem flex-grow bolt-textfield flex-row flex-center focus-keyboard-only">
<span aria-hidden="true" class="keyword-filter-icon prefix bolt-textfield-icon bolt-textfield-no-text flex-noshrink fabric-icon ms-Icon--Filter medium"></span>
<input
type="text" autocomplete="off"
class="bolt-text-filterbaritem-input bolt-textfield-input flex-grow bolt-textfield-input-with-prefix"
id="agentFilterInput"
placeholder="Regex Filter"
role="searchbox"
tabindex="0"
value="${regexFilterString}">
<div id="agentFilterCounter" style="color: var(--text-secondary-color);"/>
<div>
<button
id="copyMatchedAgentsToClipboard"
class="bolt-button bolt-icon-button subtle bolt-focus-treatment"
role="button"
tabindex="0"
type="button"
style="padding: 0px; margin-left: 10px;"
title="Copy Matched Agents to Clipboard">
<span class="left-icon flex-noshrink fabric-icon ms-Icon--Copy medium" style="padding: 5px 10px"/>
</button>
<button
id="agentFilterRefresh"
class="refresh-dashboard-button bolt-button bolt-icon-button subtle bolt-focus-treatment"
role="button"
tabindex="0"
type="button"
style="padding: 0px;">
<span class="left-icon flex-noshrink fabric-icon ms-Icon--Refresh medium" style="padding: 5px 10px"/>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>`;
$(agentsTable).prepend(agentFilterBarElement);
document.getElementById('agentFilterInput').addEventListener('input', filterAgentsDebouncer);
document.getElementById('agentFilterInput').addEventListener('keydown', filterAgentsNow);
document.getElementById('agentFilterRefresh').addEventListener('click', filterAgentsNow);
document.getElementById('copyMatchedAgentsToClipboard').addEventListener('click', copyMatchedAgentsToClipboard);
}
filterAgents();
});
// Status of agents can change as the table is constantly updating.
setInterval(filterAgents, 60000);
}
function copyMatchedAgentsToClipboard() {
if (filterAgents.running) return;
let matchString = '';
let total = 0;
const agentRows = document.querySelectorAll('a.bolt-list-row.single-click-activation');
agentRows.forEach(agentRow => {
const agentCells = agentRow.querySelectorAll('div');
const agentName = agentCells[1].innerText;
if ($(agentRow).is(':visible')) {
matchString += `${agentName}.*,`;
total += 1;
}
});
navigator.clipboard.writeText(matchString);
swal.fire({
icon: 'success',
title: `${total} matched agents copied to clipboard!`,
showConfirmButton: false,
timer: 1500,
});
}
function filterAgentsNow(event) {
if (event.key === 'Enter' || event.type === 'click') {
filterAgents.enter = true;
filterAgents();
}
}
function filterAgentsDebouncer() {
let timeout;
if (!document.hidden) {
clearTimeout(timeout);
timeout = setTimeout(filterAgents, 1000);
}
}
async function filterAgents() {
if (filterAgents.running) return;
filterAgents.running = true;
let regexFilterString = document.getElementById('agentFilterInput').value.trim();
let previousRegexFilterString = '';
let filterCheckCounter = 0;
const minimumNumberOfMatches = 10;
while (filterCheckCounter < minimumNumberOfMatches && !filterAgents.enter) {
if (previousRegexFilterString === regexFilterString) {
filterCheckCounter += 1;
} else {
filterCheckCounter = 0;
}
previousRegexFilterString = regexFilterString;
regexFilterString = document.getElementById('agentFilterInput').value.trim();
/* eslint-disable no-await-in-loop, no-promise-executor-return */
await new Promise(r => setTimeout(r, 100));
/* eslint-enable no-await-in-loop, no-promise-executor-return */
}
let regexFilter = '';
try {
regexFilter = new RegExp(regexFilterString, 'i');
} catch (e) {
showAllAgents(e);
return;
}
document.getElementById('agentFilterCounter').innerText = 'Filtering...';
document.getElementById('agentFilterInput').readOnly = true;
document.getElementById('copyMatchedAgentsToClipboard').disabled = true;
// Try to push the filter term if possible.
try {
const currentUrl = new URL(window.location.href);
currentUrl.searchParams.set('agentFilter', regexFilterString);
window.history.pushState({}, '', currentUrl.toString());
} catch (e) {
error(e);
}
const agentRows = document.querySelectorAll('a.bolt-list-row.single-click-activation');
const totalCount = agentRows.length;
const poolName = Array.from(document.querySelectorAll('div.bolt-breadcrumb-item-text-container')).pop().innerText;
const currentPoolId = await fetchJsonAndCache(
`azdoPool${poolName}Id`,
12 * 60 * 60,
`${azdoApiBaseUrl}/_apis/distributedtask/pools?poolName=${poolName}`,
1,
poolInfo => poolInfo.value[0].id,
);
const poolAgentsInfo = await fetchJsonAndCache(
`azdoPool${poolName}IdAgents`,
6,
`${azdoApiBaseUrl}/_apis/distributedtask/pools/${currentPoolId}/agents?includeCapabilities=True&propertyFilters=*`,
2,
poolAgentsInfoWithCapabilities => {
const filteredAgentInfo = {};
poolAgentsInfoWithCapabilities.value.forEach(agentInfo => {
filteredAgentInfo[agentInfo.name] = {
id: agentInfo.id,
userCapabilities: agentInfo.userCapabilities || {},
properties: agentInfo.properties,
};
});
return filteredAgentInfo;
},
);
try {
$('.hiddenAgentRow').show();
$(agentRows).find('.disable-reason').remove();
$(agentRows).find('.capabilities-holder').remove();
const matchedAgents = {};
agentRows.forEach(agentRow => {
const agentCells = agentRow.querySelectorAll('div');
const agentName = agentCells[1].innerText;
const disableReason = poolAgentsInfo[agentName].userCapabilities.DISABLE_REASON || null;
const rowValue = agentRow.textContent.replace(/[\r\n]/g, '').trim() + disableReason;
if (!regexFilter.test(rowValue)) {
agentRow.classList.add('hiddenAgentRow');
} else {
agentRow.classList.remove('hiddenAgentRow');
matchedAgents[agentName] = agentCells;
}
});
$('.hiddenAgentRow').hide();
for (const [agentName, agentCells] of Object.entries(matchedAgents)) {
if (atNI) {
agentCells[1].querySelectorAll('span')[0].classList.add('agent-name-span');
addAgentExtraInformation(agentCells, agentName, currentPoolId, poolAgentsInfo);
}
}
document.getElementById('agentFilterCounter').innerText = `(${Object.keys(matchedAgents).length}/${totalCount})`;
} catch (e) {
showAllAgents(e);
return;
}
exitFilterAgents();
}
function exitFilterAgents() {
document.getElementById('agentFilterInput').readOnly = false;
document.getElementById('copyMatchedAgentsToClipboard').disabled = false;
filterAgents.running = false;
filterAgents.enter = false;
}
function addAgentExtraInformation(agentCells, agentName, currentPoolId, poolAgentsInfo) {
const agentInfo = poolAgentsInfo[agentName];
if (agentInfo.userCapabilities) {
const disableReason = agentInfo.userCapabilities.DISABLE_REASON || null;
if (disableReason) {
const userIcon = document.createElement('span');
userIcon.className = 'fabric-icon ms-Icon--Contact';
const hiddenDisableReason = document.createElement('a');
hiddenDisableReason.text = disableReason;
hiddenDisableReason.style = 'display: none';
const disableReasonMessage = document.createElement('a');
let reservedBy = disableReason.match(/\[(.*)\]/);
if (!reservedBy) {
reservedBy = disableReason.match(/^([^-]*)/);
}
disableReasonMessage.className = 'disable-reason';
disableReasonMessage.text = reservedBy ? reservedBy[1] : disableReason;
disableReasonMessage.href = `${azdoApiBaseUrl}/_settings/agentpools?agentId=${agentInfo.id}&poolId=${currentPoolId}&view=capabilities`;
disableReasonMessage.prepend(userIcon);
disableReasonMessage.prepend(hiddenDisableReason);
disableReasonMessage.title = disableReason;
disableReasonMessage.style = 'max-width: 200px; text-overflow: ellipsis; overflow: hidden';
$(agentCells[5]).prepend(disableReasonMessage);
}
}
const capabilitiesHolder = document.createElement('div');
capabilitiesHolder.className = 'capabilities-holder';
const participateInRelease = agentInfo.userCapabilities.PARTICIPATE_IN_RELEASE || null;
if (participateInRelease === '1') {
const participateInReleaseElement = document.createElement('span');
participateInReleaseElement.className = 'capability-icon release-machine fabric-icon ms-Icon--Rocket';
participateInReleaseElement.title = 'PARTICIPATE_IN_RELEASE=1';
capabilitiesHolder.append(participateInReleaseElement);
}
if (!document.body.classList.contains('agent-arbitration-status-off')) {
if (agentInfo.properties && Object.prototype.hasOwnProperty.call(agentInfo.properties, 'under_arbitration')) {
const underArbitration = agentInfo.properties.under_arbitration.$value.toLowerCase() === 'true';
const iconType = underArbitration ? 'CirclePause' : 'Airplane';
const arbitrationIcon = document.createElement('span');
arbitrationIcon.className = `capability-icon arbiter fabric-icon ms-Icon--${iconType}`;
arbitrationIcon.title = underArbitration ? 'Arbitration Started: ' : 'Last Arbitration: ';
arbitrationIcon.title += new Date(agentInfo.properties.arbitration_start.$value * 1000);
capabilitiesHolder.append(arbitrationIcon);
}
}
agentCells[1].append(capabilitiesHolder);
}
function showAllAgents(searchError) {
if (searchError) {
document.getElementById('agentFilterCounter').innerText = searchError;
}
$('.hiddenAgentRow').show();
$('.hiddenAgentRow').removeClass('hiddenAgentRow');
exitFilterAgents();
}
async function watchForReviewerList(session) {
addStyleOnce('pr-reviewer-annotations', /* css */ `
.reviewer-status-message {
font-size: 0.7em;
margin-left: 2ch;
padding: 0px 3px;
border-radius: 4px;
cursor: pointer;
border: 1px solid #ffffff22;
float: right;
}
.reviewer-status-message.ooo {
background: var(--status-warning-background);
color: var(--status-warning-foreground);
}
.reviewer-status-message.flag {
background: none;
border: none;
}
.reviewer-status-message.owner {
background: rgba(var(--palette-primary), 1);
color: #fff;
}
.reviewer-status-message.alternate {
background: rgba(var(--palette-primary), 0.3);
color: #fff;
}
.reviewer-status-message.expert {
background: rgba(var(--palette-primary), 0.3);
color: #fff;
}
.tippy-box[data-theme~='azdo-userscript'] {
padding: 5px 10px;
}
.tippy-box[data-theme~='azdo-userscript'] li {
list-style: disc;
}
.tippy-box[data-theme~='azdo-userscript'] h1 {
background: rgb(255, 255, 255, 0.3);
border-radius: 4px;
margin-top: 0;
padding: 5px 10px;
font-size: 1.1em;
text-align: center;
line-height: 1.8em;
}
.tippy-box[data-theme~='azdo-userscript'] .user-message {
}
.owner-dir {
opacity: 0.7;
font-size: 80%;
}
.owner-file {
display: inline-block;
float: right;
margin-left: 2ex;
}`);
const prUrl = await getCurrentPullRequestUrlAsync();
const ownersInfo = await getNationalInstrumentsPullRequestOwnersInfo(prUrl);
const dataMaxAgeInDays = 3;
let oooInfo;
let oooByEmail;
try {
oooInfo = await fetchJsonAndCache('outOfOfficeLatest', 12 * 60 * 60, `${azdoApiBaseUrl}/_apis/git/repositories/3378df6b-8fc9-41dd-a9d9-16640f2392cb/items?api-version=6.0&path=/data/outOfOfficeLatest.json&version=main`);
if (oooInfo.version === 1) {
const dataDate = dateFns.parse(oooInfo.date);
if (dateFns.differenceInDays(new Date(), dataDate) >= dataMaxAgeInDays) {
// This data is too old. It hasn't been updated properly by the pipeline producing it. Avoid annotating.
throw new Error(`Data is too old (must be ${dataMaxAgeInDays} days old or less). Data date is: ${dataDate.toISOString()}`);
}
oooByEmail = _.keyBy(oooInfo.value, 'Email');
} else {
throw new Error(`Invalid version: ${oooInfo.version}`);
}
} catch (e) {
oooInfo = null;
error(`Cannot annotate out-of-office info on PRs: ${e}`);
}
let employeeInfo;
let employeeByEmail;
let me;
try {
employeeInfo = await fetchJsonAndCache('employeesLatest', 12 * 60 * 60, `${azdoApiBaseUrl}/_apis/git/repositories/3378df6b-8fc9-41dd-a9d9-16640f2392cb/items?api-version=6.0&path=/data/employeesLatest.json&version=main`, 3, employees => {
// HACK: Make the data much smaller so it fits in local storage.
for (const employee of employees.value) {
delete employee.username;
delete employee.title;
delete employee.manager_email;
delete employee.hr_org;
switch (employee.status) {
case 'Active Assignment':
delete employee.status;
break;
case 'Terminate Assignment':
employee.status = 'Ex-Employee';
break;
case 'LOA':
employee.status = 'Leave of Absence';
break;
default:
// Keep it.
break;
}
}
return employees;
});
if (employeeInfo.version === 1) {
const dataDate = dateFns.parse(employeeInfo.date);
if (dateFns.differenceInDays(new Date(), dataDate) >= dataMaxAgeInDays) {
// This data is too old. It hasn't been updated properly by the pipeline producing it. Avoid annotating.
throw new Error(`Data is too old (must be ${dataMaxAgeInDays} days old or less). Data date is: ${dataDate.toISOString()}`);
}
employeeByEmail = _.keyBy(employeeInfo.value, 'email');
me = employeeByEmail[currentUser.uniqueName];
} else {
throw new Error(`Invalid version: ${employeeInfo.version}`);
}
} catch (e) {
employeeInfo = null;
error(`Cannot annotate employee info on PRs: ${e}`);
}
session.onEveryNew(document, '.repos-pr-details-page .repos-reviewer', reviewer => {
const imageUrl = $(reviewer).find('.bolt-coin-content')[0].src;
const reviewerInfos = getPropertyThatStartsWith(reviewer.parentElement.parentElement, '__reactInternalInstance$').return.stateNode.state.values.reviewers;
const reviewerInfo = _.find(reviewerInfos, r => imageUrl.startsWith(r.identity.imageUrl));
const email = reviewerInfo.baseReviewer.uniqueName.toLowerCase();
const nameElement = $(reviewer).find('.body-m')[0];
if (ownersInfo) {
const reviewerIdentityIndex = _.findIndex(ownersInfo.reviewProperties.reviewerIdentities, r => r.email === email);
if (reviewerIdentityIndex >= 0) {
// eslint-disable-next-line no-inner-declarations
function annotateReviewerRole(label, cssClass, matcher) {
const files = _.filter(ownersInfo.reviewProperties.fileProperties, matcher).map(f => f.path);
if (files.length > 0) {
let prefix = '';
let filesToShow = files.sort();
const maxFilesToShow = 25;
if (files.length > maxFilesToShow) {
filesToShow = _.take(filesToShow, maxFilesToShow);
prefix = `<p>Showing first ${maxFilesToShow}:</p>`;
}
const fileListing = filesToShow
.map(f => `<li>${escapeStringForHtml(f).replace(/^(.*\/)?([^/]+?)$/, '<span class="owner-dir">$1</span><span class="owner-file">$2</span>')}</li>`)
.join('');
annotateReviewer(nameElement, cssClass, `${files.length}× ${label}`, `<div style='word-wrap : break-word;'>${prefix}${fileListing}</div>`, 'none');
}
}
// Note that the values for file.owner/alternate/experts may contain the value 0 (which is not a valid 1-based index) to indicate nobody for that role.
annotateReviewerRole('owner', 'owner', f => f.owner === reviewerIdentityIndex + 1);
annotateReviewerRole('alternate', 'alternate', f => f.alternate === reviewerIdentityIndex + 1);
annotateReviewerRole('expert', 'expert', f => _.some(f.experts, e => e === reviewerIdentityIndex + 1));
}
}
if (employeeInfo) {
const employee = employeeByEmail[email];
if (employee) {
if (me.country !== employee.country) {
annotateReviewer(nameElement, 'flag', `<img style="height: 1.2em" src="https://flagcdn.com/h20/${employee.country.toLowerCase()}.png" alt='${employee.country} flag' />`, escapeStringForHtml(employee.location_code));
}
if (employee.status) {
let status = employee.status;
if (status === 'Leave Without Pay') {
// Be nice and not show this status like this.
status = 'On Leave';
}
annotateReviewer(nameElement, 'ooo', escapeStringForHtml(status));
}
}
}
if (oooInfo) {
const ooo = oooByEmail[email];
if (ooo && dateFns.isFuture(ooo.End)) {
let label;
if (dateFns.isFuture(ooo.Start)) {
if (dateFns.differenceInHours(ooo.Start, new Date()) <= 24) {
label = 'Unavailable in <24h';
} else {
// Don't show a label. This person is leaving too far into the future.
label = null;
}
} else {
label = `Returns in ${dateFns.distanceInWordsToNow(ooo.End)}`;
}
if (label) {
const tooltipHtml = `
<p style='font-weight: bold; text-align: center'>Outlook Auto Response</p>
<h1>Leaving ${dateFns.format(ooo.Start, 'ha ddd, MMM D, YYYY')}<br>Returning ${dateFns.format(ooo.End, 'ha ddd, MMM D, YYYY')}</h1>
<p class="user-message">${ooo.Text.replace(/\r?\n/ig, '<br><br>')}</p>`;
annotateReviewer(nameElement, 'ooo', escapeStringForHtml(label), tooltipHtml);
}
}
}
});
}
function annotateReviewer(nameElement, cssClass, labelHtml, tooltipHtml, maxWidth = '600px') {
const messageElement = $('<span class="reviewer-status-message" />').addClass(cssClass).html(labelHtml);
if (tooltipHtml) {
tippy(messageElement[0], {
content: tooltipHtml,
allowHTML: true,
arrow: true,
theme: 'azdo-userscript',
maxWidth,
});
}
$(nameElement).append(messageElement);
}
function addEditButtons(session) {
session.onEveryNew(document, '.repos-summary-header > div:first-child .flex-column .secondary-text:nth-child(2)', path => {
const end = $(path).closest('.flex-row').find('.justify-end');
const branchUrl = $('.pr-header-branches a:first-child').attr('href');
const url = `${branchUrl}&path=${path.innerText}&_a=diff&azdouserscriptaction=edit`;
$('<a style="margin: 0px 1em;" class="flex-end bolt-button bolt-link-button enabled bolt-focus-treatment" data-focuszone="" data-is-focusable="true" target="_blank" role="link" onclick="window.open(this.href,\'popup\',\'width=600,height=600\'); return false;">Edit</a>').attr('href', url).appendTo(end);
});
session.onEveryNew(document, '.repos-compare-header-commandbar.bolt-button-group', button => {
if (eus.seen(button)) return;
$(button).before(setupVSCodeButton(() => {
if ($('.pr-status-completed').length > 0) {
eus.toast.fire({
title: 'AzDO userscript',
text: 'Cannot open VSCode on a completed pull request.',
icon: 'error',
});
return null;
}
const urlParams = new URLSearchParams(window.location.search);
const path = urlParams.get('path') || '';
const branchUrl = `${window.location.origin}${$('.pr-header-branches a').attr('href')}`;
const url = `${branchUrl}&path=${path}`;
return url;
}));
});
}
async function doEditAction(session) {
if (window.location.search.indexOf('azdouserscriptaction=edit') >= 0) {
await eus.sleep(1500);
$('button#__bolt-edit').click();
$('div#__bolt-tab-diff').click();
}
}
// This is "main()" for this script. Runs periodically when the page updates.
function onPageUpdated() {
try {
// The page may not have refreshed when moving between URLs--sometimes AzDO acts as a single-page application. So we must always check where we are and act accordingly.
if (/\/(pullrequest)\//i.test(window.location.pathname)) {
// TODO: BROKEN IN NEW PR UX: applyStickyPullRequestComments();
// TODO: BROKEN IN NEW PR UX: highlightAwaitComments();
addAccessKeysToPullRequestTabs();
if (atNI) {
conditionallyAddBypassReminderAsync();
}
}
if (/\/(pullrequests)/i.test(window.location.pathname)) {
addOrgPRLink();
}
} catch (e) {
eus.toast.fire({
title: 'AzDO userscript error',
text: 'See JS console for more info.',
icon: 'error',
showConfirmButton: true,
confirmButtonColor: '#d43',
confirmButtonText: '<i class="fa fa-bug"></i> Get Help!',
}).then((result) => {
if (result.value) {
window.open(GM_info.script.supportURL, '_blank');
}
});
throw e;
}
}
enhanceOverallUX();
addStyleOnce('labels', /* css */ `
/* Known bug severities we should style. */
.pr-bug-severity-1 {
background: #a008 !important;
}
.pr-bug-severity-2 {
background: #fd38 !important;
}
/* Align labels to the right and give them a nice border. */
.repos-pr-list .bolt-pill-group {
flex-grow: 1;
justify-content: flex-end;
}
.bolt-pill {
border: 1px solid #0001;
}
/* Known labels we should style. */
.pr-annotation:not([title=""]) {
cursor: help !important;
}
.pr-annotation.file-count,
.pr-annotation.build-status {
background: #fff4 !important;
min-width: 8ex;
}`);
if (atNI) {
addStyleOnce('ni-labels', /* css */ `
/* Known labels we should style. */
.bolt-pill[aria-label='draft' i] {
background: #8808 !important;
}
.bolt-pill[aria-label='tiny' i] {
background: #0a08 !important;
}
.bolt-pill[aria-label~='blocked' i] {
background: #a008 !important;
}`);
}
addStyleOnce('bypassOwnersPrompt', /* css */ `
.bypass-reminder {
display: inline;
position: absolute;
top: 38px;
left: -250px;
z-index: 1000;
background-color: #E6B307;
color: #222;
font-weight: bold;
padding: 3ch 5ch;
font-size: 16px;
border-radius: 6px 0px 6px 6px;
box-shadow: 4px 4px 4px #18181888;
opacity: 0;
transition: 0.3s;
}
.bypass-reminder-container {
position: relative;
display: inline-flex;
flex-direction: column;
}
.vote-button-wrapper {
border: 3px solid transparent;
border-radius: 4px 4px 0px 0px;
transition: 0.3s;
}
.vote-button-wrapper:hover {
border-color: #E6B307;
}
.vote-button-wrapper:hover ~ .bypass-reminder {
opacity: 1;
}`);
function watchForWorkItemForms() {
eus.globalSession.onEveryNew(document, '#__bolt-follow', followButton => {
followButton.addEventListener('click', async _ => {
await eus.sleep(1000); // We need to allow the other handlers to send the request to follow/unfollow. After the request is sent, we can annotate our follows list correctly.
await annotateWorkItemWithFollowerList(document.querySelector('.comment-editor.enter-new-comment'));
});
});
// Annotate work items (under the comment box) with who is following it.
eus.globalSession.onEveryNew(document, '.comment-editor.enter-new-comment', async commentEditor => {
await annotateWorkItemWithFollowerList(commentEditor);
});
}
async function annotateWorkItemWithFollowerList(commentEditor) {
const commentEditorContainer = commentEditor.closest('.new-comment-div');
commentEditorContainer.querySelectorAll('.work-item-followers-list').forEach(e => e.remove());
const workItemId = getCurrentWorkItemId(commentEditor);
const queryResponse = await fetch(`${azdoApiBaseUrl}_apis/notification/subscriptionquery?api-version=6.0`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
conditions: [
{
filter: {