Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
163bfad30a | ||
|
|
23c8e57a8e | ||
|
|
350bfc067d | ||
|
|
98aecd8255 | ||
|
|
7d4ff1f095 | ||
|
|
3605c42651 | ||
|
|
d7e2813700 | ||
|
|
fb34b5ffda | ||
|
|
820da7130d |
No files matched your search
@@ -30,6 +30,8 @@ button { background: linear-gradient(180deg,#1f3a5f,#15324d); border:1px solid #
|
||||
.security-activity-header h3, .security-activity-header p { margin:0 0 6px; }
|
||||
.security-activity-list { display:grid; gap:8px; margin:12px 0; }
|
||||
.security-event { padding:12px; border:1px solid #243d5d; border-radius:12px; background:#0d1c30; }
|
||||
.authentication-alert { border-color:#d69e2e; background:#241b09; }
|
||||
.authentication-alert strong { color:#f6c453; }
|
||||
.security-event strong, .security-event span { display:block; overflow-wrap:anywhere; }
|
||||
#load-more-security-activity { width:100%; min-height:44px; }
|
||||
button:hover { filter: brightness(1.15); }
|
||||
@@ -151,6 +153,12 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.my-work-card-main.review-trigger { width:100%; text-align:left; font:inherit; }
|
||||
.my-work-card:hover { border-color:var(--accent); }
|
||||
.my-work-card-title { display:block; margin:5px 0; font-weight:650; }
|
||||
.update-selection-controls { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
|
||||
.update-selection-controls button { min-height:44px; }
|
||||
.update-selector { min-height:44px; display:flex; align-items:center; gap:10px; padding:6px; border:1px solid #31577f; border-radius:8px; cursor:pointer; }
|
||||
.update-selector input { width:22px; height:22px; flex:0 0 auto; }
|
||||
.my-work-card.selection-active { border-color:#31577f; }
|
||||
.my-work-card.selected { border-color:#60a5fa; box-shadow:inset 4px 0 #60a5fa; }
|
||||
.later-actions, .today-actions { display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:8px; }
|
||||
.later-actions button { min-height:44px; width:100%; }
|
||||
.today-actions button { min-height:44px; width:100%; }
|
||||
@@ -265,6 +273,7 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.update-ownership-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
|
||||
.update-ownership-actions button { min-width:0; width:100%; }
|
||||
.update-sheet-actions button, .update-sheet-actions a { min-height:44px; display:flex; align-items:center; justify-content:center; }
|
||||
.update-sheet-actions #acknowledge-update-next { min-height:44px; width:100%; }
|
||||
.update-sheet-actions a { border:1px solid #60a5fa; border-radius:10px; font-weight:700; }
|
||||
.update-retry { min-height:44px; width:100%; margin-top:10px; }
|
||||
.issue-sheet { position:fixed; inset:0; z-index:56; display:none; justify-content:flex-end; background:rgba(5,12,21,.72); backdrop-filter:blur(4px); }
|
||||
@@ -461,6 +470,7 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.work-settings:not([open]) > .work-settings-panel { display:none; }
|
||||
.work-settings-panel { display:grid; gap:10px; margin-top:8px; }
|
||||
.my-work-list { grid-template-columns:1fr; }
|
||||
.my-work-bulk { bottom:calc(56px + env(safe-area-inset-bottom)); }
|
||||
.my-work-card { min-width:0; overflow-x:hidden; }
|
||||
.card-planning > summary { min-height:44px; display:flex; align-items:center; justify-content:center; cursor:pointer; border:1px solid #60a5fa; border-radius:10px; font-weight:700; list-style:none; }
|
||||
.card-planning > summary::-webkit-details-marker { display:none; }
|
||||
|
||||
+140
-32
@@ -269,11 +269,8 @@
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
const reviewController = createReviewController({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
const wrapPreference = createReviewController.createWrapPreference({
|
||||
storage: localStorage,
|
||||
mobile: window.matchMedia('(max-width: 600px)').matches,
|
||||
});
|
||||
let reviewController = null;
|
||||
let wrapPreference = null;
|
||||
const issueController = createIssueSheet({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
const issueAttachmentController = issueAttachment.mount({
|
||||
input: qs('#issue-attachment'),
|
||||
@@ -366,7 +363,7 @@
|
||||
loadLabels: item => issueController.loadLabels(item),
|
||||
loadMilestones: item => issueController.loadMilestones(item),
|
||||
});
|
||||
const issueCapture = createIssueCapture({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
let issueCapture = null;
|
||||
const unfiledCaptures = createUnfiledCaptures({
|
||||
storage: localStorage,
|
||||
getCaptureLogin: () => String(lastContextSnapshot?.user?.login || '').trim(),
|
||||
@@ -416,9 +413,49 @@
|
||||
text: shareParams.get('text') || '',
|
||||
url: shareParams.get('url') || '',
|
||||
};
|
||||
let sharedLaunchState = Object.values(sharedLaunch).some(Boolean) ?
|
||||
issueCapture.stageSharedContent(sharedLaunch) : null;
|
||||
const pullController = createPullSheet({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
const issueCaptureFeatures = createFeatureLoader({
|
||||
document,
|
||||
urls: {
|
||||
'issue-capture': document.querySelector('meta[name="stackchain-feature-issue-capture"]')?.content || '',
|
||||
},
|
||||
});
|
||||
let sharedLaunchState = null;
|
||||
let sharedLaunchHandled = false;
|
||||
async function ensureIssueCapture() {
|
||||
return await issueCaptureFeatures.run('issue-capture', {
|
||||
trigger: qs('#new-issue'), status: qs('#my-work-action-status'),
|
||||
}, () => {
|
||||
if (!issueCapture) {
|
||||
issueCapture = createIssueCapture({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
}
|
||||
if (!sharedLaunchHandled && Object.values(sharedLaunch).some(Boolean)) {
|
||||
sharedLaunchState = issueCapture.stageSharedContent(sharedLaunch);
|
||||
sharedLaunchHandled = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
if (Object.values(sharedLaunch).some(Boolean)) await ensureIssueCapture();
|
||||
const pullWorkflowFeatures = createFeatureLoader({
|
||||
document,
|
||||
urls: {
|
||||
'pull-workflow': document.querySelector('meta[name="stackchain-feature-pull-workflow"]')?.content || '',
|
||||
},
|
||||
});
|
||||
let pullController = null;
|
||||
async function ensurePullWorkflow(trigger = null) {
|
||||
return await pullWorkflowFeatures.run('pull-workflow', {
|
||||
trigger, status: qs('#my-work-action-status'), retryLabel:'Tap the work card to retry.',
|
||||
}, () => {
|
||||
if (!pullController) pullController = createPullSheet({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
if (!reviewController) reviewController = createReviewController({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
if (!wrapPreference) {
|
||||
wrapPreference = createReviewController.createWrapPreference({
|
||||
storage: localStorage,
|
||||
mobile: window.matchMedia('(max-width: 600px)').matches,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
const draftInbox = createDraftInbox({ storage: localStorage, getCurrentLogin: () => activeFlushLogin });
|
||||
outboxCoordinator.subscribe(() => refreshMyWorkView());
|
||||
const offlineWorkStore = createOfflineWorkStore({ storage: localStorage, indexedDB:window.indexedDB });
|
||||
@@ -436,8 +473,13 @@
|
||||
retry.hidden = status.failed === 0;
|
||||
}
|
||||
const offlineToday = createOfflineToday({
|
||||
loadDetail: item => item.is_review ? reviewController.load(item) :
|
||||
item.kind === 'pull' ? pullController.load(item) : issueController.load(item),
|
||||
loadDetail: async item => {
|
||||
if (item.is_review || item.kind === 'pull') {
|
||||
if (!await ensurePullWorkflow()) throw new Error('Pull workspace is unavailable.');
|
||||
return item.is_review ? reviewController.load(item) : pullController.load(item);
|
||||
}
|
||||
return issueController.load(item);
|
||||
},
|
||||
loadSavedDetail: (login, item) => offlineWorkStore.loadDetail(login, item),
|
||||
saveDetail: (login, item, detail) => offlineWorkStore.saveDetail(login, item, detail),
|
||||
onStatus: renderOfflineTodayStatus,
|
||||
@@ -488,6 +530,14 @@
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function acknowledgeNotification(notificationId) {
|
||||
const response = await fetch('api/v1/notifications/' + encodeURIComponent(notificationId) +
|
||||
'/acknowledge', { method: 'POST', headers: { Accept: 'application/json' } });
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(payload.error || 'Acknowledging the update failed.');
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function markNotificationsRead(ids) {
|
||||
const response = await fetch('api/v1/notifications/read', {
|
||||
method: 'PATCH',
|
||||
@@ -566,6 +616,13 @@
|
||||
},
|
||||
onStatus: message => { qs('#my-work-action-status').textContent = message; },
|
||||
});
|
||||
const notificationSelection = createNotificationSelection({
|
||||
limit: 50,
|
||||
onChange: () => {
|
||||
bulkConfirmationPending = false;
|
||||
renderMyWork();
|
||||
},
|
||||
});
|
||||
const notificationPager = createNotificationPager({
|
||||
load: fetchNotificationPage,
|
||||
onNotifications: items => {
|
||||
@@ -654,6 +711,7 @@
|
||||
load: fetchNotificationDetail,
|
||||
loadConversation: fetchNotificationConversation,
|
||||
markRead: markNotificationRead,
|
||||
acknowledge: acknowledgeNotification,
|
||||
queueRead: notificationId => notificationReadOutbox.enqueueDurably(notificationId),
|
||||
loadSaved: item => offlineWorkStore.loadDetail(confirmedOwnerLogin, item),
|
||||
onOpen: item => {
|
||||
@@ -676,6 +734,7 @@
|
||||
qs('#update-reply-status').textContent = '';
|
||||
qs('#send-update-reply').disabled = false;
|
||||
qs('#send-update-reply-read-next').disabled = false;
|
||||
qs('#acknowledge-update-next').hidden = true;
|
||||
qs('#update-ownership-action').hidden = true;
|
||||
qs('#update-ownership-start').hidden = true;
|
||||
qs('#retry-update-load').hidden = true;
|
||||
@@ -688,6 +747,7 @@
|
||||
qs('#update-subject-state').textContent = detail.state || '';
|
||||
qs('#update-subject-body').innerHTML = renderMarkdown(detail.subject_body || 'No subject context was provided.');
|
||||
qs('#open-update-gitea').href = detail.url || selectedUpdate?.url || '#';
|
||||
qs('#acknowledge-update-next').hidden = !detail.acknowledge_supported;
|
||||
if (offlineWorkMode) {
|
||||
setOfflineUpdateControls(true);
|
||||
} else {
|
||||
@@ -1656,6 +1716,7 @@
|
||||
function setOfflineUpdateControls(offline) {
|
||||
qs('#mark-update-read-next').disabled = false;
|
||||
qs('#mark-update-read-next').textContent = offline ? 'Queue read & next' : 'Mark read & next';
|
||||
qs('#acknowledge-update-next').disabled = offline;
|
||||
qs('#update-ownership-action').disabled = offline;
|
||||
qs('#update-ownership-start').disabled = offline;
|
||||
qs('#load-older-update-comments').disabled = offline;
|
||||
@@ -2032,6 +2093,8 @@
|
||||
filterMyWork(laterMyWork, 'all', selectedWorkMilestone) :
|
||||
filterMyWork(activeMyWork, selectedWorkFilter, selectedWorkMilestone);
|
||||
const incomplete = activeWorkStreams().some(stream => workPagination[stream]?.has_more);
|
||||
const selection = notificationSelection.snapshot();
|
||||
const selectedIds = new Set(selection.ids);
|
||||
qs('#my-work-list').innerHTML = visible.length ? visible.map(item => {
|
||||
const index = lastMyWork.findIndex(candidate => candidate.key === item.key && candidate.kind === item.kind);
|
||||
const routeItem = routedWorkItem(item);
|
||||
@@ -2045,7 +2108,13 @@
|
||||
(item.has_update ? ' <span class="pill">Unread update</span>' : '') +
|
||||
(item.deferred_until ? '<span class="small">Deferred until ' + escapeHtml(fmt(item.deferred_until)) + '</span>' : '') +
|
||||
(item.updated_at ? '<span class="small"> · Updated ' + escapeHtml(fmt(item.updated_at)) + '</span>' : '');
|
||||
const markRead = item.has_update && Number.isInteger(item.notification_id) ?
|
||||
const selectable = selectedWorkFilter === 'update' && selection.active &&
|
||||
item.has_update && Number.isInteger(item.notification_id);
|
||||
const selector = selectable ?
|
||||
'<label class="update-selector"><input type="checkbox" data-select-notification-id="' + item.notification_id + '" aria-label="Select update ' + escAttr(item.key + ' ' + item.title) + '"' + (selectedIds.has(item.notification_id) ? ' checked' : '') + '> Select</label>' : '';
|
||||
const cardClasses = 'my-work-card' + (selectable ? ' selection-active' : '') +
|
||||
(selectedIds.has(item.notification_id) ? ' selected' : '');
|
||||
const markRead = item.has_update && Number.isInteger(item.notification_id) && !selection.active ?
|
||||
'<button class="mark-update-read" data-notification-id="' + item.notification_id + '">Mark read</button>' : '';
|
||||
const readUpdate = item.has_update && Number.isInteger(item.notification_id) ?
|
||||
'<a class="read-update" href="' + escAttr(createWorkRoute.serialize({ kind:'update', notification_id:item.notification_id })) + '" data-update-index="' + index + '">Read update</a>' : '';
|
||||
@@ -2061,19 +2130,30 @@
|
||||
const planningActions = selectedWorkFilter === 'later' ? laterActions :
|
||||
'<details class="card-planning" data-card-planning><summary aria-expanded="false">Plan or defer</summary><div class="card-planning-actions">' + todayActions + laterActions + '</div></details>';
|
||||
if (item.is_review) {
|
||||
return '<article class="my-work-card"><a class="my-work-card-main review-trigger" href="' + escAttr(routeHref) + '" data-review-index="' + index + '">' + contents + '</a>' + readUpdate + markRead + planningActions + '</article>';
|
||||
return '<article class="' + cardClasses + '">' + selector + '<a class="my-work-card-main review-trigger" href="' + escAttr(routeHref) + '" data-review-index="' + index + '">' + contents + '</a>' + readUpdate + markRead + planningActions + '</article>';
|
||||
}
|
||||
if (item.kind === 'issue') {
|
||||
return '<article class="my-work-card"><a class="my-work-card-main issue-trigger" href="' + escAttr(routeHref) + '" data-issue-index="' + index + '">' + contents + '</a>' + readUpdate + markRead + planningActions + '</article>';
|
||||
return '<article class="' + cardClasses + '">' + selector + '<a class="my-work-card-main issue-trigger" href="' + escAttr(routeHref) + '" data-issue-index="' + index + '">' + contents + '</a>' + readUpdate + markRead + planningActions + '</article>';
|
||||
}
|
||||
if (item.kind === 'pull') {
|
||||
return '<article class="my-work-card"><a class="my-work-card-main pull-trigger" href="' + escAttr(routeHref) + '" data-pull-index="' + index + '">' + contents + '</a>' + readUpdate + markRead + planningActions + '</article>';
|
||||
return '<article class="' + cardClasses + '">' + selector + '<a class="my-work-card-main pull-trigger" href="' + escAttr(routeHref) + '" data-pull-index="' + index + '">' + contents + '</a>' + readUpdate + markRead + planningActions + '</article>';
|
||||
}
|
||||
return '<article class="my-work-card"><a class="my-work-card-main update-trigger" href="' + escAttr(routeHref) + '" data-update-index="' + index + '">' + contents + '</a>' + markRead + planningActions + '</article>';
|
||||
return '<article class="' + cardClasses + '">' + selector + '<a class="my-work-card-main update-trigger" href="' + escAttr(routeHref) + '" data-update-index="' + index + '">' + contents + '</a>' + markRead + planningActions + '</article>';
|
||||
}).join('') : '<div class="muted">' + (incomplete ?
|
||||
'More work is available. Load the next page.' :
|
||||
'No ' + (selectedWorkFilter === 'attention' ? 'items need attention' : (selectedWorkFilter === 'review' ? 'reviews' : (selectedWorkFilter === 'update' ? 'unread updates' : (selectedWorkFilter === 'later' ? 'deferred work' : (selectedWorkFilter === 'all' ? 'work' : selectedWorkFilter + ' items'))))) + '.') + '</div>';
|
||||
cardPlanning.wire();
|
||||
document.querySelectorAll('[data-select-notification-id]').forEach(input => {
|
||||
input.addEventListener('change', () => {
|
||||
const notificationId = Number(input.dataset.selectNotificationId);
|
||||
const result = input.checked ? notificationSelection.select(notificationId) :
|
||||
notificationSelection.toggle(notificationId);
|
||||
if (result === 'limit') {
|
||||
input.checked = false;
|
||||
qs('#my-work-action-status').textContent = 'Select up to 50 updates per batch.';
|
||||
}
|
||||
});
|
||||
});
|
||||
document.querySelectorAll('[data-review-index]').forEach(button => {
|
||||
button.addEventListener('click', event => { event.preventDefault(); openRoutedWork(lastMyWork[Number(button.dataset.reviewIndex)], button); });
|
||||
});
|
||||
@@ -2192,20 +2272,22 @@
|
||||
document.querySelector('[data-today-move="' + button.dataset.todayMove + '"][data-work-index="' + button.dataset.workIndex + '"]')?.focus();
|
||||
});
|
||||
});
|
||||
const allIds = notificationIds(visible);
|
||||
const ids = allIds.slice(0, Math.min(lastNotifications.length, 50));
|
||||
const bulkBar = qs('#bulk-mark-read-bar');
|
||||
const bulkButton = qs('#bulk-mark-read');
|
||||
bulkBar.hidden = selectedWorkFilter !== 'update' || ids.length === 0;
|
||||
const updateIds = notificationIds(visible);
|
||||
const selectionControls = qs('#update-selection-controls');
|
||||
selectionControls.hidden = selectedWorkFilter !== 'update' || updateIds.length === 0;
|
||||
qs('#select-updates').hidden = selection.active;
|
||||
qs('#cancel-update-selection').hidden = !selection.active;
|
||||
qs('#update-selection-status').textContent = selection.active ?
|
||||
selection.count + ' of 50 selected' : 'Choose specific updates to keep important work unread.';
|
||||
bulkBar.hidden = selectedWorkFilter !== 'update' || !selection.active;
|
||||
qs('#load-more-notifications').hidden =
|
||||
selectedWorkFilter !== 'update' || !notificationPagination.has_more;
|
||||
bulkButton.disabled = bulkMarkPending;
|
||||
const bulkLabel = allIds.length > ids.length ?
|
||||
'next ' + ids.length + ' of ' + allIds.length + ' loaded updates' :
|
||||
'all ' + ids.length + ' updates';
|
||||
bulkButton.disabled = bulkMarkPending || selection.count === 0;
|
||||
bulkButton.textContent = bulkConfirmationPending ?
|
||||
'Confirm marking ' + bulkLabel + ' read' :
|
||||
'Mark ' + bulkLabel + ' read';
|
||||
'Confirm marking ' + selection.count + ' selected read' :
|
||||
'Mark ' + selection.count + ' selected read';
|
||||
workRoute.setItems(lastMyWork);
|
||||
}
|
||||
|
||||
@@ -2556,6 +2638,7 @@
|
||||
|
||||
async function openPullSheet(item, trigger, offlineDetail = null) {
|
||||
if (!item) return;
|
||||
if (!await ensurePullWorkflow(trigger)) return;
|
||||
if (!sameWorkTarget(selectedPull, item)) pullAttachmentController.clear();
|
||||
qs('#pull-review').inert = false;
|
||||
selectedPull = item;
|
||||
@@ -2759,6 +2842,7 @@
|
||||
}
|
||||
|
||||
function saveIssueCaptureDraft() {
|
||||
if (!issueCapture) return;
|
||||
issueCapture.saveDraft({
|
||||
repository: qs('#create-issue-repository').value,
|
||||
title: qs('#create-issue-title').value,
|
||||
@@ -2955,7 +3039,8 @@
|
||||
sharedLaunchState = null;
|
||||
}
|
||||
|
||||
function openCreateIssueSheet(navigate = true) {
|
||||
async function openCreateIssueSheet(navigate = true) {
|
||||
if (!issueCapture && !await ensureIssueCapture()) return;
|
||||
if (navigate) {
|
||||
taskOverlayHistory.open('new');
|
||||
return;
|
||||
@@ -3110,6 +3195,7 @@
|
||||
}
|
||||
|
||||
async function openReviewSheet(item, trigger, cachedDetail = null) {
|
||||
if (!item || !await ensurePullWorkflow(trigger)) return;
|
||||
selectedReview = item;
|
||||
reviewTrigger = trigger;
|
||||
offlineReview = Boolean(cachedDetail);
|
||||
@@ -4674,6 +4760,16 @@
|
||||
qs('#mark-update-read-next').disabled = false;
|
||||
}
|
||||
});
|
||||
qs('#acknowledge-update-next').addEventListener('click', async () => {
|
||||
const button = qs('#acknowledge-update-next');
|
||||
button.disabled = true;
|
||||
try {
|
||||
const result = await notificationReader.acknowledgeAndNext(lastMyWork);
|
||||
if (result) qs('#my-work-action-status').textContent = 'Update acknowledged with 👍.';
|
||||
} finally {
|
||||
button.disabled = offlineWorkMode;
|
||||
}
|
||||
});
|
||||
qs('#close-review-sheet').addEventListener('click', closeReviewSheet);
|
||||
qs('#retry-review-load').addEventListener('click', () => {
|
||||
if (selectedReview) openReviewSheet(selectedReview, reviewTrigger);
|
||||
@@ -5093,32 +5189,44 @@
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
qs('#select-updates').addEventListener('click', () => {
|
||||
notificationSelection.start();
|
||||
qs('#update-selection-status').textContent = '0 of 50 selected';
|
||||
document.querySelector('[data-select-notification-id]')?.focus();
|
||||
});
|
||||
qs('#cancel-update-selection').addEventListener('click', () => {
|
||||
notificationSelection.cancel();
|
||||
qs('#select-updates').focus();
|
||||
});
|
||||
qs('#bulk-mark-read').addEventListener('click', async () => {
|
||||
const allIds = notificationIds(filterMyWork(lastMyWork, 'update'));
|
||||
const ids = allIds.slice(0, 50);
|
||||
if (!ids.length || bulkMarkPending) return;
|
||||
const selection = notificationSelection.snapshot();
|
||||
if (!selection.ids.length || bulkMarkPending) return;
|
||||
if (!bulkConfirmationPending) {
|
||||
bulkConfirmationPending = true;
|
||||
qs('#my-work-action-status').textContent = 'Confirm to mark all visible updates read.';
|
||||
qs('#my-work-action-status').textContent = 'Confirm to mark only the selected updates read.';
|
||||
renderMyWork();
|
||||
return;
|
||||
}
|
||||
bulkConfirmationPending = false;
|
||||
bulkMarkPending = true;
|
||||
renderMyWork();
|
||||
const result = await bulkNotificationAcknowledger.acknowledge(lastMyWork, ids);
|
||||
const result = await bulkNotificationAcknowledger.acknowledge(lastMyWork, selection.ids);
|
||||
if (result) {
|
||||
const marked = new Set(result.marked);
|
||||
lastNotifications = lastNotifications.filter(item => !marked.has(item.id));
|
||||
notificationSelection.retain(result.failed);
|
||||
if (!result.failed.length) notificationSelection.cancel();
|
||||
}
|
||||
bulkMarkPending = false;
|
||||
renderMyWork();
|
||||
(document.querySelector('[data-notification-id]') || qs('[data-work-filter="update"]'))?.focus();
|
||||
(document.querySelector('[data-select-notification-id]') || qs('#select-updates'))?.focus();
|
||||
});
|
||||
document.querySelectorAll('[data-work-filter]').forEach(button => {
|
||||
button.setAttribute('aria-pressed', String(button.dataset.workFilter === selectedWorkFilter));
|
||||
button.addEventListener('click', () => {
|
||||
const leavingUpdates = selectedWorkFilter === 'update' && button.dataset.workFilter !== 'update';
|
||||
selectedWorkFilter = button.dataset.workFilter;
|
||||
if (leavingUpdates && notificationSelection.snapshot().active) notificationSelection.cancel();
|
||||
savedWorkFilter = selectedWorkFilter;
|
||||
launchFilterResolved = true;
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
function createFeatureLoader({ document, urls, timeoutMs = 10000 }) {
|
||||
const pending = new Map();
|
||||
const loaded = new Set();
|
||||
|
||||
function load(name) {
|
||||
if (loaded.has(name)) return Promise.resolve();
|
||||
if (pending.has(name)) return pending.get(name);
|
||||
const url = urls[name];
|
||||
if (!url) return Promise.reject(new Error('Unknown feature: ' + name));
|
||||
|
||||
const request = new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
let timeout;
|
||||
const fail = () => {
|
||||
clearTimeout(timeout);
|
||||
script.remove();
|
||||
pending.delete(name);
|
||||
reject(new Error('Could not load ' + name.replace(/-/g, ' ') + '.'));
|
||||
};
|
||||
script.src = url;
|
||||
script.async = true;
|
||||
script.onload = () => {
|
||||
clearTimeout(timeout);
|
||||
pending.delete(name);
|
||||
loaded.add(name);
|
||||
resolve();
|
||||
};
|
||||
script.onerror = fail;
|
||||
timeout = setTimeout(fail, timeoutMs);
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
pending.set(name, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
async function run(name, elements, callback) {
|
||||
const trigger = elements?.trigger;
|
||||
const status = elements?.status;
|
||||
const retryLabel = elements?.retryLabel || 'Tap New issue to retry.';
|
||||
if (trigger) trigger.disabled = true;
|
||||
if (status) status.textContent = 'Loading ' + name.replace(/-/g, ' ') + '…';
|
||||
try {
|
||||
await load(name);
|
||||
callback();
|
||||
if (status) status.textContent = '';
|
||||
return true;
|
||||
} catch (_error) {
|
||||
if (status) {
|
||||
const label = name === 'issue-capture' ? 'Issue capture' :
|
||||
name === 'pull-workflow' ? 'Pull workspace' : name.replace(/-/g, ' ');
|
||||
status.textContent = label + ' could not load. ' + retryLabel;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (trigger) trigger.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
return { load, run, ready: name => loaded.has(name) };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createFeatureLoader;
|
||||
@@ -116,6 +116,11 @@
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="update-selection-controls" id="update-selection-controls" hidden>
|
||||
<button id="select-updates" type="button">Select updates</button>
|
||||
<button id="cancel-update-selection" type="button" hidden>Cancel selection</button>
|
||||
<span class="small" id="update-selection-status" role="status" aria-live="polite"></span>
|
||||
</div>
|
||||
<div class="my-work-list" id="my-work-list"></div>
|
||||
<div class="small" id="work-page-status" aria-live="polite"></div>
|
||||
<button class="load-more-work" id="load-more-work" type="button" hidden>Load older work</button>
|
||||
@@ -548,6 +553,7 @@
|
||||
<button id="update-ownership-start" type="button" hidden aria-describedby="update-sheet-status">Take ownership & start</button>
|
||||
</div>
|
||||
<button class="share-work-route" type="button">Share</button>
|
||||
<button id="acknowledge-update-next" type="button" hidden aria-label="Acknowledge and open next update">👍 Acknowledge & next</button>
|
||||
<button id="mark-update-read-next" type="button">Mark read & next</button>
|
||||
<a id="open-update-gitea" href="#" target="_blank" rel="noopener noreferrer">Open in Gitea</a>
|
||||
<details class="detail-defer"><summary>Defer</summary><div class="detail-defer-options"><button type="button" data-detail-defer-preset="today" disabled data-planning-disabled>Later today</button><button type="button" data-detail-defer-preset="tomorrow" disabled data-planning-disabled>Tomorrow</button><button type="button" data-detail-defer-custom disabled data-planning-disabled>Choose date & time</button><button type="button" data-detail-defer-cancel>Cancel</button></div></details>
|
||||
@@ -718,6 +724,7 @@
|
||||
<div class="footer">Creative AI-imbued UI • stackchain-dashboard</div>
|
||||
|
||||
<script src="static/session.js"></script>
|
||||
<script src="static/feature-loader.js"></script>
|
||||
<script src="static/markdown.js"></script>
|
||||
<script src="static/commands.js"></script>
|
||||
<script src="static/search-preview.js"></script>
|
||||
|
||||
@@ -178,6 +178,62 @@ function createBulkNotificationAcknowledger({ markRead, onItems, onStatus }) {
|
||||
};
|
||||
}
|
||||
|
||||
function createNotificationSelection({ limit = 50, onChange = () => {} } = {}) {
|
||||
const maximum = Number.isInteger(limit) && limit > 0 ? limit : 50;
|
||||
let active = false;
|
||||
const selected = new Set();
|
||||
const snapshot = () => ({
|
||||
active,
|
||||
ids: Array.from(selected),
|
||||
count: selected.size,
|
||||
limit: maximum,
|
||||
at_limit: selected.size >= maximum,
|
||||
});
|
||||
const publish = () => onChange(snapshot());
|
||||
const select = notificationId => {
|
||||
if (!active || !Number.isInteger(notificationId)) return 'inactive';
|
||||
if (selected.has(notificationId)) return 'already-selected';
|
||||
if (selected.size >= maximum) return 'limit';
|
||||
selected.add(notificationId);
|
||||
publish();
|
||||
return 'selected';
|
||||
};
|
||||
return {
|
||||
start() {
|
||||
if (active) return snapshot();
|
||||
active = true;
|
||||
publish();
|
||||
return snapshot();
|
||||
},
|
||||
select,
|
||||
toggle(notificationId) {
|
||||
if (!selected.has(notificationId)) return select(notificationId);
|
||||
selected.delete(notificationId);
|
||||
publish();
|
||||
return 'deselected';
|
||||
},
|
||||
retain(notificationIds) {
|
||||
const allowed = new Set((notificationIds || []).filter(Number.isInteger));
|
||||
let changed = false;
|
||||
selected.forEach(id => {
|
||||
if (!allowed.has(id)) {
|
||||
selected.delete(id);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if (changed) publish();
|
||||
return snapshot();
|
||||
},
|
||||
cancel() {
|
||||
active = false;
|
||||
selected.clear();
|
||||
publish();
|
||||
return snapshot();
|
||||
},
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
|
||||
function createNotificationPager({ load, onNotifications, onPagination, onStatus }) {
|
||||
let pagination = { page: 1, total: 0, has_more: false };
|
||||
let pending = false;
|
||||
@@ -280,6 +336,7 @@ function createWorkPager({ load, onItems, onPagination, onStatus }) {
|
||||
|
||||
function createNotificationReader({
|
||||
load, markRead, onOpen, onDetail, onItems, onStatus, onClose,
|
||||
acknowledge = null,
|
||||
queueRead = null,
|
||||
loadSaved = () => null,
|
||||
loadConversation = null,
|
||||
@@ -382,6 +439,21 @@ function createNotificationReader({
|
||||
marking = false;
|
||||
}
|
||||
},
|
||||
async acknowledgeAndNext(items) {
|
||||
if (!selected || marking || offlineHydrated || !acknowledge) return false;
|
||||
const current = selected;
|
||||
marking = true;
|
||||
onStatus('Adding reaction and marking read…');
|
||||
try {
|
||||
await acknowledge(current.notification_id);
|
||||
return await advanceAfterRead(items, current);
|
||||
} catch (_error) {
|
||||
onStatus('Could not acknowledge update. Retry.');
|
||||
return false;
|
||||
} finally {
|
||||
marking = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -766,6 +838,7 @@ if (typeof module !== 'undefined' && module.exports) {
|
||||
buildMyWork.createNotificationAcknowledger = createNotificationAcknowledger;
|
||||
buildMyWork.notificationIds = notificationIds;
|
||||
buildMyWork.createBulkNotificationAcknowledger = createBulkNotificationAcknowledger;
|
||||
buildMyWork.createNotificationSelection = createNotificationSelection;
|
||||
buildMyWork.createNotificationPager = createNotificationPager;
|
||||
buildMyWork.createWorkPager = createWorkPager;
|
||||
buildMyWork.createNotificationReader = createNotificationReader;
|
||||
|
||||
@@ -12,6 +12,7 @@ const SHELL = [
|
||||
BASE + 'static/icons/stackchain-192.png',
|
||||
BASE + 'static/icons/stackchain-512.png',
|
||||
BASE + 'static/session.js',
|
||||
BASE + 'static/feature-loader.js',
|
||||
BASE + 'static/markdown.js',
|
||||
BASE + 'static/commands.js',
|
||||
BASE + 'static/search-preview.js',
|
||||
|
||||
@@ -142,6 +142,20 @@
|
||||
}
|
||||
try {
|
||||
const page = await boundary.listSecurityEvents(append ? activityCursor : null);
|
||||
if (!append) {
|
||||
page.authentication_alerts.forEach(alert => {
|
||||
const row = root.document.createElement('article');
|
||||
row.className = 'security-event authentication-alert';
|
||||
const formatted = boundary.formatAuthenticationAlert(alert);
|
||||
const title = root.document.createElement('strong');
|
||||
title.textContent = formatted.title;
|
||||
const details = root.document.createElement('span');
|
||||
details.className = 'small muted';
|
||||
details.textContent = formatted.detail;
|
||||
row.append(title, details);
|
||||
activityList.append(row);
|
||||
});
|
||||
}
|
||||
const labels = {
|
||||
sign_in: 'Signed in',
|
||||
sign_out: 'Signed out',
|
||||
@@ -665,6 +679,21 @@
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function formatAuthenticationAlert(alert) {
|
||||
const failed = Math.max(0, Number(alert?.failed_count) || 0);
|
||||
const blocked = Math.max(0, Number(alert?.blocked_count) || 0);
|
||||
const method = alert?.method === 'passkey' ? 'passkey' : 'token';
|
||||
const title = `${failed} failed ${method} sign-in${failed === 1 ? '' : 's'}`
|
||||
+ (blocked ? ` · ${blocked} blocked` : '');
|
||||
const formatTime = value => new Date(Number(value) * 1000).toLocaleString(
|
||||
'en-US', { timeZone: 'UTC' },
|
||||
);
|
||||
return {
|
||||
title,
|
||||
detail: `${formatTime(alert?.first_at)} – ${formatTime(alert?.last_at)}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function listSecurityEvents(cursor = null) {
|
||||
const query = new URLSearchParams({ limit: '25' });
|
||||
if (Number.isInteger(cursor) && cursor > 0) query.set('cursor', String(cursor));
|
||||
@@ -673,6 +702,8 @@
|
||||
const payload = await response.json();
|
||||
return {
|
||||
events: Array.isArray(payload.events) ? payload.events : [],
|
||||
authentication_alerts: Array.isArray(payload.authentication_alerts)
|
||||
? payload.authentication_alerts : [],
|
||||
next_cursor: Number.isInteger(payload.next_cursor) ? payload.next_cursor : null,
|
||||
};
|
||||
}
|
||||
@@ -722,6 +753,7 @@
|
||||
listActiveDevices,
|
||||
listPasskeys,
|
||||
listSecurityEvents,
|
||||
formatAuthenticationAlert,
|
||||
enrollPasskey,
|
||||
revokeActiveDevice,
|
||||
revokePasskey,
|
||||
|
||||
+47
-11
@@ -13,11 +13,23 @@ import rjsmin
|
||||
|
||||
SCRIPT_TAG = re.compile(r'^<script src="(static/[^"?]+\.js)"></script>$', re.MULTILINE)
|
||||
WORKER_RUNTIME_SOURCE = "static/background-issue-sync.js"
|
||||
FEATURE_SOURCES = {
|
||||
"issue-capture": ("static/create-issue-sheet.js",),
|
||||
"pull-workflow": ("static/pull-sheet.js", "static/review-sheet.js"),
|
||||
}
|
||||
CACHE_DECLARATION = re.compile(
|
||||
r"const CACHE = 'stackchain-dashboard-shell-(?:v\d+|[0-9a-f]{16})';"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeBundle:
|
||||
runtime_bytes: bytes
|
||||
runtime_gzip_bytes: bytes
|
||||
runtime_digest: str
|
||||
runtime_name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FrontendBuild:
|
||||
dashboard_html: str
|
||||
@@ -27,6 +39,7 @@ class FrontendBuild:
|
||||
runtime_name: str
|
||||
shell_digest: str
|
||||
page_sources: tuple[str, ...]
|
||||
feature_bundles: dict[str, RuntimeBundle]
|
||||
service_worker_source: str
|
||||
|
||||
|
||||
@@ -41,6 +54,17 @@ def _bundle(frontend_dir: Path, sources: tuple[str, ...]) -> bytes:
|
||||
return minified + f';"source-sha256:{revision}";'.encode()
|
||||
|
||||
|
||||
def _runtime(frontend_dir: Path, sources: tuple[str, ...], prefix: str) -> RuntimeBundle:
|
||||
content = _bundle(frontend_dir, sources)
|
||||
digest = hashlib.sha256(content).hexdigest()[:16]
|
||||
return RuntimeBundle(
|
||||
runtime_bytes=content,
|
||||
runtime_gzip_bytes=gzip.compress(content, compresslevel=6, mtime=0),
|
||||
runtime_digest=digest,
|
||||
runtime_name=f"{prefix}-{digest}.js",
|
||||
)
|
||||
|
||||
|
||||
def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
"""Return one internally consistent HTML, runtime, and offline-worker build."""
|
||||
source_html = (frontend_dir / "index.html").read_text()
|
||||
@@ -48,13 +72,21 @@ def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
if not sources:
|
||||
raise ValueError("dashboard entry document has no page scripts")
|
||||
|
||||
runtime = _bundle(frontend_dir, sources)
|
||||
runtime_gzip = gzip.compress(runtime, compresslevel=6, mtime=0)
|
||||
digest = hashlib.sha256(runtime).hexdigest()[:16]
|
||||
runtime_name = f"runtime-{digest}.js"
|
||||
feature_source_names = {source for group in FEATURE_SOURCES.values() for source in group}
|
||||
core_sources = tuple(source for source in sources if source not in feature_source_names)
|
||||
core = _runtime(frontend_dir, core_sources, "runtime")
|
||||
feature_bundles = {
|
||||
name: _runtime(frontend_dir, feature_sources, f"feature-{name}")
|
||||
for name, feature_sources in FEATURE_SOURCES.items()
|
||||
}
|
||||
dashboard_html = SCRIPT_TAG.sub("", source_html)
|
||||
feature_metadata = "\n".join(
|
||||
f'<meta name="stackchain-feature-{name}" content="{bundle.runtime_name}">'
|
||||
for name, bundle in feature_bundles.items()
|
||||
)
|
||||
dashboard_html = dashboard_html.replace("</head>", feature_metadata + "\n</head>")
|
||||
dashboard_html = dashboard_html.replace(
|
||||
"</body>", f'<script src="{runtime_name}"></script>\n</body>'
|
||||
"</body>", f'<script src="{core.runtime_name}"></script>\n</body>'
|
||||
)
|
||||
|
||||
worker = (frontend_dir / "service-worker.js").read_text()
|
||||
@@ -63,7 +95,9 @@ def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
worker = worker.replace(f" BASE + '{source}',\n", "")
|
||||
worker = worker.replace(
|
||||
" BASE + 'static/dashboard.css',\n",
|
||||
f" BASE + 'static/dashboard.css',\n BASE + '{runtime_name}',\n",
|
||||
" BASE + 'static/dashboard.css',\n"
|
||||
+ f" BASE + '{core.runtime_name}',\n"
|
||||
+ "".join(f" BASE + '{bundle.runtime_name}',\n" for bundle in feature_bundles.values()),
|
||||
)
|
||||
worker = CACHE_DECLARATION.sub(
|
||||
"const CACHE = 'stackchain-dashboard-shell-BUILD';", worker, count=1
|
||||
@@ -72,7 +106,8 @@ def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
shell_hasher = hashlib.sha256()
|
||||
shell_inputs = (
|
||||
("dashboard.html", dashboard_html.encode()),
|
||||
(runtime_name, runtime),
|
||||
(core.runtime_name, core.runtime_bytes),
|
||||
*((bundle.runtime_name, bundle.runtime_bytes) for bundle in feature_bundles.values()),
|
||||
("static/dashboard.css", (frontend_dir / "dashboard.css").read_bytes()),
|
||||
("manifest.webmanifest", (frontend_dir / "manifest.webmanifest").read_bytes()),
|
||||
(
|
||||
@@ -105,11 +140,12 @@ def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
|
||||
return FrontendBuild(
|
||||
dashboard_html=dashboard_html,
|
||||
runtime_bytes=runtime,
|
||||
runtime_gzip_bytes=runtime_gzip,
|
||||
runtime_digest=digest,
|
||||
runtime_name=runtime_name,
|
||||
runtime_bytes=core.runtime_bytes,
|
||||
runtime_gzip_bytes=core.runtime_gzip_bytes,
|
||||
runtime_digest=core.runtime_digest,
|
||||
runtime_name=core.runtime_name,
|
||||
shell_digest=shell_digest,
|
||||
page_sources=sources,
|
||||
feature_bundles=feature_bundles,
|
||||
service_worker_source=worker,
|
||||
)
|
||||
@@ -735,6 +735,60 @@ async def mark_notification_read(thread_id: int) -> None:
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
async def acknowledge_notification(thread_id: int) -> dict:
|
||||
thread = await fetch(f"notifications/threads/{thread_id}")
|
||||
if not isinstance(thread, dict):
|
||||
raise ValueError("Gitea notification thread response was not an object")
|
||||
repository = thread.get("repository")
|
||||
subject = thread.get("subject")
|
||||
if not isinstance(repository, dict) or not isinstance(subject, dict):
|
||||
raise ValueError("Notification does not identify a conversation")
|
||||
repository_name = repository.get("full_name")
|
||||
subject_path = _gitea_api_path(subject.get("url"))
|
||||
comment_path = _gitea_api_path(subject.get("latest_comment_url"))
|
||||
subject_match = re.fullmatch(
|
||||
r"repos/([^/]+/[^/]+)/(issues|pulls)/(\d+)", subject_path
|
||||
)
|
||||
comment_match = re.fullmatch(
|
||||
r"repos/([^/]+/[^/]+)/issues/comments/(\d+)", comment_path
|
||||
)
|
||||
if (
|
||||
not subject_match
|
||||
or not comment_match
|
||||
or subject_match.group(1) != repository_name
|
||||
or comment_match.group(1) != repository_name
|
||||
or subject.get("type") not in {"Issue", "Pull"}
|
||||
):
|
||||
raise ValueError("Notification has no supported latest comment")
|
||||
|
||||
user = await current_user()
|
||||
login = user.get("login") if isinstance(user, dict) else None
|
||||
if not isinstance(login, str) or not login:
|
||||
raise ValueError("Authenticated Gitea user is unavailable")
|
||||
reaction_path = f"/api/v1/{comment_path}/reactions"
|
||||
response = await _get_client().get(reaction_path, headers=_auth())
|
||||
response.raise_for_status()
|
||||
reactions = response.json()
|
||||
existing = any(
|
||||
isinstance(reaction, dict)
|
||||
and reaction.get("content") == "+1"
|
||||
and isinstance(reaction.get("user"), dict)
|
||||
and reaction["user"].get("login") == login
|
||||
for reaction in (reactions if isinstance(reactions, list) else [])
|
||||
)
|
||||
if not existing:
|
||||
response = await _get_client().post(
|
||||
reaction_path, headers=_auth(), json={"content": "+1"}
|
||||
)
|
||||
response.raise_for_status()
|
||||
await mark_notification_read(thread_id)
|
||||
return {
|
||||
"id": thread_id,
|
||||
"reaction": "existing" if existing else "created",
|
||||
"status": "read",
|
||||
}
|
||||
|
||||
|
||||
def _gitea_api_path(value: Any) -> str:
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
@@ -763,6 +817,9 @@ async def notification_detail(thread_id: int) -> dict:
|
||||
conversation_match = re.fullmatch(
|
||||
r"repos/([^/]+/[^/]+)/(issues|pulls)/(\d+)", subject_path
|
||||
)
|
||||
comment_match = re.fullmatch(
|
||||
r"repos/([^/]+/[^/]+)/issues/comments/(\d+)", comment_path
|
||||
)
|
||||
repository_name = repository.get("full_name")
|
||||
supported_conversation = (
|
||||
conversation_match
|
||||
@@ -838,6 +895,11 @@ async def notification_detail(thread_id: int) -> dict:
|
||||
"url": latest_url,
|
||||
},
|
||||
"issue": issue,
|
||||
"acknowledge_supported": bool(
|
||||
supported_conversation
|
||||
and comment_match
|
||||
and comment_match.group(1) == repository_name
|
||||
),
|
||||
"conversation": conversation,
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,9 @@ class LoginAttemptStore:
|
||||
window_seconds: int,
|
||||
max_entries: int = 10_000,
|
||||
lock_timeout_seconds: float = 0.1,
|
||||
alert_bucket_seconds: int = 60 * 60,
|
||||
alert_retention_seconds: int = 30 * 24 * 60 * 60,
|
||||
max_alert_buckets: int = 720,
|
||||
) -> None:
|
||||
self.path = Path(path)
|
||||
self.clock = clock
|
||||
@@ -56,6 +59,9 @@ class LoginAttemptStore:
|
||||
self.window_seconds = max(1, window_seconds)
|
||||
self.max_entries = max(1, max_entries)
|
||||
self.lock_timeout_seconds = lock_timeout_seconds
|
||||
self.alert_bucket_seconds = max(1, alert_bucket_seconds)
|
||||
self.alert_retention_seconds = max(1, alert_retention_seconds)
|
||||
self.max_alert_buckets = max(1, max_alert_buckets)
|
||||
|
||||
@staticmethod
|
||||
def _digest(source: str) -> str:
|
||||
@@ -85,6 +91,19 @@ class LoginAttemptStore:
|
||||
)
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS login_alerts (
|
||||
method TEXT NOT NULL,
|
||||
bucket_started_at INTEGER NOT NULL,
|
||||
failed_count INTEGER NOT NULL DEFAULT 0,
|
||||
blocked_count INTEGER NOT NULL DEFAULT 0,
|
||||
first_at INTEGER NOT NULL,
|
||||
last_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (method, bucket_started_at)
|
||||
)
|
||||
"""
|
||||
)
|
||||
return connection
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
raise LoginAttemptStoreError(
|
||||
@@ -154,7 +173,35 @@ class LoginAttemptStore:
|
||||
"Sign-in throttling is temporarily unavailable"
|
||||
) from exc
|
||||
|
||||
def record_failure(self, source: str) -> None:
|
||||
def _record_alert(
|
||||
self, connection: sqlite3.Connection, method: str, *, blocked: bool, now: float
|
||||
) -> None:
|
||||
safe_method = method if method in {"token", "passkey"} else "unknown"
|
||||
occurred_at = int(now)
|
||||
bucket = occurred_at - (occurred_at % self.alert_bucket_seconds)
|
||||
failed = 0 if blocked else 1
|
||||
blocked_count = 1 if blocked else 0
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO login_alerts(
|
||||
method, bucket_started_at, failed_count, blocked_count, first_at, last_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(method, bucket_started_at) DO UPDATE SET
|
||||
failed_count = failed_count + excluded.failed_count,
|
||||
blocked_count = blocked_count + excluded.blocked_count,
|
||||
first_at = MIN(first_at, excluded.first_at),
|
||||
last_at = MAX(last_at, excluded.last_at)
|
||||
""",
|
||||
(safe_method, bucket, failed, blocked_count, occurred_at, occurred_at),
|
||||
)
|
||||
connection.execute(
|
||||
"DELETE FROM login_alerts WHERE (method, bucket_started_at) NOT IN "
|
||||
"(SELECT method, bucket_started_at FROM login_alerts "
|
||||
"ORDER BY bucket_started_at DESC LIMIT ?)",
|
||||
(self.max_alert_buckets,),
|
||||
)
|
||||
|
||||
def record_failure(self, source: str, *, method: str = "token") -> None:
|
||||
now = self.clock()
|
||||
source_hash = self._digest(source)
|
||||
try:
|
||||
@@ -188,11 +235,52 @@ class LoginAttemptStore:
|
||||
""",
|
||||
(self.max_entries,),
|
||||
)
|
||||
self._record_alert(connection, method, blocked=False, now=now)
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
raise LoginAttemptStoreError(
|
||||
"Sign-in throttling is temporarily unavailable"
|
||||
) from exc
|
||||
|
||||
def record_blocked(self, *, method: str = "token") -> None:
|
||||
now = self.clock()
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
self._record_alert(connection, method, blocked=True, now=now)
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
raise LoginAttemptStoreError(
|
||||
"Sign-in throttling is temporarily unavailable"
|
||||
) from exc
|
||||
|
||||
def list_alerts(self, *, limit: int = 24) -> list[dict[str, int | str]]:
|
||||
bounded_limit = min(100, max(1, limit))
|
||||
now = int(self.clock())
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
connection.execute(
|
||||
"DELETE FROM login_alerts WHERE last_at < ?",
|
||||
(now - self.alert_retention_seconds,),
|
||||
)
|
||||
rows = connection.execute(
|
||||
"SELECT method, failed_count, blocked_count, first_at, last_at "
|
||||
"FROM login_alerts ORDER BY bucket_started_at DESC LIMIT ?",
|
||||
(bounded_limit,),
|
||||
).fetchall()
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
raise LoginAttemptStoreError(
|
||||
"Sign-in throttling is temporarily unavailable"
|
||||
) from exc
|
||||
return [
|
||||
{
|
||||
"method": row[0],
|
||||
"failed_count": row[1],
|
||||
"blocked_count": row[2],
|
||||
"first_at": row[3],
|
||||
"last_at": row[4],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def clear(self, source: str) -> None:
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
|
||||
+41
-1
@@ -947,6 +947,14 @@ async def sign_in(payload: DashboardSignIn, request: Request, response: Response
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
if retry_after:
|
||||
try:
|
||||
await asyncio.to_thread(attempts.record_blocked, method="token")
|
||||
except LoginAttemptStoreError:
|
||||
return JSONResponse(
|
||||
{"detail": "Sign-in throttling is temporarily unavailable"},
|
||||
status_code=503,
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
return JSONResponse(
|
||||
{"detail": "Too many sign-in attempts"},
|
||||
status_code=429,
|
||||
@@ -1034,7 +1042,10 @@ async def list_security_events(
|
||||
page = await asyncio.to_thread(
|
||||
_security_event_store().list, limit=limit, cursor=cursor
|
||||
)
|
||||
except SecurityEventStoreError:
|
||||
authentication_alerts = await asyncio.to_thread(
|
||||
_login_attempt_store().list_alerts, limit=24
|
||||
)
|
||||
except (SecurityEventStoreError, LoginAttemptStoreError):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Security activity is temporarily unavailable"
|
||||
)
|
||||
@@ -1052,6 +1063,7 @@ async def list_security_events(
|
||||
}
|
||||
for event in page.events
|
||||
],
|
||||
"authentication_alerts": authentication_alerts,
|
||||
"next_cursor": page.next_cursor,
|
||||
},
|
||||
headers={"Cache-Control": "no-store"},
|
||||
@@ -3066,6 +3078,34 @@ async def read_notification(thread_id: int = PathParam(gt=0)) -> JSONResponse:
|
||||
return JSONResponse({"id": thread_id, "status": "read"})
|
||||
|
||||
|
||||
@app.post("/api/v1/notifications/{thread_id}/acknowledge")
|
||||
async def acknowledge_notification(thread_id: int = PathParam(gt=0)) -> JSONResponse:
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
gitea_proxy.acknowledge_notification(thread_id),
|
||||
timeout=NOTIFICATION_MUTATION_TIMEOUT_SECONDS,
|
||||
)
|
||||
except TimeoutError:
|
||||
return JSONResponse(
|
||||
{"error": "Acknowledging the update timed out. Please retry."},
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
except ValueError:
|
||||
return JSONResponse(
|
||||
{"error": "This update has no comment that can be acknowledged."},
|
||||
status_code=422,
|
||||
)
|
||||
except Exception:
|
||||
return JSONResponse(
|
||||
{"error": "The update could not be acknowledged. Please retry."},
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
await _remove_notifications_from_live_snapshot([thread_id])
|
||||
return JSONResponse(result)
|
||||
|
||||
|
||||
@app.post("/api/v1/notifications/{thread_id}/reply", status_code=201)
|
||||
async def reply_to_notification(
|
||||
reply: NotificationReply,
|
||||
|
||||
@@ -69,3 +69,20 @@ async def runtime_bundle(digest: str, request: Request) -> Response:
|
||||
**({"Content-Encoding": "gzip"} if accepts_gzip else {}),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/feature-{name}-{digest}.js")
|
||||
async def feature_bundle(name: str, digest: str, request: Request) -> Response:
|
||||
bundle = FRONTEND_BUILD.feature_bundles.get(name)
|
||||
if bundle is None or digest != bundle.runtime_digest:
|
||||
raise HTTPException(status_code=404, detail="Feature revision not found")
|
||||
accepts_gzip = _quality(request.headers.get("Accept-Encoding", ""), "gzip") > 0
|
||||
return Response(
|
||||
bundle.runtime_gzip_bytes if accepts_gzip else bundle.runtime_bytes,
|
||||
media_type="application/javascript",
|
||||
headers={
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
"Vary": "Accept-Encoding",
|
||||
**({"Content-Encoding": "gzip"} if accepts_gzip else {}),
|
||||
},
|
||||
)
|
||||
@@ -825,6 +825,44 @@ async def test_sign_in_throttles_repeated_failures_with_retry_guidance(access_co
|
||||
assert blocked.headers["cache-control"] == "no-store"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_security_activity_surfaces_failed_and_blocked_token_sign_ins(access_control):
|
||||
attacker_transport = httpx.ASGITransport(app=main.app, client=("203.0.113.7", 1234))
|
||||
operator_transport = httpx.ASGITransport(app=main.app, client=("198.51.100.4", 1234))
|
||||
async with httpx.AsyncClient(
|
||||
transport=attacker_transport, base_url="https://test"
|
||||
) as attacker:
|
||||
failures = [
|
||||
await attacker.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "wrong", "device_label": "Unknown"},
|
||||
)
|
||||
for _ in range(4)
|
||||
]
|
||||
async with httpx.AsyncClient(
|
||||
transport=operator_transport, base_url="https://test"
|
||||
) as operator:
|
||||
signed_in = await operator.post(
|
||||
"/api/v1/session",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"device_label": "Phone",
|
||||
},
|
||||
)
|
||||
activity = await operator.get("/api/v1/security-events")
|
||||
|
||||
assert [response.status_code for response in failures] == [401, 401, 401, 429]
|
||||
assert signed_in.status_code == 200
|
||||
assert activity.status_code == 200
|
||||
assert activity.headers["cache-control"] == "no-store"
|
||||
alerts = activity.json()["authentication_alerts"]
|
||||
assert len(alerts) == 1
|
||||
assert alerts[0]["method"] == "token"
|
||||
assert alerts[0]["failed_count"] == 3
|
||||
assert alerts[0]["blocked_count"] == 1
|
||||
assert alerts[0]["first_at"] <= alerts[0]["last_at"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_successful_sign_in_clears_prior_failures(access_control):
|
||||
transport = httpx.ASGITransport(app=main.app, client=("203.0.113.8", 1234))
|
||||
@@ -1555,6 +1593,9 @@ async def test_sign_in_throttle_lookup_does_not_block_the_event_loop(
|
||||
time.sleep(0.15)
|
||||
return 17
|
||||
|
||||
def record_blocked(self, *, method):
|
||||
assert method == "token"
|
||||
|
||||
monkeypatch.setattr(main, "_login_attempt_store", lambda: SlowAttempts())
|
||||
transport = httpx.ASGITransport(app=main.app, client=("203.0.113.10", 1234))
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
|
||||
@@ -736,6 +736,34 @@ process.stdout.write(JSON.stringify(state));
|
||||
]
|
||||
|
||||
|
||||
def test_security_activity_formats_failed_sign_in_alerts_for_mobile_scanability():
|
||||
result = run_session_scenario(
|
||||
"""
|
||||
state.formatted = boundary.formatAuthenticationAlert({
|
||||
method:'token', failed_count:12, blocked_count:3, first_at:1000, last_at:1060
|
||||
});
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["formatted"] == {
|
||||
"title": "12 failed token sign-ins · 3 blocked",
|
||||
"detail": "1/1/1970, 12:16:40 AM – 1/1/1970, 12:17:40 AM",
|
||||
}
|
||||
|
||||
|
||||
def test_security_activity_renders_authentication_alerts_before_journal_events():
|
||||
source = SESSION_JS.read_text()
|
||||
|
||||
alerts = source.index("page.authentication_alerts.forEach")
|
||||
events = source.index("page.events.forEach")
|
||||
assert alerts < events
|
||||
assert "boundary.formatAuthenticationAlert(alert)" in source
|
||||
assert "row.className = 'security-event authentication-alert'" in source
|
||||
css = (ROOT / "frontend" / "dashboard.css").read_text()
|
||||
assert ".authentication-alert { border-color:#d69e2e;" in css
|
||||
|
||||
|
||||
def test_security_activity_explains_pending_outcome_confirmation():
|
||||
source = SESSION_JS.read_text()
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
LOADER = Path(__file__).parents[1] / "frontend" / "feature-loader.js"
|
||||
|
||||
|
||||
def run_loader(scenario: str) -> dict:
|
||||
harness = f"""
|
||||
const fs=require('fs'); const vm=require('vm');
|
||||
const state={{appends:0, removed:0}};
|
||||
const document={{
|
||||
head:{{appendChild(node){{ state.appends++; state.node=node; }} }},
|
||||
createElement(){{ return {{remove(){{state.removed++;}}}}; }},
|
||||
}};
|
||||
const context={{document, setTimeout, clearTimeout, console}};
|
||||
context.globalThis=context;
|
||||
vm.createContext(context);
|
||||
vm.runInContext(fs.readFileSync({json.dumps(str(LOADER))},'utf8'),context);
|
||||
const createFeatureLoader=context.createFeatureLoader;
|
||||
(async()=>{{ {scenario} }})().catch(error=>{{console.error(error);process.exit(1);}});
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", harness], check=True, capture_output=True, text=True)
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_concurrent_feature_requests_share_one_script():
|
||||
result = run_loader("""
|
||||
const loader=createFeatureLoader({document, urls:{'issue-capture':'feature-a.js'}, timeoutMs:100});
|
||||
const first=loader.load('issue-capture'); const second=loader.load('issue-capture');
|
||||
state.node.onload(); await Promise.all([first,second]);
|
||||
console.log(JSON.stringify({appends:state.appends,same:first===second,ready:loader.ready('issue-capture')}));
|
||||
""")
|
||||
assert result == {"appends": 1, "same": True, "ready": True}
|
||||
|
||||
|
||||
def test_failed_feature_request_can_retry_without_reload():
|
||||
result = run_loader("""
|
||||
const loader=createFeatureLoader({document, urls:{'issue-capture':'feature-a.js'}, timeoutMs:100});
|
||||
const failed=loader.load('issue-capture').catch(error=>error.message); state.node.onerror();
|
||||
const message=await failed; const retry=loader.load('issue-capture'); state.node.onload(); await retry;
|
||||
console.log(JSON.stringify({appends:state.appends,removed:state.removed,message,ready:loader.ready('issue-capture')}));
|
||||
""")
|
||||
assert result == {"appends": 2, "removed": 1, "message": "Could not load issue capture.", "ready": True}
|
||||
|
||||
|
||||
def test_feature_gate_exposes_loading_failure_and_success_to_mobile_controls():
|
||||
result = run_loader("""
|
||||
const trigger={disabled:false}; const status={textContent:''}; let opened=0;
|
||||
const loader=createFeatureLoader({document, urls:{'issue-capture':'feature-a.js'}, timeoutMs:100});
|
||||
const failed=loader.run('issue-capture',{trigger,status},()=>{opened++;});
|
||||
const loading={disabled:trigger.disabled,status:status.textContent}; state.node.onerror();
|
||||
const first=await failed;
|
||||
const failedState={disabled:trigger.disabled,status:status.textContent,opened};
|
||||
const retry=loader.run('issue-capture',{trigger,status},()=>{opened++;}); state.node.onload();
|
||||
const second=await retry;
|
||||
console.log(JSON.stringify({loading,failedState,first,second,opened,finalStatus:status.textContent}));
|
||||
""")
|
||||
assert result == {
|
||||
"loading": {"disabled": True, "status": "Loading issue capture…"},
|
||||
"failedState": {
|
||||
"disabled": False,
|
||||
"status": "Issue capture could not load. Tap New issue to retry.",
|
||||
"opened": 0,
|
||||
},
|
||||
"first": False,
|
||||
"second": True,
|
||||
"opened": 1,
|
||||
"finalStatus": "",
|
||||
}
|
||||
|
||||
|
||||
def test_pull_workspace_failure_is_accessible_and_retryable_from_same_card():
|
||||
result = run_loader("""
|
||||
const trigger={disabled:false}; const status={textContent:''}; let opened=0;
|
||||
const loader=createFeatureLoader({document, urls:{'pull-workflow':'feature-pull.js'}, timeoutMs:100});
|
||||
const failed=loader.run('pull-workflow',{trigger,status,retryLabel:'Tap the work card to retry.'},()=>{opened++;});
|
||||
state.node.onerror(); const first=await failed;
|
||||
const failedStatus=status.textContent;
|
||||
const retry=loader.run('pull-workflow',{trigger,status,retryLabel:'Tap the work card to retry.'},()=>{opened++;});
|
||||
state.node.onload(); const second=await retry;
|
||||
console.log(JSON.stringify({first,second,failedStatus,opened,appends:state.appends}));
|
||||
""")
|
||||
assert result == {
|
||||
"first": False,
|
||||
"second": True,
|
||||
"failedStatus": "Pull workspace could not load. Tap the work card to retry.",
|
||||
"opened": 1,
|
||||
"appends": 2,
|
||||
}
|
||||
@@ -9,7 +9,7 @@ from starlette.requests import Request
|
||||
|
||||
from src import main
|
||||
from src.frontend_bundle import build_frontend
|
||||
from src.views import dashboard, runtime_bundle, service_worker
|
||||
from src.views import dashboard, feature_bundle, runtime_bundle, service_worker
|
||||
|
||||
|
||||
FRONTEND = Path(__file__).resolve().parents[1] / "frontend"
|
||||
@@ -42,6 +42,58 @@ def test_page_runtime_is_one_deterministic_content_addressed_bundle(tmp_path):
|
||||
assert changed.runtime_bytes != first.runtime_bytes
|
||||
|
||||
|
||||
def test_product_workflows_are_stable_lazy_feature_chunks(tmp_path):
|
||||
first = build_frontend(FRONTEND)
|
||||
|
||||
assert set(first.feature_bundles) == {"issue-capture", "pull-workflow"}
|
||||
capture = first.feature_bundles["issue-capture"]
|
||||
pull_workflow = first.feature_bundles["pull-workflow"]
|
||||
assert b"function createIssueCapture" not in first.runtime_bytes
|
||||
assert b"function createIssueCapture" in capture.runtime_bytes
|
||||
assert b"function createPullSheet" not in first.runtime_bytes
|
||||
assert b"function createReviewController" not in first.runtime_bytes
|
||||
assert b"function createPullSheet" in pull_workflow.runtime_bytes
|
||||
assert b"function createReviewController" in pull_workflow.runtime_bytes
|
||||
assert len(first.runtime_gzip_bytes) <= 95 * 1024
|
||||
assert f'name="stackchain-feature-issue-capture" content="{capture.runtime_name}"' in first.dashboard_html
|
||||
assert f'name="stackchain-feature-pull-workflow" content="{pull_workflow.runtime_name}"' in first.dashboard_html
|
||||
assert f"BASE + '{capture.runtime_name}'" in first.service_worker_source
|
||||
assert f"BASE + '{pull_workflow.runtime_name}'" in first.service_worker_source
|
||||
|
||||
changed_frontend = tmp_path / "frontend"
|
||||
shutil.copytree(FRONTEND, changed_frontend)
|
||||
capture_source = changed_frontend / "create-issue-sheet.js"
|
||||
capture_source.write_text(capture_source.read_text() + "\n// feature-only change\n")
|
||||
|
||||
changed = build_frontend(changed_frontend)
|
||||
assert changed.runtime_name == first.runtime_name
|
||||
assert changed.feature_bundles["issue-capture"].runtime_name != capture.runtime_name
|
||||
|
||||
pull_source = changed_frontend / "pull-sheet.js"
|
||||
pull_source.write_text(pull_source.read_text() + "\n// pull-workflow-only change\n")
|
||||
pull_changed = build_frontend(changed_frontend)
|
||||
assert pull_changed.runtime_name == first.runtime_name
|
||||
assert pull_changed.feature_bundles["pull-workflow"].runtime_name != pull_workflow.runtime_name
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feature_chunk_is_immutable_and_rejects_unknown_revision():
|
||||
build = build_frontend(FRONTEND)
|
||||
capture = build.feature_bundles["issue-capture"]
|
||||
|
||||
request = Request(
|
||||
{"type": "http", "method": "GET", "path": f"/{capture.runtime_name}",
|
||||
"headers": [(b"accept-encoding", b"identity")]}
|
||||
)
|
||||
response = await feature_bundle("issue-capture", capture.runtime_digest, request)
|
||||
|
||||
assert response.body == capture.runtime_bytes
|
||||
assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
|
||||
with pytest.raises(Exception) as rejected:
|
||||
await feature_bundle("issue-capture", "missing", request)
|
||||
assert rejected.value.status_code == 404
|
||||
|
||||
|
||||
def test_css_only_release_gets_a_new_shell_generation(tmp_path):
|
||||
first = build_frontend(FRONTEND)
|
||||
changed_frontend = tmp_path / "frontend"
|
||||
|
||||
@@ -182,6 +182,7 @@ async def test_notification_detail_loads_subject_and_latest_comment_for_inbox_re
|
||||
"url": "https://forge.example/stackchain/api/issues/7#issuecomment-9",
|
||||
},
|
||||
"issue": {"number": 7, "assignees": [], "claimable": True},
|
||||
"acknowledge_supported": True,
|
||||
"conversation": {
|
||||
"comments": [{
|
||||
"id": 9,
|
||||
|
||||
@@ -74,6 +74,100 @@ def test_failure_ledger_evicts_oldest_sources_at_its_size_limit(tmp_path):
|
||||
assert connection.execute("SELECT COUNT(*) FROM login_attempts").fetchone() == (2,)
|
||||
|
||||
|
||||
def test_failed_sign_ins_are_aggregated_across_workers_and_survive_throttle_clear(tmp_path):
|
||||
now = [1_000.0]
|
||||
database = tmp_path / "login-attempts.sqlite3"
|
||||
first = LoginAttemptStore(
|
||||
database,
|
||||
clock=lambda: now[0],
|
||||
max_failures=3,
|
||||
window_seconds=60,
|
||||
alert_bucket_seconds=300,
|
||||
)
|
||||
second = LoginAttemptStore(
|
||||
database,
|
||||
clock=lambda: now[0],
|
||||
max_failures=3,
|
||||
window_seconds=60,
|
||||
alert_bucket_seconds=300,
|
||||
)
|
||||
|
||||
first.record_failure("203.0.113.7", method="token")
|
||||
now[0] = 1_010.0
|
||||
second.record_failure("198.51.100.4", method="token")
|
||||
first.clear("203.0.113.7")
|
||||
|
||||
assert second.list_alerts() == [
|
||||
{
|
||||
"method": "token",
|
||||
"failed_count": 2,
|
||||
"blocked_count": 0,
|
||||
"first_at": 1_000,
|
||||
"last_at": 1_010,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_rate_blocked_sign_ins_increment_a_distinct_privacy_safe_count(tmp_path):
|
||||
store = LoginAttemptStore(
|
||||
tmp_path / "login-attempts.sqlite3",
|
||||
clock=lambda: 1_000.0,
|
||||
max_failures=3,
|
||||
window_seconds=60,
|
||||
)
|
||||
|
||||
store.record_blocked(method="token")
|
||||
|
||||
assert store.list_alerts() == [
|
||||
{
|
||||
"method": "token",
|
||||
"failed_count": 0,
|
||||
"blocked_count": 1,
|
||||
"first_at": 1_000,
|
||||
"last_at": 1_000,
|
||||
}
|
||||
]
|
||||
with sqlite3.connect(store.path) as connection:
|
||||
columns = [row[1] for row in connection.execute("PRAGMA table_info(login_alerts)")]
|
||||
assert "source_hash" not in columns
|
||||
|
||||
|
||||
def test_expired_sign_in_alert_buckets_are_not_returned(tmp_path):
|
||||
now = [1_000.0]
|
||||
store = LoginAttemptStore(
|
||||
tmp_path / "login-attempts.sqlite3",
|
||||
clock=lambda: now[0],
|
||||
max_failures=3,
|
||||
window_seconds=60,
|
||||
alert_retention_seconds=300,
|
||||
)
|
||||
store.record_failure("203.0.113.7")
|
||||
|
||||
now[0] = 1_301.0
|
||||
|
||||
assert store.list_alerts() == []
|
||||
|
||||
|
||||
def test_sign_in_alert_bucket_count_is_bounded_during_rotating_source_floods(tmp_path):
|
||||
now = [1_000.0]
|
||||
store = LoginAttemptStore(
|
||||
tmp_path / "login-attempts.sqlite3",
|
||||
clock=lambda: now[0],
|
||||
max_failures=3,
|
||||
window_seconds=60,
|
||||
alert_bucket_seconds=60,
|
||||
max_alert_buckets=2,
|
||||
)
|
||||
for index, timestamp in enumerate((1_000.0, 1_060.0, 1_120.0)):
|
||||
now[0] = timestamp
|
||||
store.record_failure(f"203.0.113.{index}")
|
||||
|
||||
with sqlite3.connect(store.path) as connection:
|
||||
count = connection.execute("SELECT COUNT(*) FROM login_alerts").fetchone()[0]
|
||||
|
||||
assert count == 2
|
||||
|
||||
|
||||
def test_named_admission_budget_is_atomic_across_instances_and_source_scoped(tmp_path):
|
||||
now = [1_000.0]
|
||||
database = tmp_path / "login-attempts.sqlite3"
|
||||
|
||||
+153
-9
@@ -3312,6 +3312,68 @@ Promise.all([first, duplicate]).then(results => process.stdout.write(JSON.string
|
||||
]
|
||||
|
||||
|
||||
def test_notification_selection_tracks_a_bounded_subset_and_clears_on_cancel():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
const states = [];
|
||||
const selection = buildMyWork.createNotificationSelection({{
|
||||
limit: 2,
|
||||
onChange: state => states.push(state),
|
||||
}});
|
||||
selection.start();
|
||||
const first = selection.select(42);
|
||||
const duplicate = selection.select(42);
|
||||
selection.toggle(42);
|
||||
selection.select(43);
|
||||
selection.select(44);
|
||||
const second = selection.select(45);
|
||||
selection.cancel();
|
||||
process.stdout.write(JSON.stringify({{first, duplicate, second, states, snapshot:selection.snapshot()}}));
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
)
|
||||
output = json.loads(result.stdout)
|
||||
|
||||
assert output["first"] == "selected"
|
||||
assert output["duplicate"] == "already-selected"
|
||||
assert output["second"] == "limit"
|
||||
assert output["states"] == [
|
||||
{"active": True, "ids": [], "count": 0, "limit": 2, "at_limit": False},
|
||||
{"active": True, "ids": [42], "count": 1, "limit": 2, "at_limit": False},
|
||||
{"active": True, "ids": [], "count": 0, "limit": 2, "at_limit": False},
|
||||
{"active": True, "ids": [43], "count": 1, "limit": 2, "at_limit": False},
|
||||
{"active": True, "ids": [43, 44], "count": 2, "limit": 2, "at_limit": True},
|
||||
{"active": False, "ids": [], "count": 0, "limit": 2, "at_limit": False},
|
||||
]
|
||||
assert output["snapshot"] == output["states"][-1]
|
||||
|
||||
|
||||
def test_notification_selection_retains_only_failed_ids_after_partial_acknowledgement():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
const states = [];
|
||||
const selection = buildMyWork.createNotificationSelection({{
|
||||
onChange: state => states.push(state),
|
||||
}});
|
||||
selection.start();
|
||||
selection.select(42);
|
||||
selection.select(43);
|
||||
selection.select(44);
|
||||
const retained = selection.retain([44, 44, 99]);
|
||||
process.stdout.write(JSON.stringify({{retained, states}}));
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
)
|
||||
output = json.loads(result.stdout)
|
||||
|
||||
assert output["retained"] == {
|
||||
"active": True, "ids": [44], "count": 1, "limit": 50, "at_limit": False,
|
||||
}
|
||||
assert output["states"][-1] == output["retained"]
|
||||
|
||||
|
||||
def test_notification_pager_is_single_flight_and_merges_unique_updates():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
@@ -3439,6 +3501,68 @@ reader.open(original[0], original).then(() =>
|
||||
assert output["result"]["next"]["notification_id"] == 43
|
||||
|
||||
|
||||
def test_notification_reader_acknowledges_once_and_opens_next_update():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
const items = [
|
||||
{{kind:'update', notification_id:42, has_update:true}},
|
||||
{{kind:'update', notification_id:43, has_update:true}},
|
||||
];
|
||||
let release;
|
||||
const calls = [];
|
||||
const events = [];
|
||||
const reader = buildMyWork.createNotificationReader({{
|
||||
load: async id => ({{id}}), markRead: async () => {{}},
|
||||
acknowledge: id => new Promise(resolve => {{ calls.push(id); release = resolve; }}),
|
||||
onOpen: item => events.push(['open', item.notification_id]), onDetail: () => {{}},
|
||||
onItems: next => events.push(['items', next.map(item => item.notification_id)]),
|
||||
onStatus: status => events.push(['status', status]), onClose: () => events.push(['close']),
|
||||
}});
|
||||
(async () => {{
|
||||
await reader.open(items[0]);
|
||||
events.length = 0;
|
||||
const first = reader.acknowledgeAndNext(items);
|
||||
const duplicate = reader.acknowledgeAndNext(items);
|
||||
await Promise.resolve();
|
||||
release({{reaction:'created', status:'read'}});
|
||||
const results = await Promise.all([first, duplicate]);
|
||||
process.stdout.write(JSON.stringify({{calls, events, results}}));
|
||||
}})();
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["calls"] == [42]
|
||||
assert output["events"] == [
|
||||
["status", "Adding reaction and marking read…"],
|
||||
["items", [43]],
|
||||
["open", 43],
|
||||
["status", "Loading update…"],
|
||||
["status", "Update ready."],
|
||||
]
|
||||
assert output["results"][0]["next"]["notification_id"] == 43
|
||||
assert output["results"][1] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_update_sheet_wires_touch_safe_online_acknowledge_and_next():
|
||||
html = await dashboard()
|
||||
|
||||
assert (
|
||||
'id="acknowledge-update-next" type="button" hidden '
|
||||
'aria-label="Acknowledge and open next update">👍 Acknowledge & next</button>'
|
||||
) in html
|
||||
assert "qs('#acknowledge-update-next').hidden = true;" in html
|
||||
assert "qs('#acknowledge-update-next').hidden = !detail.acknowledge_supported;" in html
|
||||
assert "async function acknowledgeNotification(notificationId)" in html
|
||||
assert "'/acknowledge', { method: 'POST'" in html
|
||||
assert "acknowledge: acknowledgeNotification" in html
|
||||
assert "notificationReader.acknowledgeAndNext(lastMyWork)" in html
|
||||
assert "qs('#acknowledge-update-next').disabled = offline;" in html
|
||||
assert '.update-sheet-actions #acknowledge-update-next { min-height:44px;' in html
|
||||
|
||||
|
||||
def test_notification_reader_keeps_current_update_retryable_when_detail_load_fails():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
@@ -4217,7 +4341,10 @@ async def test_assigned_pulls_open_accessible_mobile_completion_sheet():
|
||||
assert "pullConversation.append(comment)" in html
|
||||
assert 'id="pull-comment"' in html and 'maxlength="10000"' in html
|
||||
assert 'id="merge-pull"' in html and 'id="open-pull-gitea"' in html
|
||||
assert '<script src="static/pull-sheet.js"></script>' in html
|
||||
assert 'stackchain-feature-pull-workflow' in html
|
||||
assert "pullWorkflowFeatures.run('pull-workflow'" in html
|
||||
assert "let pullController = null" in html
|
||||
assert "let reviewController = null" in html
|
||||
assert "pullController.load(item)" in html
|
||||
assert "createPullSheet.renderFile" in html
|
||||
assert "pullController.toggleReviewed" in html
|
||||
@@ -4337,6 +4464,14 @@ async def test_mobile_my_work_captures_new_issue_in_accessible_draft_safe_sheet(
|
||||
assert '.create-issue-label-option' in html and 'min-height:44px' in html
|
||||
|
||||
|
||||
def test_new_issue_capture_waits_for_retryable_feature_before_opening():
|
||||
dashboard_source = (Path(__file__).parents[1] / "frontend" / "dashboard.js").read_text()
|
||||
|
||||
assert "await issueCaptureFeatures.run('issue-capture'" in dashboard_source
|
||||
assert "if (!issueCapture)" in dashboard_source
|
||||
assert "async function openCreateIssueSheet" in dashboard_source
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_issue_capture_warns_before_queuing_a_possible_duplicate():
|
||||
html = await dashboard()
|
||||
@@ -4482,18 +4617,26 @@ async def test_mobile_update_sheet_has_persistent_accessible_reply_composer():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_updates_view_offers_confirmed_sticky_mobile_bulk_acknowledgement():
|
||||
async def test_updates_view_offers_accessible_sticky_mobile_subset_selection():
|
||||
html = await dashboard()
|
||||
|
||||
assert 'id="bulk-mark-read"' in html
|
||||
assert 'id="bulk-mark-read-bar"' in html
|
||||
assert 'class="my-work-bulk"' in html
|
||||
assert 'id="select-updates"' in html
|
||||
assert 'id="cancel-update-selection"' in html
|
||||
assert 'id="update-selection-status"' in html
|
||||
assert 'aria-live="polite"' in html
|
||||
assert 'class="update-selector"' in html
|
||||
assert 'type="checkbox"' in html
|
||||
assert 'Select update ' in html
|
||||
assert '.update-selector { min-height:44px;' in html
|
||||
assert '.my-work-bulk { position:sticky;' in html
|
||||
assert 'padding-bottom:calc(10px + env(safe-area-inset-bottom));' in html
|
||||
assert '.my-work-bulk button { min-height:44px; width:100%; }' in html
|
||||
assert "'next ' + ids.length + ' of ' + allIds.length + ' loaded updates'" in html
|
||||
assert "'Confirm marking ' + bulkLabel + ' read'" in html
|
||||
assert "const ids = allIds.slice(0, 50)" in html
|
||||
assert '.my-work-bulk { bottom:calc(56px + env(safe-area-inset-bottom)); }' in html
|
||||
assert "'Mark ' + selection.count + ' selected read'" in html
|
||||
assert "'Confirm marking ' + selection.count + ' selected read'" in html
|
||||
assert 'bulkNotificationAcknowledger.acknowledge(lastMyWork, selection.ids)' in html
|
||||
assert 'notificationSelection.retain(result.failed)' in html
|
||||
assert "notificationSelection.cancel()" in html
|
||||
assert "createBulkNotificationAcknowledger" in html
|
||||
assert "api/v1/notifications/read" in html
|
||||
assert "body: JSON.stringify({ ids })" in html
|
||||
@@ -4510,7 +4653,8 @@ async def test_updates_view_discloses_incomplete_inbox_and_loads_more_on_mobile(
|
||||
assert "api/v1/notifications?page=" in html
|
||||
assert "snapshot.notification_pagination" in html
|
||||
assert "notificationPager.loadMore(lastNotifications)" in html
|
||||
assert "Math.min(lastNotifications.length, 50)" in html
|
||||
assert "createNotificationSelection({" in html
|
||||
assert "limit: 50" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -66,6 +66,7 @@ async def test_notification_detail_opens_the_newest_conversation_page_in_chronol
|
||||
"assignees": [],
|
||||
"claimable": True,
|
||||
}
|
||||
assert result["acknowledge_supported"] is True
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -41,6 +41,117 @@ async def test_mark_notification_read_calls_supported_gitea_thread_endpoint(monk
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_acknowledge_notification_resolves_latest_comment_and_adds_one_reaction(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_fetch(path):
|
||||
calls.append(("fetch", path))
|
||||
if path == "notifications/threads/42":
|
||||
return {
|
||||
"repository": {"full_name": "stackchain/api"},
|
||||
"subject": {
|
||||
"type": "Issue",
|
||||
"url": "https://forge.example/api/v1/repos/stackchain/api/issues/7",
|
||||
"latest_comment_url": (
|
||||
"https://forge.example/api/v1/repos/stackchain/api/issues/comments/91"
|
||||
),
|
||||
},
|
||||
}
|
||||
if path == "user":
|
||||
return {"login": "timmy"}
|
||||
raise AssertionError(path)
|
||||
|
||||
class Response:
|
||||
def __init__(self, payload=None):
|
||||
self._payload = payload
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
class Client:
|
||||
async def get(self, path, headers):
|
||||
calls.append(("get", path))
|
||||
return Response([])
|
||||
|
||||
async def post(self, path, headers, json):
|
||||
calls.append(("post", path, json))
|
||||
return Response({"content": "+1"})
|
||||
|
||||
async def patch(self, path, headers):
|
||||
calls.append(("patch", path))
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "GITEA_URL", "https://forge.example")
|
||||
monkeypatch.setattr(gitea_proxy, "fetch", fake_fetch)
|
||||
monkeypatch.setattr(gitea_proxy, "_get_client", lambda: Client())
|
||||
monkeypatch.setattr(gitea_proxy, "_auth", lambda: {"Authorization": "token test"})
|
||||
|
||||
result = await gitea_proxy.acknowledge_notification(42)
|
||||
|
||||
reaction_path = "/api/v1/repos/stackchain/api/issues/comments/91/reactions"
|
||||
assert result == {"id": 42, "reaction": "created", "status": "read"}
|
||||
assert calls == [
|
||||
("fetch", "notifications/threads/42"),
|
||||
("fetch", "user"),
|
||||
("get", reaction_path),
|
||||
("post", reaction_path, {"content": "+1"}),
|
||||
("patch", "/api/v1/notifications/threads/42?to-status=read"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_acknowledge_notification_reuses_existing_operator_reaction_on_retry(monkeypatch):
|
||||
posts = []
|
||||
|
||||
async def fake_fetch(path):
|
||||
if path == "user":
|
||||
return {"login": "timmy"}
|
||||
return {
|
||||
"repository": {"full_name": "stackchain/api"},
|
||||
"subject": {
|
||||
"type": "Pull",
|
||||
"url": "https://forge.example/api/v1/repos/stackchain/api/pulls/7",
|
||||
"latest_comment_url": (
|
||||
"https://forge.example/api/v1/repos/stackchain/api/issues/comments/91"
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
class Response:
|
||||
def __init__(self, payload=None):
|
||||
self.payload = payload
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def json(self):
|
||||
return self.payload
|
||||
|
||||
class Client:
|
||||
async def get(self, path, headers):
|
||||
return Response([{"content": "+1", "user": {"login": "timmy"}}])
|
||||
|
||||
async def post(self, path, headers, json):
|
||||
posts.append((path, json))
|
||||
return Response()
|
||||
|
||||
async def patch(self, path, headers):
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "GITEA_URL", "https://forge.example")
|
||||
monkeypatch.setattr(gitea_proxy, "fetch", fake_fetch)
|
||||
monkeypatch.setattr(gitea_proxy, "_get_client", lambda: Client())
|
||||
|
||||
result = await gitea_proxy.acknowledge_notification(42)
|
||||
|
||||
assert result == {"id": 42, "reaction": "existing", "status": "read"}
|
||||
assert posts == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mark_notification_read_api_is_bounded_and_never_cacheable(monkeypatch):
|
||||
marked = []
|
||||
@@ -61,6 +172,33 @@ async def test_mark_notification_read_api_is_bounded_and_never_cacheable(monkeyp
|
||||
assert marked == [42]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_acknowledge_notification_api_confirms_reaction_and_removes_snapshot_item(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def acknowledge(thread_id):
|
||||
calls.append(thread_id)
|
||||
return {"id": thread_id, "reaction": "created", "status": "read"}
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "acknowledge_notification", acknowledge, raising=False)
|
||||
monkeypatch.setattr(
|
||||
main,
|
||||
"_live_snapshot_value",
|
||||
{"notifications": [{"id": 42}, {"id": 43}]},
|
||||
)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post("/api/v1/notifications/42/acknowledge")
|
||||
invalid = await client.post("/api/v1/notifications/0/acknowledge")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"id": 42, "reaction": "created", "status": "read"}
|
||||
assert response.headers["cache-control"] == "no-store"
|
||||
assert invalid.status_code == 422
|
||||
assert calls == [42]
|
||||
assert main._live_snapshot_value == {"notifications": [{"id": 43}]}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_snapshot_maintenance_does_not_block_the_event_loop(monkeypatch):
|
||||
async def mark(_thread_id):
|
||||
|
||||
@@ -53,6 +53,7 @@ async def test_authenticated_security_activity_lists_private_sign_in_history(sec
|
||||
"status": "completed",
|
||||
}
|
||||
],
|
||||
"authentication_alerts": [],
|
||||
"next_cursor": None,
|
||||
}
|
||||
persisted = (security_access / "security.sqlite3").read_bytes()
|
||||
|
||||
@@ -419,6 +419,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/icons/stackchain-192.png",
|
||||
"/dashboard/static/icons/stackchain-512.png",
|
||||
"/dashboard/static/session.js",
|
||||
"/dashboard/static/feature-loader.js",
|
||||
"/dashboard/static/markdown.js",
|
||||
"/dashboard/static/commands.js",
|
||||
"/dashboard/static/search-preview.js",
|
||||
|
||||
Reference in new issue
Block a user