Skip to content

Instantly share code, notes, and snippets.

@miku1958
Last active August 27, 2026 07:29
Show Gist options
  • Select an option

  • Save miku1958/d0d1b5ba6329672353c44851184fe4a2 to your computer and use it in GitHub Desktop.

Select an option

Save miku1958/d0d1b5ba6329672353c44851184fe4a2 to your computer and use it in GitHub Desktop.
ADOQuickReply.js
// ==UserScript==
// @name ADO Quick Reply
// @namespace http://tampermonkey.net/
// @version 2026.8.27.3
// @description ADO Quick Reply
// @author Tao Zhuang
// @match https://office.visualstudio.com/*/_workitems/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=visualstudio.com
// @grant none
// ==/UserScript==
(function () {
const NEWBOX_SELECTOR = '.discussion-new-comment.markdown-discussion-comment';
/**
* Write a diagnostic event with a sortable timestamp.
* @param {'debug' | 'error'} level
* @param {string} event
* @param {Record<string, unknown>} details
*/
function log(level, event, details) {
console[level](`[ADO Quick Reply ${new Date().toISOString()}] ${event}`, details);
}
/**
* Get the active Rooster discussion editor.
* @returns {HTMLElement | null}
*/
function getDiscussionEditor() {
const editor = document.querySelector(
`${NEWBOX_SELECTOR} [contenteditable="true"][role="textbox"]`
);
return editor instanceof HTMLElement ? editor : null;
}
/**
* Get the identity and source HTML already loaded by the ADO comment component.
* @param {HTMLElement} commentEl
* @returns {{author: {id: string, name: string} | null, text: string} | null}
*/
function getRenderedComment(commentEl) {
const authorName = commentEl
.querySelector('.user-display-name')
?.textContent
?.trim();
const reactKey = Object.keys(commentEl).find(key =>
key.startsWith('__reactInternalInstance$') ||
key.startsWith('__reactFiber$')
);
let fiber = reactKey ? commentEl[reactKey] : null;
let author = null;
let comment = null;
const findAuthor = (value, depth = 0) => {
if (author || depth > 8 || value == null || typeof value !== 'object') {
return;
}
if (
typeof value.id === 'string' &&
value.displayName === authorName &&
/^[0-9a-f-]{36}$/i.test(value.id)
) {
author = {id: value.id, name: value.displayName};
return;
}
if (Array.isArray(value)) {
value.forEach(item => findAuthor(item, depth + 1));
return;
}
['identity', 'props', 'children'].forEach(key => {
findAuthor(value[key], depth + 1);
});
};
for (let index = 0; fiber && index < 10; index++, fiber = fiber.return) {
const props = fiber.memoizedProps;
findAuthor(props);
const candidate = props?.commentWithReactions?.comment ?? props?.comment;
if (!comment && candidate && typeof candidate.text === 'string') {
comment = candidate;
}
}
if (!comment || (!commentEl.querySelector('.ms-Icon--Edit') && !author)) {
return null;
}
return {
author: commentEl.querySelector('.ms-Icon--Edit') ? null : author,
text: comment.text
};
}
/**
* Extract the author and mention targets from a comment API response.
* @param {string} commentText
* @param {{id: string, name: string} | null} author
* @returns {{id: string, name: string}[]}
*/
function extractPeople(commentText, author) {
/** @type {Map<string, {id: string, name: string}>} */
const people = new Map();
const source = new DOMParser().parseFromString(
commentText,
'text/html'
);
source.querySelectorAll('a[data-vss-mention]').forEach(anchor => {
const identityMatch = anchor
.getAttribute('data-vss-mention')
?.match(/^version:2\.0,([0-9a-f-]{36})$/i);
const name = anchor.textContent?.trim().replace(/^@/, '');
if (identityMatch && name) {
people.set(identityMatch[1], {id: identityMatch[1], name});
}
});
if (author) {
people.set(author.id, author);
}
return [...people.values()];
}
/**
* Append native ADO mention nodes to the discussion editor.
* @param {HTMLElement} editor
* @param {{id: string, name: string}[]} people
* @returns {boolean}
*/
function appendMentions(editor, people) {
editor.focus();
const selection = getSelection();
const range = document.createRange();
range.selectNodeContents(editor);
range.collapse(false);
selection?.removeAllRanges();
selection?.addRange(range);
const content = document.createElement('span');
if (editor.textContent?.trim()) {
content.append(' ');
}
people.forEach(person => {
const mention = document.createElement('a');
mention.href = '#';
mention.dataset.vssMention = `version:2.0,${person.id}`;
mention.textContent = `@${person.name}`;
content.append(mention, ' ');
});
return document.execCommand('insertHTML', false, content.innerHTML);
}
/**
* Resolve and append the people associated with one comment.
* @param {HTMLElement} commentEl
* @param {HTMLButtonElement} button
*/
function forwardComment(commentEl, button) {
const traceId = crypto.randomUUID();
const startedAt = performance.now();
button.disabled = true;
log('debug', 'forward_started', {traceId});
try {
const comment = getRenderedComment(commentEl);
if (!comment) {
log('error', 'rendered_comment_missing', {
traceId,
result: 'No content was inserted.'
});
return;
}
const people = extractPeople(comment.text, comment.author);
const editor = getDiscussionEditor();
if (!editor || people.length === 0) {
log('error', 'forward_content_missing', {
traceId,
hasEditor: !!editor,
peopleCount: people.length,
result: 'No content was inserted.'
});
return;
}
stage = 'insert_mentions';
const inserted = appendMentions(editor, people);
log(inserted ? 'debug' : 'error', 'forward_finished', {
traceId,
peopleCount: people.length,
inserted,
durationMs: Math.round(performance.now() - startedAt)
});
} catch (error) {
log('error', 'forward_failed', {
traceId,
error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
result: 'No additional content was inserted.'
});
} finally {
button.disabled = false;
}
}
/**
* Ensure each comment has a "Forward" button and bind click event
* @param {HTMLElement} commentEl
*/
function ensureForwardButtons(commentEl) {
if (commentEl.querySelector('.forward-btn-x')) {
return;
}
/** @type {HTMLButtonElement} */
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'forward-btn-x';
btn.textContent = 'Forward';
Object.assign(btn.style, {
marginLeft: '8px',
padding: '2px 8px',
border: '1px solid #ccc',
borderRadius: '6px',
background: 'transparent',
cursor: 'pointer'
});
const rightOpArea = commentEl.querySelector(
'.comment-viewer-toolbar > .flex-row'
);
if (rightOpArea == null) {
return;
}
rightOpArea.appendChild(btn);
btn.addEventListener('click', () => {
forwardComment(commentEl, btn);
});
}
document.querySelectorAll('.comment-item').forEach(comment => {
if (comment instanceof HTMLElement) {
ensureForwardButtons(comment);
}
});
new MutationObserver((items) => {
items.forEach((item) => {
item.addedNodes.forEach(node => {
if (!(node instanceof HTMLElement)) {
return;
}
const parentComment = node.closest('.comment-item');
if (parentComment instanceof HTMLElement) {
ensureForwardButtons(parentComment);
}
node.querySelectorAll('.comment-item').forEach(comment => {
if (comment instanceof HTMLElement) {
ensureForwardButtons(comment);
}
});
});
});
}).observe(document.body, {
subtree: true,
childList: true
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment