-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathazdo-pr-dashboard.user.js
More file actions
2889 lines (2509 loc) · 117 KB
/
Copy pathazdo-pr-dashboard.user.js
File metadata and controls
2889 lines (2509 loc) · 117 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.13.0
// @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://github.com/alejandro5042/azdo-userscripts/releases/latest/download/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
// @grant GM_xmlhttpRequest
// @connect graph.microsoft.com
// @connect login.microsoftonline.com
// ==/UserScript==
(function () {
'use strict';
// Early check: are we in an OOO auth redirect popup from the PKCE OAuth flow?
// This runs before any other script logic and closes the popup after relaying the code.
// Uses GM_setValue (Tampermonkey IPC) — reliable across sandboxed script contexts.
{
const oooParams = new URLSearchParams(window.location.search);
const oooState = oooParams.get('state');
if (oooState && oooState.startsWith('azdo-ooo-')) {
try {
// Key is state-specific to avoid collisions between concurrent attempts.
GM_setValue(`oooAuthResult-${oooState}`, JSON.stringify({
code: oooParams.get('code') || null,
state: oooState,
error: oooParams.get('error_description') || null,
errorCode: oooParams.get('error') || null,
}));
} catch (e) { /* ignore */ }
setTimeout(() => window.close(), 200);
return;
}
}
// All REST API calls should fail after a timeout, instead of going on forever.
$.ajaxSetup({ timeout: 5000 });
let currentUser;
let azdoApiBaseUrl;
let oooAccessToken = null;
let oooAccessTokenExpiry = null;
let oooAuthPromise = null; // coalesces concurrent token acquisitions (refresh or popup) across callers
let oooSilentAuthAttempted = false; // limit the fallback popup to one attempt per page session
// 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-2026-07-27', 'New in the AzDO userscript', `
<p>Highlights from the 2026-07-27 update!</p>
<ul>
<li>OOO info is now looked up live per-reviewer via Microsoft Graph (no more stale data!)</li>
<li>For non-NI/Emerson users, use <b>script menu → OOO Lookup: Configure Graph Client ID</b> to set up</li>
</ul>
<p>Comments, bugs, suggestions? File an issue on <a href="https://github.com/alejandro5042/azdo-userscripts" target="_blank">GitHub</a> 🧡</p>
`);
GM_registerMenuCommand('OOO Lookup: Configure Graph Client ID', async () => {
const current = GM_getValue('oooGraphClientId', '');
// eslint-disable-next-line no-alert
const clientId = prompt(
'OOO lookup works out of the box using a shared app registration – you normally do not '
+ 'need to set anything here.\n\n'
+ 'Only override the Azure AD Application (Client) ID if you are on a non-NI/Emerson tenant/org '
+ 'and want to use your own app registration (SPA redirect URI '
+ `${getOooRedirectUri()}, delegated Presence.Read.All + offline_access).\n\n`
+ 'Leave blank to use the shared default.',
current,
);
if (clientId === null) {
return;
}
GM_setValue('oooGraphClientId', clientId.trim());
oooAccessToken = null;
oooAccessTokenExpiry = null;
oooAuthPromise = null;
oooSilentAuthAttempted = false;
GM_deleteValue('oooAccessToken');
GM_deleteValue('oooAccessTokenExpiry');
// A new client ID means any stored refresh token is for a different app; drop it.
GM_deleteValue('oooRefreshToken');
GM_deleteValue('oooRefreshTokenExpiry');
// Sign in immediately so the user consents once and sees any admin-approval message;
// after this, silent auth keeps the token fresh automatically.
try {
await acquireOooTokenInteractive();
swal.fire({ icon: 'success', title: 'OOO Lookup Active', text: 'Reload a PR page to see live OOO annotations.' });
} catch (e) {
if (e.code && /consent_required/i.test(e.code)) {
const tenantId = GM_getValue('oooTenantId', 'organizations');
const adminConsentUrl = `https://login.microsoftonline.com/${tenantId}/v2.0/adminconsent`
+ `?client_id=${encodeURIComponent(getOooClientId())}`
+ `&redirect_uri=${encodeURIComponent(getOooRedirectUri())}`;
swal.fire({
icon: 'warning',
title: 'Admin approval required',
html: 'Your organization requires an IT admin to approve this app before users can sign in.<br><br>'
+ 'Share this URL with your IT admin (one-time setup, unlocks OOO for everyone):<br><br>'
+ `<input style="width:100%;font-size:0.8em;padding:4px" readonly onclick="this.select()" value="${adminConsentUrl}">`,
});
} else {
swal.fire({ icon: 'error', title: 'Authentication failed', text: String(e.message) });
}
}
});
}
// 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);
});
eus.onUrl(/\/(_releaseProgress)/gi, (session, urlMatch) => {
fixScrollBarColor();
});
// 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;
}
// ===== OOO Lookup via Microsoft Graph API =====
// Looks up each reviewer's out-of-office status live at page load time.
// Uses a shared, single-tenant Azure AD app registration (Presence.Read.All, delegated). The
// client ID below is public by design: this is an Authorization Code + PKCE public client, so
// there is NO client secret to leak. The app is locked down by tenant + delegated scope + the
// registered SPA redirect URIs (one per AZDO org root, e.g. https://dev.azure.com/ni/).
// Power users on other orgs/tenants can override the client ID via the Tampermonkey menu.
// offline_access is required for AAD to return a refresh token, which lets us mint new access
// tokens via a background POST (no popup) until the refresh token's own expiry.
const OOO_GRAPH_SCOPES = 'https://graph.microsoft.com/Presence.Read.All offline_access';
const OOO_STATE_PREFIX = 'azdo-ooo-';
// Shared app registration ("TM RD PR Metrics"). Safe to commit – public PKCE client, no secret.
const OOO_DEFAULT_GRAPH_CLIENT_ID = '968d0bcc-467a-4ec6-96be-3a1ab9e339e4';
function getOooClientId() {
// A per-user override (via the Tampermonkey menu) takes precedence over the shared default.
return GM_getValue('oooGraphClientId', '') || OOO_DEFAULT_GRAPH_CLIENT_ID;
}
function getOooRedirectUri() {
// https://dev.azure.com/ does a server-side redirect to https://dev.azure.com/{org}/,
// which strips the OAuth code/state query params before the userscript can intercept them.
// Use the org-specific root URL instead — it doesn't redirect further.
if (window.location.hostname === 'dev.azure.com') {
const org = window.location.pathname.split('/').filter(Boolean)[0];
if (org) return `${window.location.origin}/${org}/`;
}
return `${window.location.origin}/`;
}
function getOooRandom(len = 43) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
const buf = new Uint8Array(len);
crypto.getRandomValues(buf);
return Array.from(buf, b => chars[b % chars.length]).join('');
}
async function getOooPkceChallenge(verifier) {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
// Promisified GM_xmlhttpRequest — bypasses CORS for all OOO-related network calls.
function oooXhr(method, url, { headers = {}, body = null } = {}) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method,
url,
headers,
data: body,
onload: resp => resolve(resp),
onerror: () => reject(new Error(`Network error calling ${url}`)),
ontimeout: () => reject(new Error(`Timeout calling ${url}`)),
});
});
}
// Auto-discovers the AAD tenant ID from the user's email domain via OIDC metadata.
// Single-tenant apps (the default after Oct 2018) reject the /common endpoint;
// they require a tenant-specific URL like /login.microsoftonline.com/{tenantId}/...
async function getOooTenantId() {
const cached = GM_getValue('oooTenantId', '');
if (cached) return cached;
const email = currentUser && currentUser.uniqueName;
const domain = email && email.split('@')[1];
if (!domain) return 'organizations';
try {
const resp = await oooXhr(
'GET',
`https://login.microsoftonline.com/${encodeURIComponent(domain)}/.well-known/openid-configuration`,
);
if (resp.status >= 200 && resp.status < 300) {
const cfg = JSON.parse(resp.responseText);
// issuer is "https://login.microsoftonline.com/{tenantId}/v2.0"
const m = cfg.issuer && cfg.issuer.match(/\/([a-f0-9-]{36})\//i);
if (m) {
GM_setValue('oooTenantId', m[1]);
return m[1];
}
}
} catch (e) { /* ignore */ }
return 'organizations';
}
async function acquireOooTokenInteractive(silent = false) {
const clientId = getOooClientId();
if (!clientId) throw new Error('OOO Graph Client ID not configured. Use the Tampermonkey menu.');
const tenantId = await getOooTenantId();
const verifier = getOooRandom();
const challenge = await getOooPkceChallenge(verifier);
const state = OOO_STATE_PREFIX + getOooRandom(16);
const redirectUri = getOooRedirectUri();
sessionStorage.setItem(`ooo-pkce-${state}`, verifier);
function openAuthPopup(promptMode) {
const authUrl = new URL(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize`);
authUrl.searchParams.set('client_id', clientId);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('redirect_uri', redirectUri);
authUrl.searchParams.set('scope', OOO_GRAPH_SCOPES);
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('login_hint', currentUser.uniqueName);
authUrl.searchParams.set('prompt', promptMode);
return new Promise((resolve, reject) => {
// Clear any stale result from a prior attempt with this same state.
GM_deleteValue(`oooAuthResult-${state}`);
const popup = window.open(authUrl.toString(), 'ooo-auth', 'width=600,height=600,resizable=yes');
if (!popup) { reject(new Error('Popup blocked - allow popups for this site')); return; }
debug('OOO auth popup opened. Waiting for redirect back to', redirectUri);
function handleResult(result) {
clearInterval(pollId); // eslint-disable-line no-use-before-define
clearTimeout(timer); // eslint-disable-line no-use-before-define
GM_deleteValue(`oooAuthResult-${state}`);
debug('OOO auth result received:', result.code ? 'code obtained' : `error: ${result.errorCode}`);
if (result.error || result.errorCode) {
const err = new Error(result.error || result.errorCode);
err.code = result.errorCode;
reject(err);
return;
}
resolve(result.code);
}
// Poll GM storage every 200ms. GM_addValueChangeListener's 'remote' flag is unreliable
// for popup→opener communication (may be false even across windows), so polling is safer.
const pollId = setInterval(() => {
const rawVal = GM_getValue(`oooAuthResult-${state}`, null);
if (rawVal === null) return;
try { handleResult(JSON.parse(rawVal)); } catch (e) { clearInterval(pollId); }
}, 200);
const timer = setTimeout(() => {
clearInterval(pollId);
GM_deleteValue(`oooAuthResult-${state}`);
reject(new Error('Authentication timed out (2 min). Check that the redirect URI matches your Azure AD registration.'));
}, 2 * 60 * 1000);
});
}
// Try silent first (prompt=none); fall back to interactive if AAD requires user interaction.
debug('Starting OOO auth. Tenant:', tenantId, 'Redirect URI:', redirectUri);
let code;
try {
code = await openAuthPopup('none');
} catch (e) {
debug('Silent OOO auth failed, errorCode:', e.code, '— trying interactive');
if (e.code && /interaction_required|consent_required|login_required/i.test(e.code)) {
if (silent) throw e; // don't fall back to interactive UI in silent mode
code = await openAuthPopup('select_account');
} else {
throw e;
}
}
const storedVerifier = sessionStorage.getItem(`ooo-pkce-${state}`) || verifier;
sessionStorage.removeItem(`ooo-pkce-${state}`);
const tokenResp = await oooXhr('POST', `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
// SPA app registrations require an Origin header matching the redirect URI origin.
// GM_xmlhttpRequest doesn't send one automatically, so we add it explicitly.
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: window.location.origin },
body: new URLSearchParams([
['grant_type', 'authorization_code'],
['client_id', clientId],
['code', code],
['redirect_uri', redirectUri],
['code_verifier', storedVerifier],
['scope', OOO_GRAPH_SCOPES],
]).toString(),
});
if (tokenResp.status < 200 || tokenResp.status >= 300) {
const errData = JSON.parse(tokenResp.responseText || '{}');
error('OOO token exchange failed. Status:', tokenResp.status, 'Body:', tokenResp.responseText);
throw new Error(errData.error_description || errData.error || `Token exchange failed: HTTP ${tokenResp.status}`);
}
debug('OOO token exchange succeeded. Access token obtained.');
storeOooTokens(JSON.parse(tokenResp.responseText), /* isFreshLogin= */ true);
return oooAccessToken;
}
// Persists tokens returned by either the authorization_code or refresh_token grant. Refresh
// tokens are single-use and rotated, so we always store the latest one. For SPA redirect URIs
// the refresh token expires 24h after the original interactive login and that expiry carries
// over across rotations, so we only stamp the 24h clock on a fresh login.
function storeOooTokens(tokenData, isFreshLogin) {
oooAccessToken = tokenData.access_token;
oooAccessTokenExpiry = new Date(Date.now() + (tokenData.expires_in - 300) * 1000);
// Cache in GM storage so the token survives page navigations.
GM_setValue('oooAccessToken', oooAccessToken);
GM_setValue('oooAccessTokenExpiry', oooAccessTokenExpiry.getTime());
if (tokenData.refresh_token) {
GM_setValue('oooRefreshToken', tokenData.refresh_token);
if (isFreshLogin) {
GM_setValue('oooRefreshTokenExpiry', Date.now() + 24 * 60 * 60 * 1000);
}
}
}
// Mints a new access token from the stored refresh token via a background POST — no popup.
// Returns null (and drops the refresh token) if there's none or AAD rejects it, so the caller
// falls back to an interactive/silent popup.
async function refreshOooAccessToken() {
const refreshToken = GM_getValue('oooRefreshToken', '');
const refreshExpiry = GM_getValue('oooRefreshTokenExpiry', 0);
// SPA refresh tokens live only 24h; once past that a popup is unavoidable, so don't bother.
if (!refreshToken || Date.now() >= refreshExpiry) return null;
const clientId = getOooClientId();
if (!clientId) return null;
const tenantId = await getOooTenantId();
const tokenResp = await oooXhr('POST', `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: window.location.origin },
body: new URLSearchParams([
['grant_type', 'refresh_token'],
['client_id', clientId],
['refresh_token', refreshToken],
['scope', OOO_GRAPH_SCOPES],
]).toString(),
});
if (tokenResp.status < 200 || tokenResp.status >= 300) {
// Expired or revoked — drop it so the next acquisition falls back to a popup.
GM_deleteValue('oooRefreshToken');
GM_deleteValue('oooRefreshTokenExpiry');
return null;
}
storeOooTokens(JSON.parse(tokenResp.responseText), /* isFreshLogin= */ false);
return oooAccessToken;
}
function getOooGraphAccessToken() {
// In-memory cache (fastest path, valid for current page session).
if (oooAccessToken && oooAccessTokenExpiry && new Date() < oooAccessTokenExpiry) {
return oooAccessToken;
}
// GM_setValue cache — survives SPA page navigation, avoids a popup on every page load.
const savedToken = GM_getValue('oooAccessToken', '');
const savedExpiry = GM_getValue('oooAccessTokenExpiry', 0);
if (savedToken && Date.now() < savedExpiry) {
oooAccessToken = savedToken;
oooAccessTokenExpiry = new Date(savedExpiry);
return oooAccessToken;
}
// No valid cached access token. Acquire one, coalescing all concurrent callers (e.g. every
// reviewer on the page) onto a single attempt so we never fire duplicate single-use refresh
// requests or open multiple popups. Try the refresh token first (a background POST, no popup);
// only if that fails fall back to a silent popup, at most once per page session.
if (!oooAuthPromise && getOooClientId()) {
oooAuthPromise = (async () => {
const refreshed = await refreshOooAccessToken();
if (refreshed) return refreshed;
if (oooSilentAuthAttempted) return null;
oooSilentAuthAttempted = true;
return acquireOooTokenInteractive(/* silent= */ true).catch(() => null);
})().finally(() => { oooAuthPromise = null; });
}
return oooAuthPromise;
}
// Resolves an email to the user's AAD object ID (originId), which Graph's /presence endpoint
// requires. Neither the reviewer's identity.id nor its "aad." descriptor is the AAD object ID
// (they're AZDO-internal IMS/storage GUIDs), and the object ID isn't present anywhere on the page.
// AZDO's Identity Picker is served same-origin, so it authenticates via the existing session with
// no extra Microsoft Graph permission or admin consent.
async function resolveOooAadObjectId(email) {
const response = await fetch(`${azdoApiBaseUrl}_apis/IdentityPicker/Identities?api-version=5.0-preview.1`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
query: email,
identityTypes: ['user'],
operationScopes: ['ims', 'source'],
properties: ['DisplayName', 'Mail'],
options: { MinResults: 1, MaxResults: 20 },
}),
});
if (!response.ok) return null;
const data = await response.json();
const identities = (data.results && data.results[0] && data.results[0].identities) || [];
const wanted = email.toLowerCase();
const match = identities.find(i => (i.mail || i.signInAddress || '').toLowerCase() === wanted);
return (match && match.originId) || null;
}
// Graph's /presence endpoint requires the user's AAD object ID (GUID), resolved from their email.
async function fetchOooForEmail(email) {
const cacheKey = `azdo-userscripts-ooo-${email.replace(/[^a-z0-9]/gi, '_')}`;
const cacheDurationMs = 2 * 60 * 60 * 1000; // 2 hours
try {
const cached = JSON.parse(localStorage.getItem(cacheKey));
if (cached && Date.now() < cached.expiry) return cached.data;
} catch (e) { /* ignore */ }
const token = await getOooGraphAccessToken();
if (!token) return null;
const userGuid = await resolveOooAadObjectId(email);
if (!userGuid) return null;
try {
const graphResp = await oooXhr(
'GET',
`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(userGuid)}/presence`,
{ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' } },
);
let oooData = null;
if (graphResp.status >= 200 && graphResp.status < 300) {
const presence = JSON.parse(graphResp.responseText);
const oof = presence.outOfOfficeSettings;
if (oof && oof.isOutOfOffice) {
oooData = { Text: oof.message || '' };
}
localStorage.setItem(cacheKey, JSON.stringify({ expiry: Date.now() + cacheDurationMs, data: oooData }));
} else if (graphResp.status === 401) {
// Token rejected; clear both in-memory and GM storage so the next call re-authenticates.
oooAccessToken = null;
oooAccessTokenExpiry = null;
GM_deleteValue('oooAccessToken');
GM_deleteValue('oooAccessTokenExpiry');
}
return oooData;
} catch (e) {
error(`OOO lookup failed for ${email}:`, e);
return null;
}
}
function watchForPipelinesPage(session, pageData) {
addStyleOnce('agent-css', /* css */ `
.pipeline-status-icon {
margin-left: 5px;
font-size: 26px;
}
.pipeline-status-icon.ms-Icon--Blocked2Solid {
color: var(--component-status-error);
}
.pipeline-status-icon.ms-Icon--CirclePauseSolid {
color: var(--component-status-warning);
}
`);
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).find('.bolt-table-link')[0].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--Blocked2Solid', paused: 'ms-Icon--CirclePauseSolid' }[pipelineQueueStatus] || 'ms-Icon--Unknown');
const spanElement = $(pipelineTitleElement).find(classToAppendTo)[0];
spanElement.appendChild(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';