Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2f83b0955 | ||
|
|
6b56188d30 | ||
|
|
467c8c665d | ||
|
|
1b311c9cd4 | ||
|
|
71d06347fd | ||
|
|
1de6d73e75 | ||
|
|
46c75f0b22 | ||
|
|
5cdb3f7b3e | ||
|
|
15d197327a | ||
|
|
df8385b325 | ||
|
|
47c6412a12 | ||
|
|
6cac778acd | ||
|
|
a8a93b2f3b | ||
|
|
ef37a66fd7 | ||
|
|
52e2c26304 | ||
|
|
3817d2c67b | ||
|
|
ad6c1edf80 | ||
|
|
d2b2c7bada | ||
|
|
9ba03613d4 | ||
|
|
1132075318 | ||
|
|
16b1d8670f |
No files matched your search
@@ -373,7 +373,10 @@ account and never contain the Gitea token. Find Work uses the same worker-shared
|
||||
`STACKCHAIN_AVAILABLE_ISSUE_SNAPSHOT_DB` overrides
|
||||
`STACKCHAIN_STATE_DIR/available-issue-snapshot.sqlite3`. One expiring lease bounds each
|
||||
catalog scan across the deployment, shared retry metadata prevents worker-by-worker retry
|
||||
bursts, and confirmed claims are removed from every worker's retained catalog. Releasing
|
||||
bursts, and confirmed claims are removed from every worker's retained catalog. On a cold
|
||||
catalog, non-owner workers wait within the bounded foreground deadline for the lease owner
|
||||
to publish; if that owner releases or abandons the lease, a waiter can take over the scan
|
||||
within its remaining request budget. Releasing
|
||||
an assignment invalidates the shared catalog so the newly available issue can be discovered
|
||||
by the next authoritative scan. Each bounded opaque revision token includes the
|
||||
store generation, so a token from a different deployment or before replacement of the store
|
||||
|
||||
@@ -77,6 +77,14 @@ main { position: relative; z-index: 1; display: grid; grid-template-columns: 300
|
||||
h2 { font-size: 13px; margin: 8px 0; text-transform: uppercase; letter-spacing: .08em; color: #94a3b8; }
|
||||
a { color: #60a5fa; text-decoration: none; }
|
||||
.muted { color: #94a3b8; }
|
||||
.empty-work-start { display:grid; gap:12px; margin:12px 0; padding:16px; border:1px solid #31577f; border-radius:14px; background:#0b1b2f; }
|
||||
.empty-work-start[hidden] { display:none; }
|
||||
.empty-work-start p { margin:6px 0 0; }
|
||||
.empty-work-start-actions { display:grid; grid-template-columns:minmax(0, 1fr) minmax(0, 1fr); gap:8px; }
|
||||
.empty-work-start-actions button { min-width:0; min-height:44px; white-space:normal; }
|
||||
@media (max-width:420px) {
|
||||
.empty-work-start-actions { grid-template-columns:1fr; }
|
||||
}
|
||||
.kv { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; }
|
||||
.kv .label { color: #94a3b8; }
|
||||
.kv .value { color: #e5e7eb; }
|
||||
|
||||
+44
-10
@@ -49,11 +49,7 @@
|
||||
attentionInterruption.hidden = !pending;
|
||||
return pending;
|
||||
}
|
||||
function openMobileWorkFallback() {
|
||||
qs('[data-work-filter="all"]').click();
|
||||
qs('#my-work').scrollIntoView({block:'start'});
|
||||
qs('#my-work').focus();
|
||||
}
|
||||
|
||||
function selectMobileQueue(name) {
|
||||
if (name === 'attention' && workSession.checkpointed()) timer.beginAttention();
|
||||
renderAttentionInterruption();
|
||||
@@ -71,7 +67,7 @@
|
||||
resumeToday: resumeTodaySession,
|
||||
startToday: startTodaySession,
|
||||
planToday: () => openPlanToday(mobileTaskButtons.work),
|
||||
openFallback: openMobileWorkFallback,
|
||||
findWork: () => qs('#find-work').click(),
|
||||
});
|
||||
let mobileQueueCounts = {};
|
||||
const mobileQueueLauncher = createMobileQueueLauncher({
|
||||
@@ -122,6 +118,8 @@
|
||||
},
|
||||
});
|
||||
mobileTaskDock.start();
|
||||
qs('#empty-work-find').addEventListener('click', () => qs('#find-work').click());
|
||||
qs('#empty-work-create').addEventListener('click', () => qs('#new-issue').click());
|
||||
let liveMode = true;
|
||||
let offlineWorkMode = false;
|
||||
const WORK_FILTER_KEY = 'stackchain.my-work-filter.v1';
|
||||
@@ -133,7 +131,7 @@
|
||||
let launchFilterResolved = false;
|
||||
try {
|
||||
const savedFilter = sessionStorage.getItem(WORK_FILTER_KEY);
|
||||
if (['all', 'today', 'attention', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)) {
|
||||
if (['all', 'today', 'agenda', 'attention', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)) {
|
||||
selectedWorkFilter = savedFilter;
|
||||
savedWorkFilter = savedFilter;
|
||||
launchFilterResolved = true;
|
||||
@@ -149,6 +147,7 @@
|
||||
let lastContextSnapshot = null;
|
||||
let notificationPagination = { page: 1, total: 0, has_more: false };
|
||||
let workPagination = {};
|
||||
let agendaChecking = false;
|
||||
let hasContextSnapshot = false;
|
||||
let selectedReview = null;
|
||||
let reviewTrigger = null;
|
||||
@@ -2158,12 +2157,15 @@
|
||||
},
|
||||
});
|
||||
const counts = countMyWork(activeMyWork);
|
||||
const agendaItems = agendaMyWork(activeMyWork);
|
||||
counts.agenda = agendaItems.length;
|
||||
counts.today = todayMyWork.length;
|
||||
counts.later = laterMyWork.length;
|
||||
counts.draft = lastDrafts.length;
|
||||
if (!launchFilterResolved) {
|
||||
selectedWorkFilter = mobileLaunch.chooseFilter({
|
||||
saved: savedWorkFilter, today: counts.today, attention: counts.attention,
|
||||
agenda: counts.agenda,
|
||||
});
|
||||
launchFilterResolved = true;
|
||||
document.querySelectorAll('[data-work-filter]').forEach(item =>
|
||||
@@ -2201,12 +2203,16 @@
|
||||
'No assigned work, review requests, or unread updates.';
|
||||
updateWorkPaginationControls();
|
||||
renderMyWork();
|
||||
if (selectedWorkFilter === 'agenda' && workPagination.issue?.has_more && !agendaChecking) {
|
||||
completeAgendaIssues();
|
||||
}
|
||||
if (reconcileSession && workSession.active()) workSession.reconcile();
|
||||
updateWorkSessionActions();
|
||||
}
|
||||
|
||||
function activeWorkStreams() {
|
||||
if (selectedWorkFilter === 'today') return ['issue', 'pull', 'review'];
|
||||
if (selectedWorkFilter === 'agenda') return ['issue'];
|
||||
if (selectedWorkFilter === 'attention') return ['issue', 'pull', 'review'];
|
||||
if (selectedWorkFilter === 'issue') return ['issue'];
|
||||
if (selectedWorkFilter === 'pull') return ['pull'];
|
||||
@@ -2215,6 +2221,20 @@
|
||||
return [];
|
||||
}
|
||||
|
||||
async function completeAgendaIssues() {
|
||||
if (selectedWorkFilter !== 'agenda' || !workPagination.issue?.has_more || !lastContextSnapshot) return;
|
||||
agendaChecking = true;
|
||||
qs('#my-work-action-status').textContent = 'Checking all assigned deadlines…';
|
||||
renderMyWork();
|
||||
const complete = await workPager.loadAll('issue', () => lastContextSnapshot?.issues || []);
|
||||
agendaChecking = false;
|
||||
if (selectedWorkFilter !== 'agenda') return;
|
||||
qs('#my-work-action-status').textContent = complete ?
|
||||
'All assigned deadlines checked.' :
|
||||
'Agenda check paused. Retry to check older assigned deadlines.';
|
||||
renderMyWork();
|
||||
}
|
||||
|
||||
function renderDrafts() {
|
||||
const list = qs('#my-work-list');
|
||||
const displayedDrafts = findQueueItems(lastDrafts, queueFindQuery);
|
||||
@@ -2425,10 +2445,15 @@
|
||||
}
|
||||
const queueItems = selectedWorkFilter === 'today' ?
|
||||
filterMyWork(todayMyWork, 'all', selectedWorkMilestone) : selectedWorkFilter === 'later' ?
|
||||
filterMyWork(laterMyWork, 'all', selectedWorkMilestone) :
|
||||
filterMyWork(laterMyWork, 'all', selectedWorkMilestone) : selectedWorkFilter === 'agenda' ?
|
||||
agendaMyWork(activeMyWork) :
|
||||
filterMyWork(activeMyWork, selectedWorkFilter, selectedWorkMilestone);
|
||||
const incomplete = activeWorkStreams().some(stream => workPagination[stream]?.has_more);
|
||||
const visible = findQueueItems(queueItems, queueFindQuery);
|
||||
const emptyWorkStart = qs('#empty-work-start');
|
||||
const showEmptyStart = selectedWorkFilter === 'all' && !queueFindQuery &&
|
||||
!queueItems.length && !incomplete && hasContextSnapshot;
|
||||
emptyWorkStart.hidden = !showEmptyStart;
|
||||
updateQueueFinder(visible.length, queueItems.length, incomplete);
|
||||
const selection = notificationSelection.snapshot();
|
||||
const selectedIds = new Set(selection.ids);
|
||||
@@ -2441,6 +2466,7 @@
|
||||
const contents =
|
||||
'<span class="small">' + escapeHtml(item.key) + ' · ' + escapeHtml(item.kind === 'pull' ? 'PR' : (item.kind === 'update' ? 'Update' : 'Issue')) + '</span>' +
|
||||
'<span class="my-work-card-title">' + escapeHtml(item.title) + '</span>' +
|
||||
(item.agenda_group ? '<span class="pill agenda-badge" data-agenda-group="' + escAttr(item.agenda_group) + '">' + escapeHtml(item.agenda_group) + '</span>' : '') +
|
||||
'<span class="pill">' + escapeHtml(item.reason) + '</span>' +
|
||||
(item.milestone?.title ? ' <span class="pill milestone-badge">' + escapeHtml(item.milestone.title) + '</span>' : '') +
|
||||
(item.due_label ? ' <span class="pill due-badge">' + escapeHtml(item.due_label) + '</span>' : '') +
|
||||
@@ -2481,9 +2507,12 @@
|
||||
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="' + 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 ?
|
||||
}).join('') : (showEmptyStart ? '' : '<div class="muted">' +
|
||||
(selectedWorkFilter === 'agenda' && workPagination.issue?.has_more ?
|
||||
(agendaChecking ? 'Checking all assigned deadlines…' :
|
||||
'Older assigned deadlines remain unchecked. Retry the Agenda check.') : (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>';
|
||||
'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', () => {
|
||||
@@ -5770,6 +5799,10 @@
|
||||
notificationPager.loadMore(lastNotifications)
|
||||
);
|
||||
qs('#load-more-work').addEventListener('click', async () => {
|
||||
if (selectedWorkFilter === 'agenda') {
|
||||
await completeAgendaIssues();
|
||||
return;
|
||||
}
|
||||
const stream = activeWorkStreams().find(item => workPagination[item]?.has_more);
|
||||
if (!stream || !lastContextSnapshot) return;
|
||||
const button = qs('#load-more-work');
|
||||
@@ -5923,6 +5956,7 @@
|
||||
qs('#active-work-queue').textContent = button.firstChild.textContent.trim() + ' (' + selectedCount + ')';
|
||||
renderMyWork();
|
||||
updateWorkPaginationControls();
|
||||
if (selectedWorkFilter === 'agenda') completeAgendaIssues();
|
||||
if (!preserveRoute) workRoute.queue(filter);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -109,6 +109,7 @@
|
||||
<div class="work-filters" aria-label="Filter My Work">
|
||||
<button class="work-filter" data-work-filter="all" aria-pressed="true">All <span data-work-count="all">0</span></button>
|
||||
<button class="work-filter" data-work-filter="today" aria-pressed="false">Today <span data-work-count="today">0</span></button>
|
||||
<button class="work-filter" data-work-filter="agenda" aria-pressed="false">Agenda <span data-work-count="agenda">0</span></button>
|
||||
<button class="work-filter" data-work-filter="attention" aria-pressed="false">Attention <span data-work-count="attention">0</span></button>
|
||||
<button class="work-filter" data-work-filter="issue" aria-pressed="false">Issues <span data-work-count="issue">0</span></button>
|
||||
<button class="work-filter" data-work-filter="pull" aria-pressed="false">PRs <span data-work-count="pull">0</span></button>
|
||||
@@ -182,6 +183,16 @@
|
||||
<div class="small" id="queue-find-status" role="status" aria-live="polite"></div>
|
||||
<button id="search-older-work" type="button" hidden>Search older work</button>
|
||||
</form>
|
||||
<section class="empty-work-start" id="empty-work-start" aria-labelledby="empty-work-start-heading" hidden>
|
||||
<div>
|
||||
<strong id="empty-work-start-heading">Ready for something new?</strong>
|
||||
<p class="small muted">Find an available issue to own, or create the work that needs doing.</p>
|
||||
</div>
|
||||
<div class="empty-work-start-actions">
|
||||
<button id="empty-work-find" type="button">Find and start work</button>
|
||||
<button id="empty-work-create" type="button">Create an issue</button>
|
||||
</div>
|
||||
</section>
|
||||
<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>
|
||||
@@ -921,6 +932,7 @@
|
||||
<p class="small muted">Choose what to work through next.</p>
|
||||
<div class="mobile-queue-list">
|
||||
<button data-mobile-queue="today" type="button"><span><strong>Today</strong><small>Planned work</small></span><span data-mobile-queue-count="today">0</span></button>
|
||||
<button data-mobile-queue="agenda" type="button"><span><strong>Agenda</strong><small>Upcoming deadlines</small></span><span data-mobile-queue-count="agenda">0</span></button>
|
||||
<button data-mobile-queue="attention" type="button"><span><strong>Attention</strong><small>Needs a response</small></span><span data-mobile-queue-count="attention">0</span></button>
|
||||
<button data-mobile-queue="update" type="button" aria-label="Updates, 0 unread conversations"><span><strong>Updates</strong><small>Unread conversations</small></span><span data-mobile-queue-count="update">0</span></button>
|
||||
<button data-mobile-queue="later" type="button"><span><strong>Later</strong><small>Deferred work</small></span><span data-mobile-queue-count="later">0</span></button>
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
else root.mobileLaunch = api;
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
|
||||
const allowedFilters = new Set([
|
||||
'all', 'today', 'attention', 'issue', 'pull', 'review', 'update', 'later', 'draft',
|
||||
'all', 'today', 'attention', 'agenda', 'issue', 'pull', 'review', 'update', 'later', 'draft',
|
||||
]);
|
||||
|
||||
function chooseFilter({ saved, today = 0, attention = 0 } = {}) {
|
||||
function chooseFilter({ saved, today = 0, attention = 0, agenda = 0 } = {}) {
|
||||
if (allowedFilters.has(saved)) return saved;
|
||||
if (today > 0) return 'today';
|
||||
if (attention > 0) return 'attention';
|
||||
if (agenda > 0) return 'agenda';
|
||||
return 'all';
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
const continuation = [
|
||||
['attention', 'Start Attention'],
|
||||
['today', 'Continue Today'],
|
||||
['agenda', 'Open Agenda'],
|
||||
['later', 'Start Later'],
|
||||
['draft', 'Open Drafts'],
|
||||
];
|
||||
|
||||
@@ -69,6 +69,7 @@
|
||||
resume: ['Resume', 'Resume Today'],
|
||||
start: ['Start', 'Start Today'],
|
||||
plan: ['Plan', 'Plan Today'],
|
||||
find: ['Find', 'Find work'],
|
||||
work: ['Work', 'Work'],
|
||||
};
|
||||
const workMode = labels[mode] ? mode : 'work';
|
||||
@@ -94,7 +95,7 @@
|
||||
}
|
||||
|
||||
function updateQueues(counts) {
|
||||
const names = 'today attention update later draft'.split(' ');
|
||||
const names = 'today agenda attention update later draft'.split(' ');
|
||||
const normalized = Object.fromEntries(names.map(name => [name, Math.max(0, Number(counts?.[name]) || 0)]));
|
||||
const total = ['today', 'attention', 'later', 'draft'].reduce((sum, name) => sum + normalized[name], 0);
|
||||
Object.entries(options.queueCounts || {}).forEach(([name, element]) => {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
if (options.getTodayCount() > 0 && options.isTodayResumable()) return 'resume';
|
||||
if (options.getTodayCount() > 0) return 'start';
|
||||
if (options.getEligibleCount() > 0) return 'plan';
|
||||
return 'work';
|
||||
return 'find';
|
||||
}
|
||||
|
||||
function open() {
|
||||
@@ -16,7 +16,7 @@
|
||||
else if (current === 'resume') options.resumeToday();
|
||||
else if (current === 'start') options.startToday();
|
||||
else if (current === 'plan') options.planToday();
|
||||
else options.openFallback();
|
||||
else options.findWork();
|
||||
return current;
|
||||
}
|
||||
|
||||
|
||||
+35
-1
@@ -277,12 +277,13 @@ function createNotificationPager({ load, onNotifications, onPagination, onStatus
|
||||
function createWorkPager({ load, onItems, onPagination, onStatus }) {
|
||||
let pagination = {};
|
||||
const pending = new Set();
|
||||
const completing = new Map();
|
||||
const labels = {
|
||||
issue: 'issues',
|
||||
pull: 'pull requests',
|
||||
review: 'review requests',
|
||||
};
|
||||
return {
|
||||
const pager = {
|
||||
reset(next) {
|
||||
Object.entries(next || {}).forEach(([stream, value]) => {
|
||||
const current = pagination[stream];
|
||||
@@ -331,7 +332,20 @@ function createWorkPager({ load, onItems, onPagination, onStatus }) {
|
||||
pending.delete(stream);
|
||||
}
|
||||
},
|
||||
loadAll(stream, getExisting) {
|
||||
if (completing.has(stream)) return completing.get(stream);
|
||||
const completion = (async () => {
|
||||
while (pagination[stream]?.has_more) {
|
||||
const loaded = await pager.loadMore(stream, getExisting());
|
||||
if (!loaded) return false;
|
||||
}
|
||||
return true;
|
||||
})().finally(() => completing.delete(stream));
|
||||
completing.set(stream, completion);
|
||||
return completion;
|
||||
},
|
||||
};
|
||||
return pager;
|
||||
}
|
||||
|
||||
function createNotificationReader({
|
||||
@@ -553,6 +567,25 @@ function filterMyWork(items, selectedFilter, selectedMilestone = 'all') {
|
||||
);
|
||||
}
|
||||
|
||||
function agendaMyWork(items, now = new Date()) {
|
||||
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const tomorrow = new Date(start); tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
const afterTomorrow = new Date(start); afterTomorrow.setDate(afterTomorrow.getDate() + 2);
|
||||
const horizon = new Date(start); horizon.setDate(horizon.getDate() + 7);
|
||||
return (items || []).flatMap(item => {
|
||||
if (item?.kind !== 'issue' || !item.is_assigned || !item.due_date) return [];
|
||||
const due = new Date(item.due_date);
|
||||
if (Number.isNaN(due.getTime()) || due >= horizon) return [];
|
||||
const group = due < start ? 'Overdue' : due < tomorrow ? 'Today' :
|
||||
due < afterTomorrow ? 'Tomorrow' : 'Next 7 days';
|
||||
return [{ ...item, agenda_group: group, _agenda_due: due.getTime() }];
|
||||
}).sort((left, right) =>
|
||||
left._agenda_due - right._agenda_due ||
|
||||
String(left.repository || '').localeCompare(String(right.repository || '')) ||
|
||||
Number(left.number || 0) - Number(right.number || 0)
|
||||
).map(({ _agenda_due, ...item }) => item);
|
||||
}
|
||||
|
||||
function milestoneLanes(items) {
|
||||
const lanes = new Map();
|
||||
(items || []).forEach(item => {
|
||||
@@ -837,6 +870,7 @@ function countMyWork(items) {
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
buildMyWork.filterMyWork = filterMyWork;
|
||||
buildMyWork.agendaMyWork = agendaMyWork;
|
||||
buildMyWork.milestoneLanes = milestoneLanes;
|
||||
buildMyWork.createWorkSession = createWorkSession;
|
||||
buildMyWork.createWorkSessionCheckpoint = createWorkSessionCheckpoint;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
'use strict';
|
||||
|
||||
const repositoryPart = /^[A-Za-z0-9_.-]+$/;
|
||||
const queueFilters = ['today', 'attention', 'update', 'later', 'draft'];
|
||||
const queueFilters = ['today', 'agenda', 'attention', 'update', 'later', 'draft'];
|
||||
|
||||
function positiveInteger(value) {
|
||||
const number = Number(value);
|
||||
|
||||
@@ -28,7 +28,7 @@ FEATURE_SOURCES = {
|
||||
"device-setup": ("static/install-app.js", "static/mobile-device-setup.js"),
|
||||
"security-center": ("static/security-center.js",),
|
||||
"today-timer": (
|
||||
"static/mobile-task-dock.js", "static/mobile-queue-launcher.js", "static/notification-undo.js", "static/today-timer.js", "static/today-recap.js",
|
||||
"static/my-work.js", "static/mobile-task-dock.js", "static/mobile-queue-launcher.js", "static/notification-undo.js", "static/today-timer.js", "static/today-recap.js",
|
||||
"static/today-rollover.js", "static/later-work.js", "static/drafts.js", "static/unfiled-captures.js",
|
||||
"static/draft-filing-session.js", "static/draft-capacity-dialog.js", "static/work-selection.js",
|
||||
"static/today-work.js", "static/pick-work.js", "static/batch-find-work.js",
|
||||
|
||||
+10
-2
@@ -22,10 +22,14 @@ class LaterStore:
|
||||
self.operation_limit = operation_limit
|
||||
self.operation_retention_seconds = operation_retention_seconds
|
||||
self.clock = clock
|
||||
self._initialize()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
def _initialize(self) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
connection = sqlite3.connect(self.path, timeout=self.timeout)
|
||||
if connection.execute("PRAGMA user_version").fetchone()[0] >= 1:
|
||||
connection.close()
|
||||
return
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
connection.execute(
|
||||
"""
|
||||
@@ -63,8 +67,12 @@ class LaterStore:
|
||||
"UPDATE later_operations SET created_at = ? WHERE created_at IS NULL",
|
||||
(self.clock(),),
|
||||
)
|
||||
connection.execute("PRAGMA user_version = 1")
|
||||
connection.commit()
|
||||
return connection
|
||||
connection.close()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
return sqlite3.connect(self.path, timeout=self.timeout)
|
||||
|
||||
def _record_operation(self, connection: sqlite3.Connection, login: str, operation_id: str) -> None:
|
||||
now = self.clock()
|
||||
|
||||
+93
-27
@@ -10,6 +10,7 @@ import sqlite3
|
||||
import time
|
||||
from collections.abc import Awaitable, Coroutine
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
@@ -59,6 +60,9 @@ from src.views import FRONTEND_BUILD, router as frontend_router
|
||||
|
||||
|
||||
async def _drain_authored_action_operations() -> None:
|
||||
for key, operation in list(_authored_action_operations.items()):
|
||||
if operation[1].done():
|
||||
_authored_action_operations.pop(key, None)
|
||||
tasks = {
|
||||
operation[1]
|
||||
for operation in _authored_action_operations.values()
|
||||
@@ -116,10 +120,18 @@ async def _push_poll_loop() -> None:
|
||||
continue
|
||||
|
||||
|
||||
async def _readiness_monitor() -> None:
|
||||
while True:
|
||||
await _check_readiness()
|
||||
await asyncio.sleep(READINESS_INTERVAL_SECONDS)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
global _live_snapshot_task, _available_issue_snapshot_task, _push_poll_task
|
||||
global _readiness_task
|
||||
gitea_proxy.start_client()
|
||||
_readiness_task = asyncio.create_task(_readiness_monitor())
|
||||
if _push_configuration().enabled:
|
||||
_push_poll_task = asyncio.create_task(_push_poll_loop())
|
||||
try:
|
||||
@@ -128,7 +140,8 @@ async def lifespan(_app: FastAPI):
|
||||
live_task = _live_snapshot_task
|
||||
available_task = _available_issue_snapshot_task
|
||||
push_task = _push_poll_task
|
||||
for task in (live_task, available_task, push_task):
|
||||
readiness_task = _readiness_task
|
||||
for task in (live_task, available_task, push_task, readiness_task):
|
||||
if task is not None and not task.done():
|
||||
task.cancel()
|
||||
try:
|
||||
@@ -145,6 +158,8 @@ async def lifespan(_app: FastAPI):
|
||||
_available_issue_snapshot_task = None
|
||||
if _push_poll_task is push_task:
|
||||
_push_poll_task = None
|
||||
if _readiness_task is readiness_task:
|
||||
_readiness_task = None
|
||||
|
||||
|
||||
app = FastAPI(title="Stackchain Dashboard", lifespan=lifespan)
|
||||
@@ -153,6 +168,60 @@ app.add_middleware(NegotiatedGZipMiddleware, minimum_size=1_024)
|
||||
CONTEXT_TIMEOUT_SECONDS = 5.0
|
||||
EVENT_STREAM_TIMEOUT_SECONDS = 5.0
|
||||
READINESS_TIMEOUT_SECONDS = 5.0
|
||||
READINESS_INTERVAL_SECONDS = max(
|
||||
READINESS_TIMEOUT_SECONDS,
|
||||
float(os.getenv("STACKCHAIN_READINESS_INTERVAL_SECONDS", "30")),
|
||||
)
|
||||
READINESS_MAX_AGE_SECONDS = max(
|
||||
READINESS_INTERVAL_SECONDS + READINESS_TIMEOUT_SECONDS + 5.0,
|
||||
float(os.getenv("STACKCHAIN_READINESS_MAX_AGE_SECONDS", "65")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReadinessState:
|
||||
checked_at: float
|
||||
ready: bool
|
||||
login: str | None = None
|
||||
error: str | None = None
|
||||
timed_out: bool = False
|
||||
|
||||
|
||||
_readiness_state: ReadinessState | None = None
|
||||
|
||||
|
||||
async def _check_readiness() -> None:
|
||||
global _readiness_state
|
||||
checked_at = time.monotonic()
|
||||
try:
|
||||
user = await asyncio.wait_for(current_user(), timeout=READINESS_TIMEOUT_SECONDS)
|
||||
if not isinstance(user, dict) or not user.get("login"):
|
||||
raise ReadinessPayloadError(
|
||||
"Gitea current-user response did not include a login"
|
||||
)
|
||||
except Exception as exc:
|
||||
timed_out = isinstance(exc, TimeoutError)
|
||||
error = (
|
||||
f"Gitea readiness check timed out after {READINESS_TIMEOUT_SECONDS:g}s"
|
||||
if timed_out
|
||||
else (
|
||||
str(exc)
|
||||
if isinstance(exc, ReadinessPayloadError)
|
||||
else "Gitea readiness check is temporarily unavailable"
|
||||
)
|
||||
)
|
||||
_readiness_state = ReadinessState(
|
||||
checked_at=checked_at,
|
||||
ready=False,
|
||||
error=error,
|
||||
timed_out=timed_out,
|
||||
)
|
||||
return
|
||||
_readiness_state = ReadinessState(
|
||||
checked_at=checked_at,
|
||||
ready=True,
|
||||
login=user["login"],
|
||||
)
|
||||
REVIEW_DETAIL_TIMEOUT_SECONDS = 5.0
|
||||
ISSUE_ACTION_TIMEOUT_SECONDS = 5.0
|
||||
ISSUE_CREATION_IDEMPOTENCY_TTL_SECONDS = 600.0
|
||||
@@ -181,6 +250,7 @@ AVAILABLE_ISSUE_SNAPSHOT_LEASE_SECONDS = WORK_PAGE_TIMEOUT_SECONDS + 1.0
|
||||
FRONTEND_DIR = Path(__file__).resolve().parent.parent / "frontend"
|
||||
_live_snapshot_task: asyncio.Task | None = None
|
||||
_push_poll_task: asyncio.Task | None = None
|
||||
_readiness_task: asyncio.Task | None = None
|
||||
_live_snapshot_value: dict | None = None
|
||||
_live_snapshot_created_at: float | None = None
|
||||
LIVE_SNAPSHOT_SECTIONS = ("context", "events", "notifications")
|
||||
@@ -2358,43 +2428,35 @@ async def sign_out_all_devices(
|
||||
|
||||
@app.get("/readyz")
|
||||
async def readiness():
|
||||
"""Return readiness after verifying the configured Gitea connection."""
|
||||
try:
|
||||
user = await asyncio.wait_for(
|
||||
current_user(), timeout=READINESS_TIMEOUT_SECONDS
|
||||
)
|
||||
if not isinstance(user, dict) or not user.get("login"):
|
||||
raise ReadinessPayloadError(
|
||||
"Gitea current-user response did not include a login"
|
||||
)
|
||||
except Exception as exc:
|
||||
timed_out = isinstance(exc, TimeoutError)
|
||||
error_message = (
|
||||
f"Gitea readiness check timed out after {READINESS_TIMEOUT_SECONDS:g}s"
|
||||
if timed_out
|
||||
else (
|
||||
str(exc)
|
||||
if isinstance(exc, ReadinessPayloadError)
|
||||
else "Gitea readiness check is temporarily unavailable"
|
||||
)
|
||||
)
|
||||
"""Return the latest readiness snapshot without contacting Gitea."""
|
||||
state = _readiness_state
|
||||
if state is None or time.monotonic() - state.checked_at > READINESS_MAX_AGE_SECONDS:
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "not_ready",
|
||||
"service": "stackchain-dashboard",
|
||||
"error": error_message,
|
||||
"error": "Gitea readiness status is not available",
|
||||
},
|
||||
status_code=503,
|
||||
)
|
||||
if not state.ready:
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "not_ready",
|
||||
"service": "stackchain-dashboard",
|
||||
"error": state.error,
|
||||
},
|
||||
status_code=503,
|
||||
headers={
|
||||
"Retry-After": str(max(1, math.ceil(READINESS_TIMEOUT_SECONDS)))
|
||||
} if timed_out else None,
|
||||
} if state.timed_out else None,
|
||||
)
|
||||
payload = {
|
||||
"status": "ready",
|
||||
"service": "stackchain-dashboard",
|
||||
}
|
||||
if not dashboard_auth.enabled():
|
||||
payload["gitea_user"] = user["login"]
|
||||
payload["gitea_user"] = state.login
|
||||
return payload
|
||||
|
||||
|
||||
@@ -2705,14 +2767,18 @@ async def _available_issue_snapshot() -> tuple[list[dict], bool, bool, bool]:
|
||||
if _available_issue_snapshot_value is not None:
|
||||
return _available_issue_snapshot_value, True, True, False
|
||||
if not local_refresh:
|
||||
for _ in range(50):
|
||||
wait_deadline = time.monotonic() + WORK_PAGE_TIMEOUT_SECONDS
|
||||
while time.monotonic() < wait_deadline:
|
||||
await asyncio.sleep(0.02)
|
||||
shared = await asyncio.to_thread(_available_issue_snapshot_store.load)
|
||||
if shared.items is not None:
|
||||
return shared.items, False, False, False
|
||||
if not shared.refreshing:
|
||||
break
|
||||
raise RuntimeError("available issue catalog refresh is owned by another worker")
|
||||
local_refresh = await _start_available_issue_refresh()
|
||||
if local_refresh:
|
||||
break
|
||||
if not local_refresh:
|
||||
raise RuntimeError("available issue catalog refresh is owned by another worker")
|
||||
try:
|
||||
return await asyncio.shield(_available_issue_snapshot_task), False, False, False
|
||||
except Exception:
|
||||
|
||||
+10
-2
@@ -30,10 +30,14 @@ class TodayStore:
|
||||
self.operation_retention_seconds = operation_retention_seconds
|
||||
self.recap_limit = recap_limit
|
||||
self.clock = clock
|
||||
self._initialize()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
def _initialize(self) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
connection = sqlite3.connect(self.path, timeout=self.timeout)
|
||||
if connection.execute("PRAGMA user_version").fetchone()[0] >= 1:
|
||||
connection.close()
|
||||
return
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
connection.execute(
|
||||
"""
|
||||
@@ -101,8 +105,12 @@ class TodayStore:
|
||||
)
|
||||
"""
|
||||
)
|
||||
connection.execute("PRAGMA user_version = 1")
|
||||
connection.commit()
|
||||
return connection
|
||||
connection.close()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
return sqlite3.connect(self.path, timeout=self.timeout)
|
||||
|
||||
def _record_operation(self, connection: sqlite3.Connection, login: str, operation_id: str) -> None:
|
||||
now = self.clock()
|
||||
|
||||
@@ -2046,6 +2046,7 @@ async def test_public_routes_remain_available_and_readiness_hides_identity(acces
|
||||
return {"id": 1, "login": "timmy"}
|
||||
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
await main._check_readiness()
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
health = await client.get("/healthz")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
@@ -245,6 +246,7 @@ async def test_application_lifespan_opens_and_closes_gitea_transport(monkeypatch
|
||||
calls = []
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "start_client", lambda: calls.append("start"))
|
||||
monkeypatch.setattr(main, "_check_readiness", AsyncMock())
|
||||
|
||||
async def stop_client():
|
||||
calls.append("stop")
|
||||
@@ -270,6 +272,7 @@ async def test_application_shutdown_finishes_snapshot_before_closing_transport(m
|
||||
calls.append("snapshot cancelled")
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "start_client", lambda: calls.append("start"))
|
||||
monkeypatch.setattr(main, "_check_readiness", AsyncMock())
|
||||
|
||||
async def stop_client():
|
||||
assert main._live_snapshot_task is not None
|
||||
@@ -306,6 +309,7 @@ async def test_application_shutdown_cancels_available_work_scan_before_transport
|
||||
calls.append("available scan cancelled")
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "start_client", lambda: calls.append("start"))
|
||||
monkeypatch.setattr(main, "_check_readiness", AsyncMock())
|
||||
|
||||
async def stop_client():
|
||||
task = main._available_issue_snapshot_task
|
||||
@@ -341,6 +345,7 @@ async def test_application_shutdown_drains_authored_mutation_before_transport(mo
|
||||
return {"id": 461}
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "start_client", lambda: calls.append("start"))
|
||||
monkeypatch.setattr(main, "_check_readiness", AsyncMock())
|
||||
|
||||
async def stop_client():
|
||||
calls.append("stop")
|
||||
@@ -382,6 +387,7 @@ async def test_application_shutdown_bounds_and_settles_stalled_authored_mutation
|
||||
|
||||
monkeypatch.setattr(main, "AUTHORED_ACTION_SHUTDOWN_GRACE_SECONDS", 0.01)
|
||||
monkeypatch.setattr(gitea_proxy, "start_client", lambda: calls.append("start"))
|
||||
monkeypatch.setattr(main, "_check_readiness", AsyncMock())
|
||||
|
||||
async def stop_client():
|
||||
calls.append("stop")
|
||||
|
||||
@@ -354,6 +354,82 @@ async def test_available_issue_endpoint_reuses_catalog_published_by_another_work
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_available_issue_endpoint_waits_for_slow_cold_catalog_from_another_worker(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
now = 100.0
|
||||
path = tmp_path / "shared-available.sqlite3"
|
||||
owner_store = AvailableIssueSnapshotStore(path, clock=lambda: now)
|
||||
worker_store = AvailableIssueSnapshotStore(path, clock=lambda: now)
|
||||
owner = owner_store.try_acquire_refresh(lease_seconds=6)
|
||||
monkeypatch.setattr(main, "_available_issue_snapshot_store", worker_store)
|
||||
|
||||
sleep_calls = 0
|
||||
|
||||
async def publish_after_existing_one_second_window(_delay):
|
||||
nonlocal sleep_calls
|
||||
sleep_calls += 1
|
||||
if sleep_calls == 60:
|
||||
owner_store.publish(
|
||||
owner,
|
||||
items=[{"repository": "stackchain/api", "number": 8}],
|
||||
)
|
||||
|
||||
async def must_not_scan():
|
||||
raise AssertionError("a valid cross-worker lease must prevent a duplicate scan")
|
||||
|
||||
monkeypatch.setattr(main.asyncio, "sleep", publish_after_existing_one_second_window)
|
||||
monkeypatch.setattr(main.gitea_proxy, "available_issue_snapshot", must_not_scan)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/api/v1/available-issues?page=1")
|
||||
|
||||
assert sleep_calls > 50
|
||||
assert response.status_code == 200
|
||||
assert response.json()["items"] == [
|
||||
{"repository": "stackchain/api", "number": 8}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_available_issue_endpoint_takes_over_released_cold_refresh(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
now = 100.0
|
||||
path = tmp_path / "shared-available.sqlite3"
|
||||
owner_store = AvailableIssueSnapshotStore(path, clock=lambda: now)
|
||||
worker_store = AvailableIssueSnapshotStore(path, clock=lambda: now)
|
||||
owner = owner_store.try_acquire_refresh(lease_seconds=6)
|
||||
monkeypatch.setattr(main, "_available_issue_snapshot_store", worker_store)
|
||||
|
||||
sleep_calls = 0
|
||||
scan_calls = 0
|
||||
|
||||
async def release_failed_owner(_delay):
|
||||
nonlocal sleep_calls
|
||||
sleep_calls += 1
|
||||
if sleep_calls == 3:
|
||||
owner_store.release_refresh(owner)
|
||||
|
||||
async def available():
|
||||
nonlocal scan_calls
|
||||
scan_calls += 1
|
||||
return [{"repository": "stackchain/web", "number": 9}]
|
||||
|
||||
monkeypatch.setattr(main.asyncio, "sleep", release_failed_owner)
|
||||
monkeypatch.setattr(main.gitea_proxy, "available_issue_snapshot", available)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/api/v1/available-issues?page=1")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["items"] == [
|
||||
{"repository": "stackchain/web", "number": 9}
|
||||
]
|
||||
assert scan_calls == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_available_issue_endpoint_coalesces_cold_scan_and_reuses_it_for_pages(monkeypatch):
|
||||
calls = 0
|
||||
|
||||
@@ -11,6 +11,49 @@ def test_health_endpoint_reports_service_liveness_without_gitea_access():
|
||||
assert main.health() == {"status": "ok", "service": "stackchain-dashboard"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_readiness_endpoint_never_contacts_gitea_for_a_request(monkeypatch):
|
||||
calls = 0
|
||||
|
||||
async def unexpected_user_lookup():
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
raise AssertionError("request-time readiness must not contact Gitea")
|
||||
|
||||
monkeypatch.setattr(main, "_readiness_state", None, raising=False)
|
||||
monkeypatch.setattr(main, "current_user", unexpected_user_lookup)
|
||||
|
||||
first = await main.readiness()
|
||||
second = await main.readiness()
|
||||
|
||||
assert first.status_code == 503
|
||||
assert second.status_code == 503
|
||||
assert calls == 0
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_readiness_monitor_refreshes_on_an_interval_and_cancels(monkeypatch):
|
||||
calls = 0
|
||||
refreshed_twice = asyncio.Event()
|
||||
|
||||
async def check():
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 2:
|
||||
refreshed_twice.set()
|
||||
|
||||
monkeypatch.setattr(main, "_check_readiness", check)
|
||||
monkeypatch.setattr(main, "READINESS_INTERVAL_SECONDS", 0.01, raising=False)
|
||||
|
||||
task = asyncio.create_task(main._readiness_monitor())
|
||||
await asyncio.wait_for(refreshed_twice.wait(), timeout=0.2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
assert calls == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_readiness_endpoint_reports_connected_gitea_user(monkeypatch):
|
||||
async def connected_user():
|
||||
@@ -18,6 +61,8 @@ async def test_readiness_endpoint_reports_connected_gitea_user(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(main, "current_user", connected_user)
|
||||
|
||||
await main._check_readiness()
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert any(getattr(route, "path", None) == "/readyz" for route in main.app.routes)
|
||||
@@ -35,6 +80,8 @@ async def test_readiness_endpoint_hides_unexpected_upstream_error_details(monkey
|
||||
|
||||
monkeypatch.setattr(main, "current_user", unavailable_user)
|
||||
|
||||
await main._check_readiness()
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert response.status_code == 503
|
||||
@@ -53,6 +100,8 @@ async def test_readiness_endpoint_returns_503_for_null_current_user_payload(monk
|
||||
|
||||
monkeypatch.setattr(main, "current_user", null_user)
|
||||
|
||||
await main._check_readiness()
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert response.status_code == 503
|
||||
@@ -77,6 +126,8 @@ async def test_readiness_endpoint_times_out_and_cancels_stalled_gitea_check(monk
|
||||
monkeypatch.setattr(main, "READINESS_TIMEOUT_SECONDS", 0.01, raising=False)
|
||||
monkeypatch.setattr(main, "current_user", hanging_user)
|
||||
|
||||
await main._check_readiness()
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert response.status_code == 503
|
||||
@@ -87,3 +138,18 @@ async def test_readiness_endpoint_times_out_and_cancels_stalled_gitea_check(monk
|
||||
"error": "Gitea readiness check timed out after 0.01s",
|
||||
}
|
||||
assert cancelled.is_set()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_readiness_endpoint_expires_a_stale_healthy_snapshot(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
main,
|
||||
"_readiness_state",
|
||||
main.ReadinessState(checked_at=10.0, ready=True, login="timmy"),
|
||||
)
|
||||
monkeypatch.setattr(main.time, "monotonic", lambda: 76.0)
|
||||
|
||||
response = await main.readiness()
|
||||
|
||||
assert response.status_code == 503
|
||||
assert json.loads(response.body)["error"] == "Gitea readiness status is not available"
|
||||
@@ -65,6 +65,23 @@ def test_deferrals_are_durable_revisioned_idempotent_and_account_scoped(tmp_path
|
||||
) == {"revision": 2, "records": {}}
|
||||
|
||||
|
||||
def test_initialized_later_reads_remain_available_during_a_planning_write(tmp_path):
|
||||
path = tmp_path / "later.sqlite3"
|
||||
store = LaterStore(path, timeout=0.05)
|
||||
expected = store.apply(
|
||||
"timmy", "seed", "defer", "issue:r:1:",
|
||||
wake_at="2026-08-10T09:00:00.000Z",
|
||||
)
|
||||
|
||||
writer = sqlite3.connect(path)
|
||||
writer.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
assert LaterStore(path, timeout=0.05).get("timmy") == expected
|
||||
finally:
|
||||
writer.rollback()
|
||||
writer.close()
|
||||
|
||||
|
||||
def test_batch_applies_in_one_ordered_idempotent_unit(tmp_path):
|
||||
store = LaterStore(tmp_path / "later.sqlite3")
|
||||
operations = [
|
||||
|
||||
@@ -14,10 +14,11 @@ def test_mobile_launch_selects_priority_queue_without_overriding_saved_choice():
|
||||
script = f"""
|
||||
const mobileLaunch = require({json.dumps(str(MOBILE_LAUNCH))});
|
||||
process.stdout.write(JSON.stringify({{
|
||||
today: mobileLaunch.chooseFilter({{saved:null, today:2, attention:4}}),
|
||||
attention: mobileLaunch.chooseFilter({{saved:null, today:0, attention:4}}),
|
||||
all: mobileLaunch.chooseFilter({{saved:null, today:0, attention:0}}),
|
||||
saved: mobileLaunch.chooseFilter({{saved:'review', today:2, attention:4}}),
|
||||
today: mobileLaunch.chooseFilter({{saved:null, today:2, attention:4, agenda:6}}),
|
||||
attention: mobileLaunch.chooseFilter({{saved:null, today:0, attention:4, agenda:6}}),
|
||||
agenda: mobileLaunch.chooseFilter({{saved:null, today:0, attention:0, agenda:6}}),
|
||||
all: mobileLaunch.chooseFilter({{saved:null, today:0, attention:0, agenda:0}}),
|
||||
saved: mobileLaunch.chooseFilter({{saved:'agenda', today:2, attention:4, agenda:6}}),
|
||||
}}));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
@@ -26,8 +27,9 @@ process.stdout.write(JSON.stringify({{
|
||||
assert json.loads(result.stdout) == {
|
||||
"today": "today",
|
||||
"attention": "attention",
|
||||
"agenda": "agenda",
|
||||
"all": "all",
|
||||
"saved": "review",
|
||||
"saved": "agenda",
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +66,7 @@ async def test_mobile_launch_progressively_discloses_secondary_controls():
|
||||
service_worker = (Path(__file__).resolve().parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
assert "BASE + 'static/mobile-launch.js'" in service_worker
|
||||
assert "mobileLaunch.chooseFilter" in html
|
||||
assert "agenda: counts.agenda" in html
|
||||
assert "mobileLaunch.createDisclosure" in html
|
||||
assert "@media (max-width: 600px)" in html
|
||||
assert "header { min-height:56px; max-height:64px;" in html
|
||||
|
||||
@@ -13,7 +13,7 @@ QUEUE_LAUNCHER = Path(__file__).resolve().parents[1] / "frontend" / "mobile-queu
|
||||
TIMER = Path(__file__).resolve().parents[1] / "frontend" / "today-timer.js"
|
||||
|
||||
|
||||
def test_mobile_work_entry_prioritizes_continue_resume_start_plan_then_fallback():
|
||||
def test_mobile_work_entry_prioritizes_continue_resume_start_plan_then_find():
|
||||
script = f"""
|
||||
const createEntry = require({json.dumps(str(ENTRY))});
|
||||
const state = {{active:true, resumable:true, today:2, eligible:3}};
|
||||
@@ -27,7 +27,7 @@ const entry = createEntry({{
|
||||
resumeToday: () => calls.push('resume'),
|
||||
startToday: () => calls.push('start'),
|
||||
planToday: () => calls.push('plan'),
|
||||
openFallback: () => calls.push('fallback'),
|
||||
findWork: () => calls.push('find'),
|
||||
}});
|
||||
const modes = [];
|
||||
modes.push(entry.open());
|
||||
@@ -43,8 +43,8 @@ process.stdout.write(JSON.stringify({{modes, calls}}));
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"modes": ["continue", "resume", "start", "plan", "work"],
|
||||
"calls": ["continue", "resume", "start", "plan", "fallback"],
|
||||
"modes": ["continue", "resume", "start", "plan", "find"],
|
||||
"calls": ["continue", "resume", "start", "plan", "find"],
|
||||
}
|
||||
|
||||
|
||||
@@ -165,10 +165,10 @@ dock.updateWork('start', 0);
|
||||
const starting = {{ text:workLabel.textContent, label:work.attributes['aria-label'] }};
|
||||
dock.updateWork('plan', 0);
|
||||
const planning = {{ text:workLabel.textContent, label:work.attributes['aria-label'] }};
|
||||
dock.updateWork('work', 0);
|
||||
dock.updateWork('find', 0);
|
||||
process.stdout.write(JSON.stringify({{
|
||||
continuing, resuming, starting, planning,
|
||||
fallback:{{ text:workLabel.textContent, label:work.attributes['aria-label'] }},
|
||||
finding:{{ text:workLabel.textContent, label:work.attributes['aria-label'] }},
|
||||
}}));
|
||||
"""
|
||||
result = subprocess.run(
|
||||
@@ -184,7 +184,7 @@ process.stdout.write(JSON.stringify({{
|
||||
"resuming": {"text": "Resume", "label": "Resume Today"},
|
||||
"starting": {"text": "Start", "label": "Start Today"},
|
||||
"planning": {"text": "Plan", "label": "Plan Today"},
|
||||
"fallback": {"text": "Work", "label": "Work"},
|
||||
"finding": {"text": "Find", "label": "Find work"},
|
||||
}
|
||||
|
||||
|
||||
@@ -372,7 +372,7 @@ def test_mobile_queue_launcher_recommends_and_revalidates_cross_queue_continuati
|
||||
script = f"""
|
||||
const createLauncher = require({json.dumps(str(QUEUE_LAUNCHER))});
|
||||
const calls = [];
|
||||
let counts = {{attention: 2, today: 1, later: 4, draft: 3}};
|
||||
let counts = {{attention: 2, today: 1, agenda: 5, later: 4, draft: 3}};
|
||||
const launcher = createLauncher({{
|
||||
openToday: () => calls.push('today'),
|
||||
selectFilter: name => calls.push('filter:' + name),
|
||||
@@ -382,21 +382,23 @@ const launcher = createLauncher({{
|
||||
openFindWork: () => calls.push('find'),
|
||||
}});
|
||||
const first = launcher.recommend();
|
||||
counts = {{attention: 0, today: 0, later: 4, draft: 3}};
|
||||
counts = {{attention: 0, today: 0, agenda: 5, later: 4, draft: 3}};
|
||||
const agenda = launcher.recommend();
|
||||
const opened = launcher.continueWork();
|
||||
counts = {{attention: 0, today: 0, later: 0, draft: 0}};
|
||||
counts = {{attention: 0, today: 0, agenda: 0, later: 0, draft: 0}};
|
||||
const fallback = launcher.recommend();
|
||||
launcher.continueWork();
|
||||
process.stdout.write(JSON.stringify({{first, opened, fallback, calls}}));
|
||||
process.stdout.write(JSON.stringify({{first, agenda, opened, fallback, calls}}));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"first": {"name": "attention", "count": 2, "label": "Start Attention (2)"},
|
||||
"agenda": {"name": "agenda", "count": 5, "label": "Open Agenda (5)"},
|
||||
"opened": "opened",
|
||||
"fallback": {"name": "find", "count": 0, "label": "Find Work"},
|
||||
"calls": ["filter:later", "open:later", "find"],
|
||||
"calls": ["filter:agenda", "open:agenda", "find"],
|
||||
}
|
||||
|
||||
|
||||
@@ -420,6 +422,12 @@ async def test_dashboard_renders_and_wires_mobile_queue_switcher():
|
||||
assert 'id="mobile-queue-sheet"' in html
|
||||
assert 'aria-labelledby="mobile-queue-heading"' in html
|
||||
assert 'data-mobile-queue="today"' in html
|
||||
assert 'data-mobile-queue="agenda"' in html
|
||||
assert '<strong>Agenda</strong><small>Upcoming deadlines</small>' in html
|
||||
assert 'data-work-filter="agenda"' in html
|
||||
assert "const agendaItems = agendaMyWork(activeMyWork);" in html
|
||||
assert "counts.agenda = agendaItems.length;" in html
|
||||
assert 'data-agenda-group' in html
|
||||
assert 'data-mobile-queue="attention"' in html
|
||||
assert 'data-mobile-queue="update"' in html
|
||||
assert '<strong>Updates</strong><small>Unread conversations</small>' in html
|
||||
|
||||
+116
-6
@@ -8,6 +8,22 @@ import pytest
|
||||
from tests.dashboard_bundle import dashboard
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_empty_all_work_queue_offers_find_and_create_actions():
|
||||
markup = (Path(__file__).resolve().parents[1] / "frontend" / "index.html").read_text()
|
||||
source = await dashboard()
|
||||
|
||||
assert 'id="empty-work-start"' in markup
|
||||
assert 'Ready for something new?' in markup
|
||||
assert 'id="empty-work-find"' in markup
|
||||
assert 'id="empty-work-create"' in markup
|
||||
assert "qs('#empty-work-find').addEventListener('click'" in source
|
||||
assert "qs('#find-work').click()" in source
|
||||
assert "qs('#empty-work-create').addEventListener('click'" in source
|
||||
assert "qs('#new-issue').click()" in source
|
||||
assert "emptyWorkStart.hidden = !showEmptyStart" in source
|
||||
|
||||
|
||||
MY_WORK = Path(__file__).parents[1] / "frontend" / "my-work.js"
|
||||
NOTIFICATION_UNDO = Path(__file__).parents[1] / "frontend" / "notification-undo.js"
|
||||
TODAY_TIMER = Path(__file__).parents[1] / "frontend" / "today-timer.js"
|
||||
@@ -118,6 +134,99 @@ process.stdout.write(JSON.stringify({{
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_agenda_groups_assigned_deadlines_in_local_seven_day_horizon():
|
||||
script = f"""
|
||||
const work = require({json.dumps(str(MY_WORK))});
|
||||
const now = new Date('2026-08-12T12:00:00');
|
||||
const items = [
|
||||
{{kind:'issue', key:'o/r#5', repository:'o/r', number:5, is_assigned:true, due_date:'2026-08-11T18:00:00'}},
|
||||
{{kind:'issue', key:'o/r#3', repository:'o/r', number:3, is_assigned:true, due_date:'2026-08-12T17:00:00'}},
|
||||
{{kind:'issue', key:'a/r#9', repository:'a/r', number:9, is_assigned:true, due_date:'2026-08-13T09:00:00'}},
|
||||
{{kind:'issue', key:'a/r#2', repository:'a/r', number:2, is_assigned:true, due_date:'2026-08-18T09:00:00'}},
|
||||
{{kind:'issue', key:'a/r#1', repository:'a/r', number:1, is_assigned:true, due_date:'2026-08-20T09:00:00'}},
|
||||
{{kind:'issue', key:'a/r#7', repository:'a/r', number:7, is_assigned:false, due_date:'2026-08-13T08:00:00'}},
|
||||
{{kind:'pull', key:'a/r#8', repository:'a/r', number:8, is_assigned:true, due_date:'2026-08-13T08:00:00'}},
|
||||
{{kind:'issue', key:'a/r#6', repository:'a/r', number:6, is_assigned:true}},
|
||||
];
|
||||
process.stdout.write(JSON.stringify(work.agendaMyWork(items, now).map(item => [item.key, item.agenda_group])));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == [
|
||||
["o/r#5", "Overdue"], ["o/r#3", "Today"],
|
||||
["a/r#9", "Tomorrow"], ["a/r#2", "Next 7 days"],
|
||||
]
|
||||
|
||||
|
||||
def test_mobile_agenda_sorts_equal_deadlines_by_repository_and_number():
|
||||
script = f"""
|
||||
const work = require({json.dumps(str(MY_WORK))});
|
||||
const items = [
|
||||
{{kind:'issue', key:'z/r#1', repository:'z/r', number:1, is_assigned:true, due_date:'2026-08-14T09:00:00'}},
|
||||
{{kind:'issue', key:'a/r#10', repository:'a/r', number:10, is_assigned:true, due_date:'2026-08-14T09:00:00'}},
|
||||
{{kind:'issue', key:'a/r#2', repository:'a/r', number:2, is_assigned:true, due_date:'2026-08-14T09:00:00'}},
|
||||
];
|
||||
process.stdout.write(JSON.stringify(work.agendaMyWork(items, new Date('2026-08-12T12:00:00')).map(item => item.key)));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == ["a/r#2", "a/r#10", "z/r#1"]
|
||||
|
||||
|
||||
def test_agenda_pager_loads_every_issue_page_single_flight_and_retries_failed_page():
|
||||
script = f"""
|
||||
const work = require({json.dumps(str(MY_WORK))});
|
||||
const calls = [];
|
||||
let failPage = 3;
|
||||
let items = [{{id:1, title:'first'}}];
|
||||
let pagination = {{issue:{{page:1,total:4,has_more:true}}}};
|
||||
const pager = work.createWorkPager({{
|
||||
load: async (stream, page) => {{
|
||||
calls.push(page);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
if (page === failPage) throw new Error('offline');
|
||||
return {{page,total:4,has_more:page < 4,items:[{{id:page,title:'page '+page}}]}};
|
||||
}},
|
||||
onItems: (_stream, next) => {{ items = next; }},
|
||||
onPagination: next => {{ pagination = next; }},
|
||||
onStatus: () => {{}},
|
||||
}});
|
||||
pager.reset(pagination);
|
||||
async function run() {{
|
||||
const first = pager.loadAll('issue', () => items);
|
||||
const duplicate = pager.loadAll('issue', () => items);
|
||||
const failed = await first;
|
||||
const samePromise = first === duplicate;
|
||||
failPage = 0;
|
||||
const retried = await pager.loadAll('issue', () => items);
|
||||
process.stdout.write(JSON.stringify({{
|
||||
failed, samePromise, retried, calls, ids:items.map(item => item.id), pagination,
|
||||
}}));
|
||||
}}
|
||||
run();
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"failed": False,
|
||||
"samePromise": True,
|
||||
"retried": True,
|
||||
"calls": [2, 3, 3, 4],
|
||||
"ids": [1, 2, 3, 4],
|
||||
"pagination": {"issue": {"page": 4, "total": 4, "has_more": False}},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_agenda_activation_checks_all_issue_pages_before_showing_empty_state():
|
||||
html = await dashboard()
|
||||
|
||||
assert "workPager.loadAll('issue'" in html
|
||||
assert "Checking all assigned deadlines…" in html
|
||||
assert "Agenda check paused. Retry to check older assigned deadlines." in html
|
||||
assert "selectedWorkFilter === 'agenda' && workPagination.issue?.has_more" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_queue_finder_is_labeled_thumb_safe_and_offers_older_search():
|
||||
html = await dashboard()
|
||||
@@ -604,12 +713,12 @@ process.stdout.write(JSON.stringify({{calls, hash:location.hash, parsed:routes.p
|
||||
def test_every_mobile_queue_route_survives_hydration_and_detail_back_navigation():
|
||||
script = f"""
|
||||
const routes = require({json.dumps(str(WORK_ROUTE))});
|
||||
const canonical = ['today', 'attention', 'updates', 'later', 'drafts'];
|
||||
const canonical = ['today', 'agenda', 'attention', 'updates', 'later', 'drafts'];
|
||||
const parsed = canonical.map(name => [name, routes.parse('#/my-work/' + name)]);
|
||||
const listeners = {{}};
|
||||
const location = {{hash:'#/my-work/later'}};
|
||||
const location = {{hash:'#/my-work/agenda'}};
|
||||
const calls = [];
|
||||
const stack = ['#/my-work/later'];
|
||||
const stack = ['#/my-work/agenda'];
|
||||
let cursor = 0;
|
||||
const history = {{
|
||||
pushState(state, _, hash) {{ stack.splice(cursor + 1); stack.push(hash); cursor += 1; location.hash = hash; }},
|
||||
@@ -638,16 +747,17 @@ process.stdout.write(JSON.stringify({{parsed, calls, hash:location.hash}}));
|
||||
assert json.loads(result.stdout) == {
|
||||
"parsed": [
|
||||
["today", {"kind": "queue", "filter": "today"}],
|
||||
["agenda", {"kind": "queue", "filter": "agenda"}],
|
||||
["attention", {"kind": "queue", "filter": "attention"}],
|
||||
["updates", {"kind": "queue", "filter": "update"}],
|
||||
["later", {"kind": "queue", "filter": "later"}],
|
||||
["drafts", {"kind": "queue", "filter": "draft"}],
|
||||
],
|
||||
"calls": [
|
||||
["queue", "later"],
|
||||
["queue", "agenda"],
|
||||
["open", 42],
|
||||
["close"],
|
||||
["queue", "later"],
|
||||
["queue", "agenda"],
|
||||
["queue", "draft"],
|
||||
],
|
||||
"hash": "#/my-work/drafts",
|
||||
@@ -5861,7 +5971,7 @@ async def test_mobile_filters_wrap_show_counts_and_persist_for_the_session():
|
||||
assert 'data-work-count="review"' in html
|
||||
assert 'data-work-count="update"' in html
|
||||
assert 'data-work-count="later"' in html
|
||||
assert "['all', 'today', 'attention', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)" in html
|
||||
assert "['all', 'today', 'agenda', 'attention', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)" in html
|
||||
assert 'data-work-count="draft"' in html
|
||||
assert 'sessionStorage.getItem(WORK_FILTER_KEY)' in html
|
||||
assert 'sessionStorage.setItem(WORK_FILTER_KEY, selectedWorkFilter)' in html
|
||||
|
||||
+20
-10
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
@@ -275,6 +274,8 @@ async def test_recap_time_logging_attempts_multiple_entries_with_bounded_concurr
|
||||
active = 0
|
||||
peak = 0
|
||||
attempted = []
|
||||
first_wave_started = asyncio.Event()
|
||||
release_first_wave = asyncio.Event()
|
||||
|
||||
async def user():
|
||||
return {"id": 1, "login": "Timmy"}
|
||||
@@ -284,8 +285,10 @@ async def test_recap_time_logging_attempts_multiple_entries_with_bounded_concurr
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
attempted.append(identity)
|
||||
if len(attempted) == 3:
|
||||
first_wave_started.set()
|
||||
try:
|
||||
await asyncio.sleep(0.1)
|
||||
await release_first_wave.wait()
|
||||
finally:
|
||||
active -= 1
|
||||
|
||||
@@ -305,17 +308,24 @@ async def test_recap_time_logging_attempts_multiple_entries_with_bounded_concurr
|
||||
await client.post("/api/v1/session", json={"access_token": "correct horse battery staple"})
|
||||
headers = {"Origin": "https://test", "X-CSRF-Token": client.cookies["stackchain_csrf"]}
|
||||
grant = await recap_time_grant(client, headers, payload)
|
||||
started = time.perf_counter()
|
||||
response = await client.post(
|
||||
"/api/v1/today/recaps/log-time",
|
||||
json=payload,
|
||||
headers={**headers, "X-Step-Up-Grant": grant},
|
||||
request = asyncio.create_task(
|
||||
client.post(
|
||||
"/api/v1/today/recaps/log-time",
|
||||
json=payload,
|
||||
headers={**headers, "X-Step-Up-Grant": grant},
|
||||
)
|
||||
)
|
||||
elapsed = time.perf_counter() - started
|
||||
await asyncio.wait_for(first_wave_started.wait(), timeout=1)
|
||||
await asyncio.sleep(0)
|
||||
assert active == 3
|
||||
assert peak == 3
|
||||
assert len(attempted) == 3
|
||||
assert not request.done()
|
||||
release_first_wave.set()
|
||||
response = await request
|
||||
|
||||
assert response.status_code == 200
|
||||
assert elapsed < 0.35
|
||||
assert 1 < peak <= 3
|
||||
assert peak == 3
|
||||
assert set(attempted) == set(identities)
|
||||
assert response.json()["time_logs"] == [
|
||||
{"identity": identity, "status": "logged"} for identity in identities
|
||||
|
||||
@@ -67,6 +67,20 @@ def test_operations_are_durable_ordered_idempotent_and_account_scoped(tmp_path):
|
||||
}
|
||||
|
||||
|
||||
def test_initialized_today_reads_remain_available_during_a_planning_write(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
store = TodayStore(path, timeout=0.05)
|
||||
expected = store.apply("timmy", "seed", "add", "issue:r:1:")
|
||||
|
||||
writer = sqlite3.connect(path)
|
||||
writer.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
assert TodayStore(path, timeout=0.05).get("timmy") == expected
|
||||
finally:
|
||||
writer.rollback()
|
||||
writer.close()
|
||||
|
||||
|
||||
def test_capacity_and_estimates_are_durable_account_scoped_and_follow_item_identity(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
store = TodayStore(path, limit=3)
|
||||
|
||||
Reference in new issue
Block a user