Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a3fb180ed | ||
|
|
74d1435ca7 | ||
|
|
8989e93c2c | ||
|
|
7b3b7dadb9 | ||
|
|
05f9e06a10 | ||
|
|
e0de45ea90 | ||
|
|
3224389441 | ||
|
|
63723e7fa3 | ||
|
|
740e91a615 | ||
|
|
0363f23cef | ||
|
|
2cbeba30fd | ||
|
|
43595de52f | ||
|
|
c451cd0bcb | ||
|
|
ad27db6846 | ||
|
|
791082bae2 | ||
|
|
d3ed0cca0c | ||
|
|
ccb595a081 | ||
|
|
7b1c9a608c | ||
|
|
854d040e88 | ||
|
|
95baa20eeb | ||
|
|
0cf88d7d7a | ||
|
|
969d5567d4 |
No files matched your search
@@ -37,10 +37,16 @@ the private content. Issue capture and authored mobile actions (issue
|
||||
comments, pull-request comments, notification replies, and reviews) persist per-draft
|
||||
idempotency keys, so retrying after a timeout, reload, process restart, or handoff to
|
||||
another worker replays a confirmed result instead of posting duplicate content. The ordered,
|
||||
five-item Today plan syncs across the operator's devices. Starting a Today work session also
|
||||
five-item Today plan syncs across the operator's devices. Adding an issue through **Plan Today**
|
||||
first previews its Gitea dependencies: unresolved blockers are listed with links and require the
|
||||
explicit **Add blocked item anyway** override, while an unavailable dependency lookup is reported
|
||||
as unknown rather than unblocked. Starting a Today work session also
|
||||
stores an account-bound checkpoint on the current device. After a reload or installed-app
|
||||
restart, **Resume Today** reopens the saved item (or the next surviving item if work changed);
|
||||
finishing or choosing **End session** clears only the checkpoint and leaves the Today plan
|
||||
**Comment & next** on that current issue or pull request posts the handoff online or admits it
|
||||
to durable account-bound delivery, then removes the item only from Today and opens the next
|
||||
one without closing or merging it. Delivery or local-admission failure preserves both the draft
|
||||
and checkpoint. Finishing or choosing **End session** clears only the checkpoint and leaves the Today plan
|
||||
unchanged. Another or unconfirmed account cannot see or resume it. Server revisions prevent delayed
|
||||
responses from replacing a newer plan; same-account browser tabs exchange fresh snapshots,
|
||||
and reconnecting or returning to the dashboard refreshes server truth after replaying queued
|
||||
@@ -218,12 +224,25 @@ below the route deadlines. Streaming diff reads share the same read capacity,
|
||||
while POST, PATCH, PUT, and DELETE requests are never coalesced.
|
||||
|
||||
Live snapshots expose independent `context`, `events`, and `notifications`
|
||||
revision tokens. Each bounded opaque token includes a per-process generation, so a token
|
||||
from another worker or from before a restart cannot suppress different content. The browser
|
||||
sends its known tokens on later polls, so `/api/v1/live` can omit unchanged section bodies
|
||||
while still returning current freshness and retry metadata. The client retains omitted data
|
||||
and only rebuilds or persists the sections that changed. Malformed or oversized tokens are
|
||||
rejected before any upstream work.
|
||||
revision tokens. Snapshot content, freshness/backoff metadata, and revisions are published
|
||||
atomically through a private SQLite store shared by all application workers. An expiring
|
||||
refresh lease ensures only one worker loads currently due sections; other workers serve the
|
||||
same stale snapshot while that refresh runs, and can recover an abandoned lease after expiry.
|
||||
Set `STACKCHAIN_LIVE_SNAPSHOT_DB` to override the default
|
||||
`STACKCHAIN_STATE_DIR/live-snapshot.sqlite3`; keep the containing directory on private,
|
||||
worker-shared writable storage. The database and directory are restricted to the service
|
||||
account and never contain the Gitea token. Each bounded opaque revision token includes the
|
||||
store generation, so a token from a different deployment or before replacement of the store
|
||||
cannot suppress different content. The browser sends its known tokens on later polls, so
|
||||
`/api/v1/live` can omit unchanged section bodies while still returning current freshness and
|
||||
retry metadata. The client retains omitted data and only rebuilds or persists the sections
|
||||
that changed. Malformed or oversized tokens are rejected before any upstream work.
|
||||
Confirmed notification acknowledgements update this worker's live view immediately, then
|
||||
maintain the shared snapshot outside the async request loop. Bulk acknowledgements remove
|
||||
all successful notification IDs in one SQLite transaction and advance the notification
|
||||
revision once. If shared-store lock admission fails after Gitea confirms the mutation, the
|
||||
API keeps the confirmed result and process-local filtering rather than falsely reporting the
|
||||
upstream write as failed; a later shared refresh reconciles the cache.
|
||||
|
||||
## Offline mobile shell
|
||||
|
||||
@@ -269,11 +288,13 @@ repository catalogs, events, raw patches, and complete API responses are exclude
|
||||
A cold offline launch labels the saved time. Cached Today details open in the existing
|
||||
phone sheet, where comments can enter the account-bound durable outbox. For issue and
|
||||
non-review pull details, planning, assignment, review, merge, and close controls remain disabled
|
||||
until reconnection. Cached
|
||||
requested reviews open in the existing review sheet so file progress, notes, summary,
|
||||
decision, and inline-comment drafts remain usable under the saved head SHA. Review
|
||||
submission is never queued: reconnect reloads the current head before enabling submit;
|
||||
a changed head starts clean SHA-scoped progress while retaining the prior-head draft.
|
||||
until reconnection. Cached requested reviews open in the existing review sheet so file progress, notes,
|
||||
summary, decision, and inline-comment drafts remain usable under the saved head SHA.
|
||||
**Queue review for reconnect** durably stores that complete SHA-bound review with one
|
||||
idempotency key. Reconnect or Background Sync submits it exactly once; transient failures
|
||||
retain the queue entry, while stale-head and invalid-inline-comment responses move it to
|
||||
Drafts as **Needs attention** without deleting feedback. Confirmed delivery removes the
|
||||
queued operation and its matching SHA-scoped draft and progress.
|
||||
Cached unread updates use the same phone conversation sheet and replies enter the
|
||||
account-bound durable outbox, while mark read, ownership, deferral, and older-message loading remain disabled until reconnection.
|
||||
Cards without a saved detail explain that reconnection is required. **Clear offline
|
||||
@@ -285,7 +306,8 @@ issue comments, pull-request comments, and unread-update replies use bounded loc
|
||||
outboxes when connectivity or a retryable server failure prevents delivery. Issue
|
||||
captures and authored messages are also mirrored into account-bound IndexedDB lanes
|
||||
and registered with Background Sync, so a supporting installed browser can deliver
|
||||
new issues, issue comments, pull-request comments, and unread-update replies after
|
||||
new issues, issue comments, pull-request comments, unread-update replies, and completed
|
||||
pull-request reviews after
|
||||
every dashboard client has closed. The worker verifies the current Gitea login, shares
|
||||
an atomic delivery claim with the foreground path, and preserves the original
|
||||
idempotency key. Installed browsers can explicitly enable **Notify me when queued
|
||||
|
||||
+73
-11
@@ -4,7 +4,26 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random().toString(16).slice(2)
|
||||
);
|
||||
const pending = new Map();
|
||||
const supportedKinds = new Set(['issue-comment', 'pull-comment', 'update-reply']);
|
||||
const supportedKinds = new Set(['issue-comment', 'pull-comment', 'update-reply', 'pull-review', 'issue-close']);
|
||||
|
||||
function reviewFingerprint(message) {
|
||||
return JSON.stringify({
|
||||
body: String(message.body || ''),
|
||||
decision: String(message.decision || 'comment'),
|
||||
expectedHeadSha: String(message.expectedHeadSha || ''),
|
||||
comments: Array.isArray(message.comments) ? message.comments : [],
|
||||
});
|
||||
}
|
||||
|
||||
function clearConfirmedReviewState(item) {
|
||||
if (item.kind !== 'pull-review') return;
|
||||
try {
|
||||
if (item.draftKey && item.draftFingerprint &&
|
||||
storage?.getItem(item.draftKey) === item.draftFingerprint) storage.removeItem(item.draftKey);
|
||||
if (item.progressKey && item.progressFingerprint &&
|
||||
storage?.getItem(item.progressKey) === item.progressFingerprint) storage.removeItem(item.progressKey);
|
||||
} catch (_error) { /* Delivery is confirmed even when local cleanup is unavailable. */ }
|
||||
}
|
||||
|
||||
function read() {
|
||||
try {
|
||||
@@ -32,6 +51,16 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
const requestedOperationId = String(message.operationId || '').slice(0, 128);
|
||||
const existing = requestedOperationId && items.find(item => item.operationId === requestedOperationId);
|
||||
if (existing) return { ...existing };
|
||||
if (message.kind === 'pull-review') {
|
||||
const queuedReview = items.find(item => item.kind === 'pull-review' &&
|
||||
item.repository === String(message.repository || '') &&
|
||||
item.number === Number(message.number || 0) &&
|
||||
item.expectedHeadSha === String(message.expectedHeadSha || ''));
|
||||
if (queuedReview) {
|
||||
if (reviewFingerprint(queuedReview) === reviewFingerprint(message)) return { ...queuedReview };
|
||||
throw new Error('A review for this saved head is already queued. Open Drafts to inspect or discard it first.');
|
||||
}
|
||||
}
|
||||
if (items.length >= maxItems) throw new Error('Message outbox is full. Send or discard a queued message first.');
|
||||
const id = String(requestedOperationId || makeId()).slice(0, 128);
|
||||
const item = {
|
||||
@@ -45,6 +74,15 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
ownerLogin,
|
||||
status: 'queued',
|
||||
queuedAt: Number(now()),
|
||||
...(message.kind === 'pull-review' ? {
|
||||
decision: String(message.decision || 'comment'),
|
||||
expectedHeadSha: String(message.expectedHeadSha || ''),
|
||||
comments: Array.isArray(message.comments) ? message.comments.map(comment => ({ ...comment })) : [],
|
||||
draftKey: String(message.draftKey || ''),
|
||||
progressKey: String(message.progressKey || ''),
|
||||
draftFingerprint: String(message.draftFingerprint || ''),
|
||||
progressFingerprint: String(message.progressFingerprint || ''),
|
||||
} : {}),
|
||||
};
|
||||
items.push(item);
|
||||
write(items, mirror);
|
||||
@@ -95,6 +133,12 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
return 'api/v1/notifications/' + encodeURIComponent(item.notificationId) + '/reply';
|
||||
}
|
||||
const repository = item.repository.split('/').map(encodeURIComponent).join('/');
|
||||
if (item.kind === 'issue-close') {
|
||||
return 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/close';
|
||||
}
|
||||
if (item.kind === 'pull-review') {
|
||||
return 'api/v1/repos/' + repository + '/pulls/' + encodeURIComponent(item.number) + '/review';
|
||||
}
|
||||
const resource = item.kind === 'pull-comment' ? 'pulls' : 'issues';
|
||||
return 'api/v1/repos/' + repository + '/' + resource + '/' + encodeURIComponent(item.number) + '/comments';
|
||||
}
|
||||
@@ -114,17 +158,32 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
}
|
||||
result = delivery.message;
|
||||
} else {
|
||||
result = await fetchJson(endpoint(item), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': item.operationId,
|
||||
},
|
||||
body: JSON.stringify({ body: item.body }),
|
||||
});
|
||||
if (item.kind === 'issue-close') {
|
||||
result = await fetchJson(endpoint(item), {
|
||||
method: 'PATCH',
|
||||
headers: { Accept: 'application/json', 'Idempotency-Key': item.operationId },
|
||||
});
|
||||
if (result?.state !== 'closed') throw new Error('Issue closure was not confirmed.');
|
||||
} else {
|
||||
const body = item.kind === 'pull-review' ? {
|
||||
body: item.body,
|
||||
decision: item.decision,
|
||||
expected_head_sha: item.expectedHeadSha,
|
||||
comments: item.comments,
|
||||
} : { body: item.body };
|
||||
result = await fetchJson(endpoint(item), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': item.operationId,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!result) return { blocked: true };
|
||||
clearConfirmedReviewState(item);
|
||||
discard(item.id);
|
||||
return { result };
|
||||
} catch (error) {
|
||||
@@ -196,7 +255,10 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
const statuses = new Map((records || []).map(item => [item.id, item]));
|
||||
const items = read().flatMap(item => {
|
||||
const background = statuses.get(item.id);
|
||||
if (background?.status === 'sent') return [];
|
||||
if (background?.status === 'sent') {
|
||||
clearConfirmedReviewState(item);
|
||||
return [];
|
||||
}
|
||||
if (background?.status === 'attention') return [{
|
||||
...item,
|
||||
status: 'attention',
|
||||
|
||||
@@ -205,6 +205,7 @@ function createBackgroundIssueSync({
|
||||
batch = work => work(), requestTimeoutMs = 15000,
|
||||
}) {
|
||||
let purgeRequested = false;
|
||||
let activePurge = null;
|
||||
let activeFlush = null;
|
||||
const activeRequests = new Set();
|
||||
const timeoutMs = Math.max(1, Number(requestTimeoutMs) || 15000);
|
||||
@@ -242,6 +243,18 @@ function createBackgroundIssueSync({
|
||||
return { id: item.id, status, kind: 'message', route: '#/my-work/update/' + encodeURIComponent(item.notificationId) };
|
||||
}
|
||||
const repository = String(item.repository || '').split('/').map(encodeURIComponent).join('/');
|
||||
if (item.kind === 'pull-review') {
|
||||
return {
|
||||
id: item.id, status, kind: 'message',
|
||||
route: '#/my-work/review/' + repository + '/' + encodeURIComponent(item.number),
|
||||
};
|
||||
}
|
||||
if (item.kind === 'issue-close') {
|
||||
return {
|
||||
id: item.id, status, kind: 'message',
|
||||
route: '#/my-work/issue/' + repository + '/' + encodeURIComponent(item.number),
|
||||
};
|
||||
}
|
||||
if (item.kind === 'issue-comment' || item.kind === 'pull-comment') {
|
||||
const resource = item.kind === 'pull-comment' ? 'pull' : 'issue';
|
||||
return { id: item.id, status, kind: 'message', route: '#/my-work/' + resource + '/' + repository + '/' + encodeURIComponent(item.number) };
|
||||
@@ -260,6 +273,34 @@ function createBackgroundIssueSync({
|
||||
return authoredRequest('api/v1/notifications/' + encodeURIComponent(item.notificationId) + '/reply', item);
|
||||
}
|
||||
const repository = String(item.repository || '').split('/').map(encodeURIComponent).join('/');
|
||||
if (item.kind === 'issue-close') {
|
||||
return {
|
||||
url: base + 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/close',
|
||||
options: {
|
||||
method: 'PATCH',
|
||||
headers: { Accept: 'application/json', 'Idempotency-Key': item.operationId },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (item.kind === 'pull-review') {
|
||||
return {
|
||||
url: base + 'api/v1/repos/' + repository + '/pulls/' + encodeURIComponent(item.number) + '/review',
|
||||
options: {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': item.operationId,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
body: item.body,
|
||||
decision: item.decision,
|
||||
expected_head_sha: item.expectedHeadSha,
|
||||
comments: item.comments || [],
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (item.kind === 'issue-comment' || item.kind === 'pull-comment') {
|
||||
const resource = item.kind === 'pull-comment' ? 'pulls' : 'issues';
|
||||
return authoredRequest(
|
||||
@@ -306,6 +347,11 @@ function createBackgroundIssueSync({
|
||||
const request = deliveryRequest(item);
|
||||
try {
|
||||
const delivered = await requestJson(request.url, request.options);
|
||||
if (item.kind === 'issue-close' && delivered?.state !== 'closed') {
|
||||
const error = new Error('Issue closure was not confirmed.');
|
||||
error.status = 422;
|
||||
throw error;
|
||||
}
|
||||
await store.complete(item.id, delivered);
|
||||
const receipt = receiptFor(item, 'confirmed', delivered);
|
||||
return item.kind ? { message: delivered, receipt } : { issue: delivered, receipt };
|
||||
@@ -397,15 +443,26 @@ function createBackgroundIssueSync({
|
||||
return activeFlush;
|
||||
}
|
||||
|
||||
async function purge() {
|
||||
function purge() {
|
||||
if (activePurge) return activePurge;
|
||||
purgeRequested = true;
|
||||
activeRequests.forEach(controller => controller.abort());
|
||||
if (activeFlush) await activeFlush.catch(() => {});
|
||||
await store.close?.();
|
||||
activePurge = (async () => {
|
||||
if (activeFlush) await activeFlush.catch(() => {});
|
||||
await store.close?.();
|
||||
})();
|
||||
return activePurge;
|
||||
}
|
||||
|
||||
async function resume() {
|
||||
const pendingPurge = activePurge;
|
||||
if (pendingPurge) await pendingPurge;
|
||||
if (activePurge === pendingPurge) activePurge = null;
|
||||
purgeRequested = false;
|
||||
}
|
||||
|
||||
return {
|
||||
flush, send, purge,
|
||||
flush, send, purge, resume,
|
||||
reconcile: (items, outboxLane) => store.reconcile(items, outboxLane),
|
||||
snapshot: () => store.snapshot(),
|
||||
setReceiptPreference: (ownerLogin, enabled) => store.setReceiptPreference(ownerLogin, enabled),
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
function createCommentNext({ post, queue, canQueue, accept = () => undefined, complete }) {
|
||||
let inFlight = null;
|
||||
|
||||
function submit(item, body, operationId = '') {
|
||||
if (inFlight) return inFlight;
|
||||
inFlight = (async () => {
|
||||
try {
|
||||
let comment;
|
||||
try {
|
||||
comment = await post(item, body);
|
||||
} catch (error) {
|
||||
if (!canQueue(error)) throw error;
|
||||
const admission = await queue({
|
||||
kind: item.kind === 'pull' ? 'pull-comment' : 'issue-comment',
|
||||
repository: item.repository,
|
||||
number: item.number,
|
||||
body,
|
||||
operationId: typeof operationId === 'function' ? operationId() : operationId,
|
||||
});
|
||||
if (!admission || (!admission.item && admission.durable !== true)) {
|
||||
throw new Error('Comment was not saved for delivery.');
|
||||
}
|
||||
accept(item, { delivery: admission.background ? 'queued' : 'saved' });
|
||||
return {
|
||||
accepted: true,
|
||||
delivery: admission.background ? 'queued' : 'saved',
|
||||
background: Boolean(admission.background),
|
||||
completed: Boolean(complete(item)),
|
||||
};
|
||||
}
|
||||
accept(item, { delivery: 'posted', comment });
|
||||
return {
|
||||
accepted: true,
|
||||
delivery: 'posted',
|
||||
comment,
|
||||
completed: Boolean(complete(item)),
|
||||
};
|
||||
} finally {
|
||||
inFlight = null;
|
||||
}
|
||||
})();
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
return { submit, busy: () => Boolean(inFlight) };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createCommentNext;
|
||||
+16
-1
@@ -100,6 +100,14 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.plan-preview-actions button { min-height:44px; }
|
||||
.plan-today-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; margin:16px -6px -6px; padding:12px 6px; padding-bottom:calc(12px + env(safe-area-inset-bottom)); background:rgba(11,21,38,.98); border-top:1px solid #2a496e; }
|
||||
.plan-today-actions button { min-height:44px; width:100%; }
|
||||
.today-readiness-sheet { position:fixed; inset:0; z-index:90; display:flex; align-items:flex-end; justify-content:center; background:rgba(5,12,21,.82); backdrop-filter:blur(4px); }
|
||||
.today-readiness-sheet[hidden] { display:none; }
|
||||
.today-readiness-panel { box-sizing:border-box; width:min(620px,100%); max-height:100%; overflow:auto; overflow-x:hidden; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); border:1px solid #b45309; border-radius:18px 18px 0 0; background:#0b1526; }
|
||||
.today-readiness-header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
|
||||
.today-readiness-header h2 { margin:.2rem 0; }
|
||||
.today-readiness-header button, .today-readiness-actions button { min-height:44px; }
|
||||
.today-readiness-item { min-width:0; overflow-wrap:anywhere; margin:12px 0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
|
||||
.today-readiness-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; margin:16px -6px -6px; padding:12px 6px; padding-bottom:calc(12px + env(safe-area-inset-bottom)); background:rgba(11,21,38,.98); border-top:1px solid #2a496e; }
|
||||
.my-work-header { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; }
|
||||
.work-settings { width:100%; }
|
||||
.work-settings > summary { display:none; }
|
||||
@@ -213,6 +221,11 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.issue-sheet-header { display:flex; align-items:center; justify-content:space-between; gap:10px; }
|
||||
.issue-sheet-header button { min-height:44px; }
|
||||
.issue-sheet-content { overflow-wrap:anywhere; white-space:pre-wrap; }
|
||||
.issue-blockers { max-width:100%; overflow-x:hidden; margin:16px 0; padding:12px; border:1px solid #b45309; border-radius:12px; background:#291b0c; }
|
||||
.issue-blockers h2 { margin-top:0; }
|
||||
.issue-blocker-list { display:grid; gap:8px; }
|
||||
.issue-blocker { min-width:0; overflow-wrap:anywhere; display:grid; gap:4px; padding:10px; border:1px solid #92400e; border-radius:10px; color:#fef3c7; text-decoration:none; }
|
||||
.issue-blocker:hover, .issue-blocker:focus-visible { border-color:#f59e0b; }
|
||||
.issue-planning { max-width:100%; margin-top:16px; border:1px solid #2a496e; border-radius:12px; padding:0 12px 12px; overflow-x:hidden; }
|
||||
.issue-planning > summary { min-height:44px; display:flex; align-items:center; cursor:pointer; font-weight:700; }
|
||||
.issue-planning-retry { min-height:44px; width:100%; }
|
||||
@@ -226,6 +239,8 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.issue-comment { padding:10px 0; border-bottom:1px solid #1b2d45; }
|
||||
.issue-comment-composer { display:grid; gap:8px; margin-top:16px; }
|
||||
.issue-comment-composer button { min-height:44px; width:100%; }
|
||||
.comment-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
|
||||
.comment-actions button { min-height:44px; width:100%; }
|
||||
.issue-label-editor { max-width:100%; margin:14px 0; padding:12px; border:1px solid #2a496e; border-radius:12px; }
|
||||
.issue-label-list { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(180px,100%),1fr)); gap:8px; max-width:100%; }
|
||||
.issue-label-option { min-height:44px; max-width:100%; display:flex; align-items:center; gap:10px; padding:8px; border:1px solid #2a496e; border-radius:10px; overflow-wrap:anywhere; }
|
||||
@@ -251,7 +266,7 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.my-work-actions { display:flex; flex-wrap:wrap; gap:8px; }
|
||||
.start-work-session { min-height:44px; }
|
||||
.resume-today-session, .end-today-session { min-height:44px; }
|
||||
.work-session-nav { position:sticky; bottom:0; z-index:5; display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:12px; padding:10px 4px; padding-bottom:calc(10px + env(safe-area-inset-bottom)); background:rgba(11,21,38,.98); border-top:1px solid #2a496e; }
|
||||
.work-session-nav { position:sticky; bottom:0; z-index:5; display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; margin-top:12px; padding:10px 4px; padding-bottom:calc(10px + env(safe-area-inset-bottom)); background:rgba(11,21,38,.98); border-top:1px solid #2a496e; }
|
||||
.work-session-nav[hidden] { display:none; }
|
||||
.work-session-nav [data-work-session-progress] { grid-column:1 / -1; text-align:center; }
|
||||
.work-session-nav button { min-height:44px; width:100%; }
|
||||
|
||||
+361
-34
@@ -120,6 +120,7 @@
|
||||
let selectedUpdate = null;
|
||||
let updateTrigger = null;
|
||||
let selectedIssue = null;
|
||||
let selectedIssueOffline = false;
|
||||
let selectedIssueDetail = null;
|
||||
let issueConversation = null;
|
||||
let issueTrigger = null;
|
||||
@@ -710,6 +711,9 @@
|
||||
document.querySelectorAll('[data-work-session-next]').forEach(button => {
|
||||
button.textContent = state.can_next ? 'Next work item' : 'Finish session';
|
||||
});
|
||||
document.querySelectorAll('[data-work-session-complete]').forEach(button => {
|
||||
button.hidden = !workSession.checkpointed();
|
||||
});
|
||||
},
|
||||
onFinish: () => {
|
||||
closeOpenWorkSheets();
|
||||
@@ -724,25 +728,105 @@
|
||||
qs('[data-work-filter="today"]').click();
|
||||
}
|
||||
|
||||
function continueTodaySession() {
|
||||
selectTodayWork();
|
||||
if (!workSession.reopen() && !workSession.reconcile()) {
|
||||
qs('#my-work-action-status').textContent = 'Current Today item is no longer available.';
|
||||
let todayReadinessTrigger = null;
|
||||
function inspectTodayDependencies(item) {
|
||||
if (offlineWorkMode) {
|
||||
const login = confirmedOwnerLogin || String(offlineWorkStore.load()?.user?.login || '').trim();
|
||||
const detail = offlineWorkStore.loadDetail(login, item);
|
||||
return Promise.resolve({
|
||||
available:detail?.dependencies_available === true,
|
||||
dependencies:Array.isArray(detail?.dependencies) ? detail.dependencies : [],
|
||||
});
|
||||
}
|
||||
const [owner, repo] = String(item.repository || '').split('/');
|
||||
return api('api/v1/repos/' + encodeURIComponent(owner) + '/' + encodeURIComponent(repo) +
|
||||
'/issues/' + encodeURIComponent(item.number) + '/detail').then(detail => ({
|
||||
available:detail?.dependencies_available === true,
|
||||
dependencies:Array.isArray(detail?.dependencies) ? detail.dependencies : [],
|
||||
}));
|
||||
}
|
||||
|
||||
function closeTodayReadiness(navigate = true) {
|
||||
qs('#today-readiness-sheet').hidden = true;
|
||||
document.body.classList.remove('task-overlay-open');
|
||||
if (navigate) taskOverlayHistory.close();
|
||||
else {
|
||||
todayReadiness.cancel();
|
||||
requestAnimationFrame(() => todayReadinessTrigger?.focus());
|
||||
}
|
||||
}
|
||||
|
||||
function renderTodayReadiness(state) {
|
||||
if (!state?.target) return;
|
||||
const unknown = state.status === 'unknown';
|
||||
qs('#today-readiness-title').textContent = unknown ? 'Blocker status unavailable' : 'This item is blocked';
|
||||
qs('#today-readiness-summary').textContent = unknown
|
||||
? 'Stackchain could not confirm whether this issue is ready. Retry or choose an explicit override.'
|
||||
: state.dependencies.length + (state.dependencies.length === 1 ? ' open dependency must finish first.' : ' open dependencies must finish first.');
|
||||
qs('#today-readiness-item').innerHTML = '<strong>' + escapeHtml(state.target.title || 'Untitled issue') +
|
||||
'</strong><div class="small">' + escapeHtml(state.target.repository + '#' + state.target.number) + '</div>';
|
||||
qs('#today-readiness-blockers').innerHTML = state.dependencies.map(blocker =>
|
||||
'<a class="issue-blocker" href="' + escAttr(blocker.url || '#') + '" target="_blank" rel="noopener noreferrer"><strong>' +
|
||||
escapeHtml(blocker.repository + '#' + blocker.number) + ' · ' + escapeHtml(blocker.title || 'Untitled blocker') +
|
||||
'</strong><span class="small">State: ' + escapeHtml(blocker.state || 'open') + '</span></a>'
|
||||
).join('');
|
||||
qs('#today-readiness-next').hidden = !state.nextReady;
|
||||
if (state.nextReady) qs('#today-readiness-next').textContent = 'Start next ready · ' +
|
||||
(state.nextReady.title || state.nextReady.key || 'work item');
|
||||
qs('#today-readiness-retry').hidden = !unknown;
|
||||
qs('#today-readiness-sheet').hidden = false;
|
||||
document.body.classList.add('task-overlay-open');
|
||||
requestAnimationFrame(() => (state.nextReady ? qs('#today-readiness-next') : qs('#today-readiness-anyway')).focus());
|
||||
}
|
||||
|
||||
function performTodayTransition(action, item = null) {
|
||||
qs('#today-readiness-sheet').hidden = true;
|
||||
document.body.classList.remove('task-overlay-open');
|
||||
if (taskOverlayHistory.current?.() === 'today-readiness') taskOverlayHistory.close();
|
||||
const transitioned = ({
|
||||
start: () => workSession.start(item),
|
||||
resume: () => workSession.resume(item),
|
||||
continue: () => workSession.reopen(item),
|
||||
next: () => workSession.next(item),
|
||||
complete: () => workSession.complete(item),
|
||||
})[action]?.();
|
||||
if (!transitioned && action !== 'next' && action !== 'complete') {
|
||||
qs('#my-work-action-status').textContent = 'Saved Today item is no longer available.';
|
||||
updateWorkSessionActions();
|
||||
}
|
||||
}
|
||||
|
||||
const todayReadiness = createTodayReadiness({
|
||||
inspect:inspectTodayDependencies,
|
||||
onOpen:performTodayTransition,
|
||||
onGate:state => {
|
||||
todayReadinessTrigger = document.activeElement;
|
||||
renderTodayReadiness(state);
|
||||
taskOverlayHistory.open('today-readiness');
|
||||
},
|
||||
});
|
||||
|
||||
function runTodayTransition(action) {
|
||||
selectTodayWork();
|
||||
const target = workSession.target(action);
|
||||
if (!target) {
|
||||
performTodayTransition(action);
|
||||
return Promise.resolve('empty');
|
||||
}
|
||||
qs('#my-work-action-status').textContent = 'Checking Today readiness…';
|
||||
return todayReadiness.run(action, workSession.items(), target);
|
||||
}
|
||||
|
||||
function continueTodaySession() {
|
||||
return runTodayTransition('continue');
|
||||
}
|
||||
|
||||
function resumeTodaySession() {
|
||||
selectTodayWork();
|
||||
if (!workSession.resume()) {
|
||||
qs('#my-work-action-status').textContent = 'Saved Today session is no longer available.';
|
||||
updateWorkSessionActions();
|
||||
}
|
||||
return runTodayTransition('resume');
|
||||
}
|
||||
|
||||
function startTodaySession() {
|
||||
selectTodayWork();
|
||||
workSession.start();
|
||||
return runTodayTransition('start');
|
||||
}
|
||||
|
||||
const createAndStart = createCreateAndStart({
|
||||
@@ -764,6 +848,68 @@
|
||||
warm: warmTodayOffline,
|
||||
});
|
||||
|
||||
const selectedSessionItem = kind => ({
|
||||
issue: selectedIssue,
|
||||
pull: selectedPull,
|
||||
review: selectedReview,
|
||||
update: selectedUpdate,
|
||||
})[kind] || null;
|
||||
const completeTodayItem = createTodayCompletion({
|
||||
todayWork,
|
||||
todaySync,
|
||||
workSession,
|
||||
refresh: () => refreshMyWorkView({ reconcileSession:false }),
|
||||
warm: warmTodayOffline,
|
||||
announce: message => { qs('#my-work-action-status').textContent = message; },
|
||||
advance: () => runTodayTransition('complete'),
|
||||
});
|
||||
function setCommentNextVisibility(kind) {
|
||||
const item = kind === 'issue' ? selectedIssue : selectedPull;
|
||||
qs('#send-' + kind + '-comment-next').hidden = !item || !workSession.checkpointed(item);
|
||||
}
|
||||
const issueCommentNext = createCommentNext({
|
||||
post: async (item, body) => {
|
||||
const comment = await issueController.comment(item, body);
|
||||
if (selectedIssue === item && issueConversation) renderIssueConversation(issueConversation.append(comment));
|
||||
return comment;
|
||||
},
|
||||
queue: message => authoredOutbox.enqueueDurably(message),
|
||||
canQueue: canQueueMessage,
|
||||
accept: item => {
|
||||
issueController.saveDraft(item, '');
|
||||
if (selectedIssue === item) qs('#issue-comment').value = '';
|
||||
},
|
||||
complete: item => completeTodayItem(item, {
|
||||
successMessage: 'Comment saved. Next Today item opened.',
|
||||
failureMessage: 'Comment saved, but Today still needs completion.',
|
||||
}),
|
||||
});
|
||||
const pullCommentNext = createCommentNext({
|
||||
post: async (item, body) => {
|
||||
const comment = await pullController.comment(item, body);
|
||||
if (selectedPull === item && pullConversation) renderPullConversation(pullConversation.append(comment));
|
||||
return comment;
|
||||
},
|
||||
queue: message => authoredOutbox.enqueueDurably(message),
|
||||
canQueue: canQueueMessage,
|
||||
accept: item => {
|
||||
pullController.saveDraft(item, '');
|
||||
if (selectedPull === item) qs('#pull-comment').value = '';
|
||||
},
|
||||
complete: item => completeTodayItem(item, {
|
||||
successMessage: 'Comment saved. Next Today item opened.',
|
||||
failureMessage: 'Comment saved, but Today still needs completion.',
|
||||
}),
|
||||
});
|
||||
const closeOfflineIssue = createOfflineIssueClose({
|
||||
enqueueDurably: message => authoredOutbox.enqueueDurably(message),
|
||||
completeToday: (item, options) => completeTodayItem(item, options),
|
||||
});
|
||||
|
||||
function reviewingActiveTodayItem() {
|
||||
return workSession.checkpointed();
|
||||
}
|
||||
|
||||
function acceptClaimedIssue(confirmed) {
|
||||
lastContextSnapshot = lastContextSnapshot || { user: {}, repos: [], issues: [], pull_requests: [] };
|
||||
lastContextSnapshot.issues = [confirmed].concat((lastContextSnapshot.issues || []).filter(candidate =>
|
||||
@@ -807,7 +953,9 @@
|
||||
const title = escapeHtml(item.title || 'Untitled work');
|
||||
const controls = selected ?
|
||||
'<div class="plan-today-item-actions"><button type="button" data-plan-move="up" data-plan-id="' + escAttr(id) + '"' + (index === 0 ? ' disabled' : '') + '>Up</button><button type="button" data-plan-move="down" data-plan-id="' + escAttr(id) + '"' + (index === planToday.snapshot().count - 1 ? ' disabled' : '') + '>Down</button><button type="button" data-plan-remove="' + escAttr(id) + '">Remove</button></div>' :
|
||||
'<div class="plan-today-candidate-actions"><button type="button" data-plan-preview="' + escAttr(id) + '">Preview</button><button type="button" data-plan-add="' + escAttr(id) + '">Add</button></div>';
|
||||
(item.kind === 'issue' ?
|
||||
'<div class="plan-today-candidate-actions"><button type="button" data-plan-preview="' + escAttr(id) + '">Preview to add</button></div>' :
|
||||
'<div class="plan-today-candidate-actions"><button type="button" data-plan-preview="' + escAttr(id) + '">Preview</button><button type="button" data-plan-add="' + escAttr(id) + '">Add</button></div>');
|
||||
return '<article class="plan-today-item"><div class="plan-today-item-copy"><span class="small">' + key + '</span><strong class="my-work-card-title">' + title + '</strong></div>' + controls + '</article>';
|
||||
}
|
||||
|
||||
@@ -876,7 +1024,7 @@
|
||||
save: saveTodayPlan,
|
||||
start: () => {
|
||||
qs('[data-work-filter="today"]').click();
|
||||
workSession.start();
|
||||
startTodaySession();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -890,6 +1038,7 @@
|
||||
function openPlanPreviewDetail(item, trigger) {
|
||||
qs('#plan-today-sheet').hidden = true;
|
||||
qs('#plan-preview-actions').hidden = false;
|
||||
if (item.kind === 'issue') renderPlanIssueDependencies(null, true);
|
||||
if (offlineWorkMode) {
|
||||
openRoutedWork(item, trigger);
|
||||
} else if (item.kind === 'update' && item.has_update) {
|
||||
@@ -916,19 +1065,68 @@
|
||||
onClose: (_item, trigger) => {
|
||||
closeOpenWorkSheets();
|
||||
qs('#plan-preview-actions').hidden = true;
|
||||
qs('#issue-blockers').hidden = true;
|
||||
qs('#issue-blocker-list').textContent = '';
|
||||
qs('#add-plan-preview').disabled = false;
|
||||
qs('#add-plan-preview').textContent = 'Add to Today & back';
|
||||
qs('#plan-today-sheet').hidden = false;
|
||||
renderPlanToday();
|
||||
requestAnimationFrame(() => trigger?.focus());
|
||||
},
|
||||
});
|
||||
|
||||
function renderPlanIssueDependencies(detail, loading = false) {
|
||||
const preview = planTodayPreview.snapshot();
|
||||
if (!preview.open || preview.item?.kind !== 'issue') return;
|
||||
const panel = qs('#issue-blockers');
|
||||
const list = qs('#issue-blocker-list');
|
||||
const status = qs('#issue-blocker-status');
|
||||
const addButton = qs('#add-plan-preview');
|
||||
panel.hidden = false;
|
||||
list.innerHTML = '';
|
||||
addButton.disabled = loading;
|
||||
addButton.dataset.planOverride = '';
|
||||
if (loading) {
|
||||
status.textContent = 'Checking unresolved blockers…';
|
||||
addButton.textContent = 'Checking blockers…';
|
||||
return;
|
||||
}
|
||||
const available = detail?.dependencies_available === true;
|
||||
const dependencies = Array.isArray(detail?.dependencies) ? detail.dependencies : [];
|
||||
planTodayPreview.setDependencies({ available, dependencies });
|
||||
if (!available) {
|
||||
status.textContent = 'Blocker status unavailable. Adding requires an explicit override.';
|
||||
addButton.textContent = 'Add without blocker status anyway & back';
|
||||
addButton.dataset.planOverride = 'true';
|
||||
return;
|
||||
}
|
||||
if (dependencies.length) {
|
||||
list.innerHTML = dependencies.map(blocker =>
|
||||
'<a class="issue-blocker" href="' + escAttr(blocker.url || '#') + '" target="_blank" rel="noopener noreferrer"><strong>' +
|
||||
escapeHtml(blocker.repository + '#' + blocker.number) + ' · ' + escapeHtml(blocker.title || 'Untitled blocker') +
|
||||
'</strong><span class="small">State: ' + escapeHtml(blocker.state || 'open') + '</span></a>'
|
||||
).join('');
|
||||
status.textContent = dependencies.length + (dependencies.length === 1 ? ' unresolved blocker.' : ' unresolved blockers.');
|
||||
addButton.textContent = 'Add blocked item anyway & back';
|
||||
addButton.dataset.planOverride = 'true';
|
||||
return;
|
||||
}
|
||||
panel.hidden = true;
|
||||
status.textContent = '';
|
||||
addButton.textContent = 'Add to Today & back';
|
||||
}
|
||||
|
||||
let addPlanPreviewOnReturn = false;
|
||||
let addPlanPreviewOverride = false;
|
||||
|
||||
qs('#back-to-plan').addEventListener('click', () => {
|
||||
addPlanPreviewOnReturn = false;
|
||||
addPlanPreviewOverride = false;
|
||||
taskOverlayHistory.close();
|
||||
});
|
||||
qs('#add-plan-preview').addEventListener('click', () => {
|
||||
addPlanPreviewOnReturn = true;
|
||||
addPlanPreviewOverride = qs('#add-plan-preview').dataset.planOverride === 'true';
|
||||
taskOverlayHistory.close();
|
||||
});
|
||||
|
||||
@@ -1038,7 +1236,7 @@
|
||||
|
||||
function setOfflineDetailControls(kind) {
|
||||
const selectors = kind === 'issue' ? [
|
||||
'#edit-issue-content', '#close-issue', '#release-issue', '#load-issue-handoff',
|
||||
'#edit-issue-content', '#release-issue', '#load-issue-handoff',
|
||||
'#issue-handoff-recipient', '#confirm-issue-handoff', '#issue-due-date',
|
||||
'#save-issue-labels', '#save-issue-due-date', '#clear-issue-due-date',
|
||||
'#issue-milestone', '#save-issue-milestone', '#load-older-issue-comments',
|
||||
@@ -1227,6 +1425,8 @@
|
||||
list.innerHTML = lastDrafts.length ? lastDrafts.map((item, index) => {
|
||||
const isOutbox = item.kind === 'issue-outbox' || item.kind === 'authored-outbox';
|
||||
const isUnfiled = item.kind === 'unfiled-issue';
|
||||
const reviewOutbox = item.outbox_kind === 'pull-review';
|
||||
const closureOutbox = item.outbox_kind === 'issue-close';
|
||||
const sendLabel = item.delivery_state === 'uncertain' ? 'Verified not posted — retry' : 'Send now';
|
||||
const outboxActions = item.quarantined ?
|
||||
'<button class="draft-copy" data-draft-index="' + index + '" type="button">Copy content</button>' +
|
||||
@@ -1238,10 +1438,18 @@
|
||||
'<button class="draft-edit" data-draft-index="' + index + '" type="button">Edit</button>' +
|
||||
'<button class="draft-send" data-draft-index="' + index + '" type="button">' + sendLabel + '</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard</button>' :
|
||||
item.kind === 'authored-outbox' ?
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">Open message</button>' +
|
||||
reviewOutbox && item.status === 'attention' ?
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">Open current review</button>' +
|
||||
'<button class="draft-copy" data-draft-index="' + index + '" type="button">Copy feedback</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard queued review</button>' :
|
||||
item.kind === 'authored-outbox' && !reviewOutbox ?
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">' +
|
||||
(closureOutbox ? 'Open issue' : 'Open message') + '</button>' +
|
||||
'<button class="draft-send" data-draft-index="' + index + '" type="button">' + sendLabel + '</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard</button>' :
|
||||
reviewOutbox ?
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">Open review</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard queued review</button>' :
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">' +
|
||||
(isUnfiled ? 'Choose repository' : 'Resume draft') + '</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard draft</button>';
|
||||
@@ -1656,6 +1864,7 @@
|
||||
qs('#issue-planning').inert = false;
|
||||
qs('#issue-handoff').inert = false;
|
||||
selectedIssue = item;
|
||||
selectedIssueOffline = Boolean(offlineDetail);
|
||||
selectedIssueDetail = null;
|
||||
issueConversation = null;
|
||||
issueTrigger = trigger;
|
||||
@@ -1694,16 +1903,20 @@
|
||||
qs('#retry-issue-load').hidden = true;
|
||||
qs('#open-issue-gitea').href = item.url || '#';
|
||||
qs('#send-issue-comment').disabled = false;
|
||||
setCommentNextVisibility('issue');
|
||||
qs('#edit-issue-content').disabled = true;
|
||||
qs('#issue-edit-form').hidden = true;
|
||||
qs('#issue-edit-status').textContent = '';
|
||||
qs('#close-issue').disabled = false;
|
||||
qs('#close-issue').textContent = workSession.active() ? 'Close & next' : 'Close issue';
|
||||
qs('#close-issue').textContent = offlineDetail ?
|
||||
(workSession.active() ? 'Queue close & next' : 'Queue issue closure') :
|
||||
(workSession.active() ? 'Close & next' : 'Close issue');
|
||||
qs('#close-issue-sheet').focus();
|
||||
try {
|
||||
const detail = offlineDetail || await issueController.load(item);
|
||||
if (selectedIssue !== item) return;
|
||||
selectedIssueDetail = detail;
|
||||
renderPlanIssueDependencies(detail);
|
||||
issueConversation = issueController.conversation(item, detail.conversation);
|
||||
qs('#issue-sheet-title').textContent = detail.title || 'Assigned issue';
|
||||
qs('#issue-sheet-body').innerHTML = renderMarkdown(detail.body || 'No description provided.');
|
||||
@@ -1747,6 +1960,7 @@
|
||||
mobileComposerViewport.close(qs('#issue-sheet .issue-sheet-panel'));
|
||||
qs('#issue-sheet').classList.remove('open');
|
||||
selectedIssue = null;
|
||||
selectedIssueOffline = false;
|
||||
selectedIssueDetail = null;
|
||||
issueConversation = null;
|
||||
if (issueTrigger?.isConnected) issueTrigger.focus();
|
||||
@@ -1853,6 +2067,7 @@
|
||||
qs('#merge-pull').textContent = workSession.active() ? 'Merge & next' : 'Merge';
|
||||
qs('#retry-pull-load').hidden = true;
|
||||
qs('#open-pull-gitea').href = item.url || '#';
|
||||
setCommentNextVisibility('pull');
|
||||
qs('#close-pull-sheet').focus();
|
||||
try {
|
||||
const detail = offlineDetail || await pullController.load(item);
|
||||
@@ -2355,7 +2570,8 @@
|
||||
qs('#review-submit-status').textContent = '';
|
||||
qs('#continue-review-to-merge').hidden = true;
|
||||
qs('#submit-review').disabled = true;
|
||||
qs('#submit-review').textContent = offlineReview ? 'Reconnect to validate & submit' : 'Submit review';
|
||||
qs('#submit-review').textContent = offlineReview && reviewingActiveTodayItem() ? 'Queue review & next' :
|
||||
(offlineReview ? 'Queue review for reconnect' : 'Submit review');
|
||||
closeInlineComposer();
|
||||
draft = null;
|
||||
reviewFiles = [];
|
||||
@@ -2422,7 +2638,7 @@
|
||||
qs('#review-sheet-status').textContent = offlineReview ?
|
||||
'Offline review · saved ' + fmt(detail.saved_at) + ' · draft feedback stays on this device.' :
|
||||
'Ready to review · by ' + (detail.author || 'unknown author');
|
||||
qs('#submit-review').disabled = offlineReview;
|
||||
qs('#submit-review').disabled = false;
|
||||
} catch (error) {
|
||||
if (selectedReview !== item) return;
|
||||
qs('#review-sheet-status').textContent = error.message + ' Retry here or use Open in Gitea.';
|
||||
@@ -2854,15 +3070,19 @@
|
||||
qs('#open-palette').focus();
|
||||
}
|
||||
if (previous === 'plan-today-preview' && kind !== 'plan-today-preview') {
|
||||
if (addPlanPreviewOnReturn) planTodayPreview.close({ add:true });
|
||||
if (addPlanPreviewOnReturn && addPlanPreviewOverride) planTodayPreview.close({ add:true, override:true });
|
||||
else if (addPlanPreviewOnReturn) planTodayPreview.close({ add:true });
|
||||
else planTodayPreview.close();
|
||||
addPlanPreviewOnReturn = false;
|
||||
addPlanPreviewOverride = false;
|
||||
}
|
||||
if (previous === 'plan-today' && kind !== 'plan-today' && kind !== 'plan-today-preview') closePlanToday(false);
|
||||
if (previous === 'today-readiness' && kind !== 'today-readiness') closeTodayReadiness(false);
|
||||
if (kind === 'new' && previous !== 'new') openCreateIssueSheet(false);
|
||||
if (kind === 'find' && previous !== 'find') openFindWorkSheet(false);
|
||||
if (kind === 'search' && previous !== 'search-preview') openCommandPalette(false);
|
||||
if (kind === 'plan-today' && previous !== 'plan-today' && previous !== 'plan-today-preview') openPlanToday(planTodayTrigger, false);
|
||||
if (kind === 'today-readiness' && previous !== 'today-readiness') renderTodayReadiness(todayReadiness.snapshot());
|
||||
},
|
||||
});
|
||||
taskOverlayHistory.start();
|
||||
@@ -3309,6 +3529,43 @@
|
||||
qs('#issue-milestone').disabled = false;
|
||||
}
|
||||
});
|
||||
async function submitCommentAndNext(kind) {
|
||||
const item = kind === 'issue' ? selectedIssue : selectedPull;
|
||||
if (!item || !workSession.checkpointed(item)) return;
|
||||
const textarea = qs('#' + kind + '-comment');
|
||||
const status = qs('#' + kind + '-comment-status');
|
||||
const body = textarea.value.trim();
|
||||
if (!body) {
|
||||
status.textContent = 'Write a comment before posting.';
|
||||
textarea.focus();
|
||||
return;
|
||||
}
|
||||
const postButton = qs('#send-' + kind + '-comment');
|
||||
const nextButton = qs('#send-' + kind + '-comment-next');
|
||||
const controller = kind === 'issue' ? issueCommentNext : pullCommentNext;
|
||||
const operationId = () => localStorage.getItem('stackchain.' + kind + '-comment.v1:' +
|
||||
item.repository + '#' + item.number + ':operation');
|
||||
postButton.disabled = true;
|
||||
nextButton.disabled = true;
|
||||
status.textContent = 'Posting comment and opening next…';
|
||||
try {
|
||||
const result = await controller.submit(item, body, operationId);
|
||||
const stillOpen = kind === 'issue' ? selectedIssue === item : selectedPull === item;
|
||||
if (!stillOpen) return;
|
||||
if (!result.completed) status.textContent = 'Comment saved, but Today still needs completion.';
|
||||
else if (result.delivery === 'posted') status.textContent = 'Comment posted.';
|
||||
else if (result.background) status.textContent = 'Queued for sync when the connection returns.';
|
||||
else status.textContent = 'Saved for next launch; background delivery unavailable.';
|
||||
} catch (error) {
|
||||
status.textContent = error.message + ' Your draft and Today position are safe; retry.';
|
||||
textarea.focus();
|
||||
} finally {
|
||||
postButton.disabled = false;
|
||||
nextButton.disabled = false;
|
||||
}
|
||||
}
|
||||
qs('#send-issue-comment-next').addEventListener('click', () => submitCommentAndNext('issue'));
|
||||
qs('#send-pull-comment-next').addEventListener('click', () => submitCommentAndNext('pull'));
|
||||
qs('#send-issue-comment').addEventListener('click', async () => {
|
||||
if (!selectedIssue) return;
|
||||
const body = qs('#issue-comment').value.trim();
|
||||
@@ -3427,6 +3684,26 @@
|
||||
const closing = selectedIssue;
|
||||
const button = qs('#close-issue');
|
||||
button.disabled = true;
|
||||
if (selectedIssueOffline) {
|
||||
qs('#issue-sheet-status').textContent = 'Saving issue closure for background delivery…';
|
||||
try {
|
||||
const outcome = await closeOfflineIssue(closing);
|
||||
closeIssueSheet();
|
||||
refreshMyWorkView({ reconcileSession:false });
|
||||
if (!outcome.advanced) {
|
||||
qs('#my-work-action-status').textContent = 'Issue closure queued, but Today still needs completion.';
|
||||
} else if (outcome.admission.background) {
|
||||
qs('#my-work-action-status').textContent = 'Issue closure queued for reconnect. Next Today item opened.';
|
||||
} else {
|
||||
qs('#my-work-action-status').textContent = 'Issue closure saved for next launch. Next Today item opened.';
|
||||
}
|
||||
} catch (error) {
|
||||
qs('#issue-sheet-status').textContent = error.message + ' The issue remains in Today; retry.';
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
qs('#issue-sheet-status').textContent = 'Closing issue…';
|
||||
try {
|
||||
await issueController.close(selectedIssue);
|
||||
@@ -3436,9 +3713,11 @@
|
||||
);
|
||||
refreshMyWorkView({ reconcileSession:false });
|
||||
const continuingSession = workSession.active();
|
||||
if (workSession.active()) workSession.complete();
|
||||
if (continuingSession && workSession.active()) {
|
||||
const transitionResult = workSession.active() ? await runTodayTransition('complete') : null;
|
||||
if (transitionResult === 'opened') {
|
||||
qs('#my-work-action-status').textContent = closing.key + ' closed. Next work item opened.';
|
||||
} else if (transitionResult === 'gated') {
|
||||
qs('#my-work-action-status').textContent = closing.key + ' closed. Choose the next ready Today item.';
|
||||
} else if (!continuingSession) {
|
||||
qs('#my-work-action-status').textContent = closing.key + ' closed.';
|
||||
}
|
||||
@@ -3528,9 +3807,11 @@
|
||||
);
|
||||
refreshMyWorkView({ reconcileSession:false });
|
||||
const continuingSession = workSession.active();
|
||||
if (workSession.active()) workSession.complete();
|
||||
if (continuingSession && workSession.active()) {
|
||||
const transitionResult = workSession.active() ? await runTodayTransition('complete') : null;
|
||||
if (transitionResult === 'opened') {
|
||||
qs('#my-work-action-status').textContent = merging.key + ' merged. Next work item opened.';
|
||||
} else if (transitionResult === 'gated') {
|
||||
qs('#my-work-action-status').textContent = merging.key + ' merged. Choose the next ready Today item.';
|
||||
} else if (!continuingSession) {
|
||||
qs('#my-work-action-status').textContent = merging.key + ' merged.';
|
||||
}
|
||||
@@ -3633,6 +3914,41 @@
|
||||
)) return;
|
||||
const button = qs('#submit-review');
|
||||
button.disabled = true;
|
||||
if (offlineReview) {
|
||||
const queuedTodayReview = reviewingActiveTodayItem();
|
||||
qs('#review-submit-status').textContent = 'Queueing review safely…';
|
||||
try {
|
||||
await authoredOutbox.enqueueDurably({
|
||||
kind: 'pull-review',
|
||||
repository: selectedReview.repository,
|
||||
number: selectedReview.number,
|
||||
body: createReviewController.formatFeedback(snapshot, reviewFiles),
|
||||
decision: snapshot.decision,
|
||||
expectedHeadSha: selectedReviewHead,
|
||||
comments: snapshot.comments,
|
||||
draftKey: draft.storageKey,
|
||||
progressKey: progress?.storageKey || '',
|
||||
draftFingerprint: localStorage.getItem(draft.storageKey) || '',
|
||||
progressFingerprint: localStorage.getItem(progress?.storageKey) || '',
|
||||
});
|
||||
if (queuedTodayReview) {
|
||||
const advanced = completeTodayItem(selectedReview, {
|
||||
successMessage: 'Review queued. Next Today item opened.',
|
||||
failureMessage: 'Review queued, but Today still needs completion.',
|
||||
});
|
||||
if (!advanced) {
|
||||
qs('#review-submit-status').textContent = 'Review queued, but Today still needs completion.';
|
||||
}
|
||||
} else {
|
||||
qs('#review-submit-status').textContent = 'Review queued · it will submit after reconnect.';
|
||||
}
|
||||
} catch (error) {
|
||||
qs('#review-submit-status').textContent = error.message + ' Your draft is safe; retry when ready.';
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
qs('#review-submit-status').textContent = 'Submitting review…';
|
||||
try {
|
||||
const item = selectedReview;
|
||||
@@ -3662,7 +3978,7 @@
|
||||
qs('#continue-review-to-merge').focus();
|
||||
} else {
|
||||
await load();
|
||||
if (workSession.active()) workSession.complete();
|
||||
if (workSession.active()) await runTodayTransition('complete');
|
||||
else button.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -3854,6 +4170,17 @@
|
||||
qs('#plan-today-sheet').addEventListener('click', event => {
|
||||
if (event.target === qs('#plan-today-sheet')) closePlanToday();
|
||||
});
|
||||
qs('#today-readiness-close').addEventListener('click', () => closeTodayReadiness());
|
||||
qs('#today-readiness-sheet').addEventListener('click', event => {
|
||||
if (event.target === qs('#today-readiness-sheet')) closeTodayReadiness();
|
||||
});
|
||||
qs('#today-readiness-next').addEventListener('click', () => todayReadiness.startNextReady());
|
||||
qs('#today-readiness-anyway').addEventListener('click', () => todayReadiness.workAnyway());
|
||||
qs('#today-readiness-retry').addEventListener('click', () => todayReadiness.retry());
|
||||
qs('#today-readiness-plan').addEventListener('click', () => {
|
||||
closeTodayReadiness();
|
||||
openPlanToday(qs('#plan-today'));
|
||||
});
|
||||
qs('#save-today-plan').addEventListener('click', () => {
|
||||
const result = planToday.commit();
|
||||
if (result === 'saved') taskOverlayHistory.leave();
|
||||
@@ -3870,15 +4197,10 @@
|
||||
qs('#my-work-action-status').textContent = 'No visible work to start.';
|
||||
return;
|
||||
}
|
||||
workSession.start();
|
||||
});
|
||||
qs('#resume-today-session').addEventListener('click', () => {
|
||||
qs('[data-work-filter="today"]').click();
|
||||
if (!workSession.resume()) {
|
||||
qs('#my-work-action-status').textContent = 'Saved Today session is no longer available.';
|
||||
updateWorkSessionActions();
|
||||
}
|
||||
if (selectedWorkFilter === 'today') runTodayTransition('start');
|
||||
else workSession.start();
|
||||
});
|
||||
qs('#resume-today-session').addEventListener('click', () => resumeTodaySession());
|
||||
qs('#end-today-session').addEventListener('click', () => {
|
||||
workSession.end();
|
||||
qs('#my-work-action-status').textContent = 'Today session ended. Your plan is unchanged.';
|
||||
@@ -3888,7 +4210,12 @@
|
||||
button.addEventListener('click', () => workSession.previous())
|
||||
);
|
||||
document.querySelectorAll('[data-work-session-next]').forEach(button =>
|
||||
button.addEventListener('click', () => workSession.next())
|
||||
button.addEventListener('click', () => workSession.checkpointed() ? runTodayTransition('next') : workSession.next())
|
||||
);
|
||||
document.querySelectorAll('[data-work-session-complete]').forEach(button =>
|
||||
button.addEventListener('click', () =>
|
||||
completeTodayItem(selectedSessionItem(button.dataset.workSessionComplete))
|
||||
)
|
||||
);
|
||||
qs('#load-more-notifications').addEventListener('click', () =>
|
||||
notificationPager.loadMore(lastNotifications)
|
||||
|
||||
+15
-3
@@ -139,22 +139,34 @@ function createDraftInbox({ storage, getCurrentLogin = () => '', now = () => Dat
|
||||
return record.items.filter(item => item && typeof item.id === 'string' && typeof item.body === 'string')
|
||||
.map(item => {
|
||||
const isUpdate = item.kind === 'update-reply';
|
||||
const routeKind = item.kind === 'pull-comment' ? 'pull' : 'issue';
|
||||
const isReview = item.kind === 'pull-review';
|
||||
const isClosure = item.kind === 'issue-close';
|
||||
const routeKind = isReview ? 'review' : (item.kind === 'pull-comment' ? 'pull' : 'issue');
|
||||
const target = isUpdate ? 'Update #' + item.notificationId : item.repository + '#' + item.number;
|
||||
const inlineFeedback = isReview && Array.isArray(item.comments) ? item.comments.map(comment =>
|
||||
String(comment.path || 'File') + ' · ' +
|
||||
(comment.new_position ? 'new line ' + comment.new_position : 'old line ' + comment.old_position) +
|
||||
': ' + String(comment.body || '')
|
||||
).filter(Boolean) : [];
|
||||
const copyText = [item.body, inlineFeedback.length ? 'Inline feedback\n' + inlineFeedback.join('\n') : '']
|
||||
.filter(Boolean).join('\n\n');
|
||||
const ownerLogin = String(item.ownerLogin || '').trim();
|
||||
const quarantined = !ownerLogin || !currentLogin || ownerLogin !== currentLogin;
|
||||
return {
|
||||
id: 'stackchain.authored-outbox.v1:' + item.id,
|
||||
outbox_id: item.id,
|
||||
outbox_kind: item.kind,
|
||||
kind: 'authored-outbox',
|
||||
status: item.status === 'attention' ? 'attention' : 'queued',
|
||||
label: item.deliveryState === 'uncertain' ? 'Verify delivery' :
|
||||
(item.status === 'attention' ? 'Needs attention' : 'Queued message'),
|
||||
(item.status === 'attention' ? (isClosure ? 'Issue closure needs attention' : 'Needs attention') :
|
||||
(isReview ? 'Queued review' : (isClosure ? 'Queued issue closure' : 'Queued message'))),
|
||||
delivery_state: item.deliveryState,
|
||||
repository: isUpdate ? '' : item.repository,
|
||||
title: target,
|
||||
preview: textPreview([item.error, item.body].filter(Boolean).join(' — ')),
|
||||
copy_text: item.body,
|
||||
copy_text: copyText,
|
||||
...(isReview ? { head_sha: item.expectedHeadSha } : {}),
|
||||
quarantined,
|
||||
ownership: quarantined ? 'Queued by ' + (ownerLogin || 'an unknown account') +
|
||||
(currentLogin ? ' — current account is ' + currentLogin : ' — account confirmation unavailable') : '',
|
||||
|
||||
+39
-2
@@ -196,6 +196,24 @@
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="today-readiness-sheet" id="today-readiness-sheet" role="dialog" aria-modal="true" aria-labelledby="today-readiness-title" hidden>
|
||||
<section class="today-readiness-panel">
|
||||
<div class="today-readiness-header">
|
||||
<div><div class="small">Today readiness</div><h2 id="today-readiness-title">This item is blocked</h2></div>
|
||||
<button id="today-readiness-close" type="button">Close</button>
|
||||
</div>
|
||||
<p id="today-readiness-summary" aria-live="polite"></p>
|
||||
<div class="today-readiness-item" id="today-readiness-item"></div>
|
||||
<div class="issue-blocker-list" id="today-readiness-blockers"></div>
|
||||
<div class="today-readiness-actions">
|
||||
<button id="today-readiness-next" type="button">Start next ready</button>
|
||||
<button id="today-readiness-anyway" type="button">Work this item anyway</button>
|
||||
<button id="today-readiness-retry" type="button">Retry status</button>
|
||||
<button id="today-readiness-plan" type="button">Review Today plan</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="plan-preview-actions" id="plan-preview-actions" hidden>
|
||||
<button id="back-to-plan" type="button">Back to plan</button>
|
||||
<button id="add-plan-preview" type="button">Add to Today & back</button>
|
||||
@@ -262,6 +280,11 @@
|
||||
<button class="issue-retry" id="retry-issue-load" type="button" hidden>Reload latest issue</button>
|
||||
<div class="row"><span id="issue-labels"></span><span class="small" id="issue-assignees"></span></div>
|
||||
<div class="issue-sheet-content markdown-content" id="issue-sheet-body"></div>
|
||||
<section class="issue-blockers" id="issue-blockers" aria-labelledby="issue-blockers-title" hidden>
|
||||
<h2 id="issue-blockers-title">Blocked by</h2>
|
||||
<div class="issue-blocker-list" id="issue-blocker-list"></div>
|
||||
<div id="issue-blocker-status" class="small" aria-live="polite"></div>
|
||||
</section>
|
||||
<h2>Full conversation</h2>
|
||||
<div id="issue-comments"></div>
|
||||
<button class="conversation-more" id="load-older-issue-comments" type="button" hidden>Load older messages</button>
|
||||
@@ -269,7 +292,10 @@
|
||||
<section class="issue-comment-composer" aria-labelledby="issue-comment-title">
|
||||
<h2 id="issue-comment-title">Add comment</h2>
|
||||
<textarea id="issue-comment" maxlength="10000" placeholder="Write a comment"></textarea>
|
||||
<button id="send-issue-comment" type="button">Post comment</button>
|
||||
<div class="comment-actions">
|
||||
<button id="send-issue-comment" type="button">Post comment</button>
|
||||
<button id="send-issue-comment-next" type="button" hidden>Comment & next</button>
|
||||
</div>
|
||||
<div id="issue-comment-status" class="small" aria-live="assertive"></div>
|
||||
</section>
|
||||
<details class="issue-planning" id="issue-planning">
|
||||
@@ -333,6 +359,7 @@
|
||||
<nav class="work-session-nav" aria-label="Work session" hidden>
|
||||
<span class="small" aria-live="polite" data-work-session-progress></span>
|
||||
<button type="button" data-work-session-previous>Previous</button>
|
||||
<button type="button" data-work-session-complete="issue" hidden>Done for Today & next</button>
|
||||
<button type="button" data-work-session-next>Next work item</button>
|
||||
</nav>
|
||||
</section>
|
||||
@@ -448,6 +475,7 @@
|
||||
<nav class="work-session-nav" aria-label="Work session" hidden>
|
||||
<span class="small" aria-live="polite" data-work-session-progress></span>
|
||||
<button type="button" data-work-session-previous>Previous</button>
|
||||
<button type="button" data-work-session-complete="update" hidden>Done for Today & next</button>
|
||||
<button type="button" data-work-session-next>Next work item</button>
|
||||
</nav>
|
||||
</section>
|
||||
@@ -468,7 +496,10 @@
|
||||
<section class="pull-comment-composer" aria-labelledby="pull-comment-title">
|
||||
<h2 id="pull-comment-title">Add comment</h2>
|
||||
<textarea id="pull-comment" maxlength="10000" placeholder="Write a comment"></textarea>
|
||||
<button id="send-pull-comment" type="button">Post comment</button>
|
||||
<div class="comment-actions">
|
||||
<button id="send-pull-comment" type="button">Post comment</button>
|
||||
<button id="send-pull-comment-next" type="button" hidden>Comment & next</button>
|
||||
</div>
|
||||
<div id="pull-comment-status" class="small" aria-live="assertive"></div>
|
||||
</section>
|
||||
<details class="pull-review" id="pull-review">
|
||||
@@ -488,6 +519,7 @@
|
||||
<nav class="work-session-nav" aria-label="Work session" hidden>
|
||||
<span class="small" aria-live="polite" data-work-session-progress></span>
|
||||
<button type="button" data-work-session-previous>Previous</button>
|
||||
<button type="button" data-work-session-complete="pull" hidden>Done for Today & next</button>
|
||||
<button type="button" data-work-session-next>Next work item</button>
|
||||
</nav>
|
||||
</section>
|
||||
@@ -552,6 +584,7 @@
|
||||
<nav class="work-session-nav" aria-label="Work session" hidden>
|
||||
<span class="small" aria-live="polite" data-work-session-progress></span>
|
||||
<button type="button" data-work-session-previous>Previous</button>
|
||||
<button type="button" data-work-session-complete="review" hidden>Done for Today & next</button>
|
||||
<button type="button" data-work-session-next>Next work item</button>
|
||||
</nav>
|
||||
</section>
|
||||
@@ -590,12 +623,16 @@
|
||||
<script src="static/background-issue-sync.js"></script>
|
||||
<script src="static/issue-outbox.js"></script>
|
||||
<script src="static/authored-outbox.js"></script>
|
||||
<script src="static/offline-issue-close.js"></script>
|
||||
<script src="static/notification-read-outbox.js"></script>
|
||||
<script src="static/offline-work.js"></script>
|
||||
<script src="static/offline-today.js"></script>
|
||||
<script src="static/my-work.js"></script>
|
||||
<script src="static/card-planning.js"></script>
|
||||
<script src="static/today-work.js"></script>
|
||||
<script src="static/today-completion.js"></script>
|
||||
<script src="static/today-readiness.js"></script>
|
||||
<script src="static/comment-next.js"></script>
|
||||
<script src="static/plan-today.js"></script>
|
||||
<script src="static/plan-today-preview.js"></script>
|
||||
<script src="static/today-sync.js"></script>
|
||||
|
||||
+38
-7
@@ -563,27 +563,31 @@ function createWorkSession({
|
||||
|
||||
return {
|
||||
active: () => running,
|
||||
checkpointed: () => running && durable,
|
||||
checkpointed: item => running && durable && (!item || workIdentity(item) === currentIdentity),
|
||||
end: () => finish(),
|
||||
resumable: () => Boolean(checkpoint?.read()),
|
||||
reopen() {
|
||||
reopen(requested = null) {
|
||||
if (!running) return false;
|
||||
const items = queue();
|
||||
const index = items.findIndex(item => workIdentity(item) === currentIdentity);
|
||||
const requestedIdentity = requested ? workIdentity(requested) : currentIdentity;
|
||||
const index = items.findIndex(item => workIdentity(item) === requestedIdentity);
|
||||
if (index < 0) return false;
|
||||
currentIdentity = requestedIdentity;
|
||||
currentIndex = index;
|
||||
if (durable && requested) checkpoint?.save(currentIdentity, currentIndex);
|
||||
report(items, index);
|
||||
onOpen(items[index]);
|
||||
return true;
|
||||
},
|
||||
resume() {
|
||||
resume(requested = null) {
|
||||
const saved = checkpoint?.read();
|
||||
if (!saved) return false;
|
||||
durable = true;
|
||||
const items = queue();
|
||||
if (!items.length) return finish();
|
||||
running = true;
|
||||
const exact = items.findIndex(item => workIdentity(item) === saved.identity);
|
||||
const exact = items.findIndex(item => workIdentity(item) ===
|
||||
(requested ? workIdentity(requested) : saved.identity));
|
||||
return openAt(items, exact >= 0 ? exact : Math.min(saved.index, items.length - 1));
|
||||
},
|
||||
start(item = null) {
|
||||
@@ -609,21 +613,48 @@ function createWorkSession({
|
||||
const index = items.findIndex(item => workIdentity(item) === currentIdentity);
|
||||
return index > 0 ? openAt(items, index - 1) : false;
|
||||
},
|
||||
next() {
|
||||
next(requested = null) {
|
||||
if (!running) return false;
|
||||
const items = queue();
|
||||
const index = items.findIndex(item => workIdentity(item) === currentIdentity);
|
||||
if (requested) {
|
||||
const requestedIndex = items.findIndex(item => workIdentity(item) === workIdentity(requested));
|
||||
return requestedIndex >= 0 ? openAt(items, requestedIndex) : false;
|
||||
}
|
||||
return index >= 0 && index < items.length - 1 ? openAt(items, index + 1) : finish();
|
||||
},
|
||||
complete() {
|
||||
complete(requested = null) {
|
||||
if (!running) return false;
|
||||
const items = queue();
|
||||
if (requested) {
|
||||
const requestedIndex = items.findIndex(item => workIdentity(item) === workIdentity(requested));
|
||||
return requestedIndex >= 0 ? openAt(items, requestedIndex) : false;
|
||||
}
|
||||
const stillPresent = items.findIndex(item => workIdentity(item) === currentIdentity);
|
||||
if (stillPresent >= 0) {
|
||||
return stillPresent < items.length - 1 ? openAt(items, stillPresent + 1) : finish();
|
||||
}
|
||||
return items.length ? openAt(items, Math.min(currentIndex, items.length - 1)) : finish();
|
||||
},
|
||||
items: () => queue().slice(),
|
||||
target(action) {
|
||||
const items = queue();
|
||||
if (!items.length) return null;
|
||||
if (action === 'start') return items[0];
|
||||
if (action === 'resume') {
|
||||
const saved = checkpoint?.read();
|
||||
if (!saved) return null;
|
||||
const exact = items.findIndex(item => workIdentity(item) === saved.identity);
|
||||
return items[exact >= 0 ? exact : Math.min(saved.index, items.length - 1)];
|
||||
}
|
||||
const current = items.findIndex(item => workIdentity(item) === currentIdentity);
|
||||
if (action === 'continue') return current >= 0 ? items[current] : null;
|
||||
if (action === 'next') return current >= 0 && current < items.length - 1 ? items[current + 1] : null;
|
||||
if (action === 'complete') {
|
||||
return items[current >= 0 ? Math.min(current + 1, items.length - 1) : Math.min(currentIndex, items.length - 1)];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
function createOfflineIssueClose({ enqueueDurably, completeToday, createOperationId = () =>
|
||||
globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random().toString(16).slice(2) }) {
|
||||
return async function closeOfflineIssue(item) {
|
||||
const admission = await enqueueDurably({
|
||||
kind: 'issue-close',
|
||||
repository: String(item.repository || ''),
|
||||
number: Number(item.number || 0),
|
||||
body: '',
|
||||
operationId: String(createOperationId()).slice(0, 128),
|
||||
});
|
||||
const advanced = Boolean(completeToday(item, {
|
||||
successMessage: 'Issue closure queued. Next Today item opened.',
|
||||
failureMessage: 'Issue closure queued, but Today still needs completion.',
|
||||
}));
|
||||
return { admission, advanced };
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createOfflineIssueClose;
|
||||
@@ -22,8 +22,19 @@
|
||||
return true;
|
||||
}
|
||||
|
||||
function close({ add = false } = {}) {
|
||||
function setDependencies({ available, dependencies } = {}) {
|
||||
if (!current) return false;
|
||||
current.dependencies_available = available === true;
|
||||
current.dependencies = Array.isArray(dependencies) ? dependencies.filter(item => item?.state === 'open') : [];
|
||||
current.requires_override = !current.dependencies_available || current.dependencies.length > 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
function close({ add = false, override = false } = {}) {
|
||||
if (!current) return 'closed';
|
||||
if (add && current.requires_override && !override) {
|
||||
return current.dependencies_available ? 'blocked' : 'dependencies-unavailable';
|
||||
}
|
||||
const { item, trigger, scroll } = current;
|
||||
let result = 'returned';
|
||||
if (add) {
|
||||
@@ -37,9 +48,16 @@
|
||||
}
|
||||
|
||||
function snapshot() {
|
||||
return current ? { open:true, item:current.item, trigger:current.trigger, scroll:current.scroll } : { open:false };
|
||||
if (!current) return { open:false };
|
||||
const state = { open:true, item:current.item, trigger:current.trigger, scroll:current.scroll };
|
||||
if (Object.prototype.hasOwnProperty.call(current, 'dependencies_available')) {
|
||||
state.dependencies_available = current.dependencies_available;
|
||||
state.dependencies = current.dependencies;
|
||||
state.requires_override = current.requires_override;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
return { open, close, snapshot };
|
||||
return { open, close, setDependencies, snapshot };
|
||||
};
|
||||
});
|
||||
@@ -169,7 +169,7 @@ function createProgress({ storage, repository, number, headSha, files }) {
|
||||
return snapshot();
|
||||
}
|
||||
|
||||
return { snapshot, markReviewed, clear };
|
||||
return { snapshot, markReviewed, clear, storageKey: key };
|
||||
}
|
||||
|
||||
function createDraft({ storage, repository, number, headSha, files }) {
|
||||
@@ -267,7 +267,10 @@ function createDraft({ storage, repository, number, headSha, files }) {
|
||||
return snapshot();
|
||||
}
|
||||
|
||||
return { snapshot, setNote, setInlineComment, removeInlineComment, setSummary, setDecision, clear };
|
||||
return {
|
||||
snapshot, setNote, setInlineComment, removeInlineComment, setSummary, setDecision, clear,
|
||||
storageKey: key,
|
||||
};
|
||||
}
|
||||
|
||||
function formatFeedback(draft, files) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
const BASE = new URL('./', self.location.href).pathname;
|
||||
importScripts(BASE + 'static/background-issue-sync.js');
|
||||
const CACHE = 'stackchain-dashboard-shell-v67';
|
||||
const CACHE = 'stackchain-dashboard-shell-v73';
|
||||
const OFFLINE_LEASE_URL = new URL(BASE + '__offline-session-lease', self.location.origin).href;
|
||||
const OUTAGE_STATUSES = new Set([500, 502, 503, 504]);
|
||||
const NAVIGATION_TIMEOUT_MS = self.__STACKCHAIN_NAVIGATION_TIMEOUT_MS || 4000;
|
||||
@@ -21,12 +21,16 @@ const SHELL = [
|
||||
BASE + 'static/outbox-coordinator.js',
|
||||
BASE + 'static/issue-outbox.js',
|
||||
BASE + 'static/authored-outbox.js',
|
||||
BASE + 'static/offline-issue-close.js',
|
||||
BASE + 'static/notification-read-outbox.js',
|
||||
BASE + 'static/offline-work.js',
|
||||
BASE + 'static/offline-today.js',
|
||||
BASE + 'static/my-work.js',
|
||||
BASE + 'static/card-planning.js',
|
||||
BASE + 'static/today-work.js',
|
||||
BASE + 'static/today-completion.js',
|
||||
BASE + 'static/today-readiness.js',
|
||||
BASE + 'static/comment-next.js',
|
||||
BASE + 'static/plan-today.js',
|
||||
BASE + 'static/plan-today-preview.js',
|
||||
BASE + 'static/today-sync.js',
|
||||
@@ -216,7 +220,10 @@ self.addEventListener('sync', event => {
|
||||
});
|
||||
|
||||
self.addEventListener('message', event => {
|
||||
if (event.data?.type === 'stackchain-resume-outbox') event.waitUntil(flushAndNotify());
|
||||
if (event.data?.type === 'stackchain-resume-outbox') event.waitUntil((async () => {
|
||||
await issueSync.resume();
|
||||
await flushAndNotify();
|
||||
})());
|
||||
if (event.data?.type === 'stackchain-session-lease') {
|
||||
event.waitUntil(storeOfflineLease(event.data.expiresAt));
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
|
||||
'use strict';
|
||||
|
||||
const allowed = new Set(['new', 'find', 'search', 'search-preview', 'plan-today', 'plan-today-preview']);
|
||||
const allowed = new Set(['new', 'find', 'search', 'search-preview', 'plan-today', 'plan-today-preview', 'today-readiness']);
|
||||
|
||||
return function createTaskOverlayHistory({ history, eventTarget, onChange }) {
|
||||
let active = allowed.has(history.state?.taskOverlay) ? history.state.taskOverlay : null;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
function createTodayCompletion({ todayWork, todaySync, workSession, refresh, warm, announce, advance = null }) {
|
||||
return function completeTodayItem(item, options = {}) {
|
||||
if (!item || !todayWork.remove(item)) {
|
||||
announce(options.failureMessage || 'Could not update Today on this device. Try again.');
|
||||
return false;
|
||||
}
|
||||
todaySync.enqueue('remove', todayWork.identity(item));
|
||||
todaySync.flush();
|
||||
refresh();
|
||||
warm();
|
||||
(advance || (() => workSession.complete()))();
|
||||
announce(options.successMessage || 'Done for Today. The Gitea item is unchanged.');
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createTodayCompletion;
|
||||
@@ -0,0 +1,78 @@
|
||||
(function (root, factory) {
|
||||
const api = factory();
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.createTodayReadiness = api;
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
|
||||
'use strict';
|
||||
|
||||
return function createTodayReadiness({ inspect, onOpen = () => {}, onGate = () => {} }) {
|
||||
let pending = null;
|
||||
let generation = 0;
|
||||
|
||||
async function classify(item) {
|
||||
if (item?.kind !== 'issue') return { status:'ready', dependencies:[] };
|
||||
try {
|
||||
const detail = await inspect(item);
|
||||
if (detail?.available !== true) return { status:'unknown', dependencies:[] };
|
||||
const dependencies = Array.isArray(detail.dependencies)
|
||||
? detail.dependencies.filter(dependency => dependency?.state === 'open')
|
||||
: [];
|
||||
return { status:dependencies.length ? 'blocked' : 'ready', dependencies };
|
||||
} catch (_error) {
|
||||
return { status:'unknown', dependencies:[] };
|
||||
}
|
||||
}
|
||||
|
||||
async function run(action, items, target = null) {
|
||||
const request = ++generation;
|
||||
const ordered = Array.isArray(items) ? items.slice() : [];
|
||||
const preferred = target || ordered[0] || null;
|
||||
if (!preferred) return 'empty';
|
||||
const preferredIndex = ordered.indexOf(preferred);
|
||||
const candidates = preferredIndex >= 0
|
||||
? ordered.slice(preferredIndex).concat(ordered.slice(0, preferredIndex))
|
||||
: [preferred].concat(ordered);
|
||||
const states = [];
|
||||
for (const item of candidates) states.push({ item, ...(await classify(item)) });
|
||||
if (request !== generation) return 'superseded';
|
||||
const targetState = states[0];
|
||||
if (targetState.status === 'ready') {
|
||||
pending = null;
|
||||
onOpen(action, preferred);
|
||||
return 'opened';
|
||||
}
|
||||
const nextReadyState = states.slice(1).find(state => state.status === 'ready');
|
||||
pending = {
|
||||
action,
|
||||
items:ordered,
|
||||
target:preferred,
|
||||
status:targetState.status,
|
||||
dependencies:targetState.dependencies,
|
||||
nextReady:nextReadyState?.item || null,
|
||||
};
|
||||
onGate({ ...pending, items:pending.items.slice() });
|
||||
return 'gated';
|
||||
}
|
||||
|
||||
function open(item) {
|
||||
if (!pending || !item) return false;
|
||||
const action = pending.action;
|
||||
pending = null;
|
||||
generation += 1;
|
||||
onOpen(action, item);
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
run,
|
||||
retry: () => pending ? run(pending.action, pending.items, pending.target) : Promise.resolve('closed'),
|
||||
startNextReady: () => open(pending?.nextReady),
|
||||
workAnyway: () => open(pending?.target),
|
||||
cancel() {
|
||||
generation += 1;
|
||||
pending = null;
|
||||
},
|
||||
snapshot: () => pending ? { ...pending, items:pending.items.slice() } : { open:false },
|
||||
};
|
||||
};
|
||||
});
|
||||
+4
-2
@@ -25,7 +25,7 @@ def _quality(accept_encoding: str, coding: str) -> float:
|
||||
class NegotiatedGZipMiddleware:
|
||||
"""Compress substantial responses only when the client permits gzip."""
|
||||
|
||||
def __init__(self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9):
|
||||
def __init__(self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 6):
|
||||
self.app = app
|
||||
self.minimum_size = minimum_size
|
||||
self.compresslevel = compresslevel
|
||||
@@ -36,7 +36,9 @@ class NegotiatedGZipMiddleware:
|
||||
return
|
||||
|
||||
accepted = Headers(scope=scope).get("Accept-Encoding", "")
|
||||
if _quality(accepted, "gzip") > 0:
|
||||
path = scope.get("path", "").rsplit("/", 1)[-1]
|
||||
immutable_runtime = path.startswith("runtime-") and path.endswith(".js")
|
||||
if _quality(accepted, "gzip") > 0 and not immutable_runtime:
|
||||
responder: ASGIApp = GZipResponder(
|
||||
self.app, self.minimum_size, compresslevel=self.compresslevel
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
@@ -16,6 +17,7 @@ WORKER_RUNTIME_SOURCE = "static/background-issue-sync.js"
|
||||
class FrontendBuild:
|
||||
dashboard_html: str
|
||||
runtime_bytes: bytes
|
||||
runtime_gzip_bytes: bytes
|
||||
runtime_digest: str
|
||||
runtime_name: str
|
||||
page_sources: tuple[str, ...]
|
||||
@@ -38,6 +40,7 @@ def build_frontend(frontend_dir: Path) -> FrontendBuild:
|
||||
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"
|
||||
dashboard_html = SCRIPT_TAG.sub("", source_html)
|
||||
@@ -63,6 +66,7 @@ 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,
|
||||
page_sources=sources,
|
||||
|
||||
+44
-2
@@ -1343,9 +1343,19 @@ async def issue_conversation_page(
|
||||
|
||||
async def issue_detail(repository: str, number: int) -> dict:
|
||||
base = f"repos/{repository}/issues/{number}"
|
||||
issue, conversation = await asyncio.gather(
|
||||
fetch(base), issue_conversation_page(repository, number)
|
||||
|
||||
async def load_dependencies() -> tuple[bool, list[dict]]:
|
||||
try:
|
||||
return True, await issue_dependencies(repository, number)
|
||||
except Exception:
|
||||
return False, []
|
||||
|
||||
issue, conversation, dependency_result = await asyncio.gather(
|
||||
fetch(base),
|
||||
issue_conversation_page(repository, number),
|
||||
load_dependencies(),
|
||||
)
|
||||
dependencies_available, dependencies = dependency_result
|
||||
if not isinstance(issue, dict):
|
||||
raise ValueError("Gitea issue response was not an object")
|
||||
labels_value = issue.get("labels")
|
||||
@@ -1377,11 +1387,43 @@ async def issue_detail(repository: str, number: int) -> dict:
|
||||
assignee["login"] for assignee in assignees
|
||||
if isinstance(assignee, dict) and isinstance(assignee.get("login"), str)
|
||||
],
|
||||
"dependencies_available": dependencies_available,
|
||||
"dependencies": dependencies,
|
||||
"comments": normalized_comments,
|
||||
"conversation": conversation,
|
||||
}
|
||||
|
||||
|
||||
async def issue_dependencies(repository: str, number: int, limit: int = 20) -> list[dict]:
|
||||
"""Return bounded open prerequisites for an issue."""
|
||||
response = await _get_client().get(
|
||||
f"/api/v1/repos/{repository}/issues/{number}/dependencies",
|
||||
headers=_auth(),
|
||||
params={"limit": limit},
|
||||
)
|
||||
response.raise_for_status()
|
||||
value = response.json()
|
||||
items = value if isinstance(value, list) else []
|
||||
dependencies = []
|
||||
for item in items[:limit]:
|
||||
if not isinstance(item, dict) or item.get("state") != "open":
|
||||
continue
|
||||
repo_value = item.get("repository")
|
||||
repo = repo_value if isinstance(repo_value, dict) else {}
|
||||
dependency_repository = repo.get("full_name")
|
||||
dependency_number = item.get("number")
|
||||
if not isinstance(dependency_repository, str) or not isinstance(dependency_number, int):
|
||||
continue
|
||||
dependencies.append({
|
||||
"repository": dependency_repository,
|
||||
"number": dependency_number,
|
||||
"title": item.get("title", "") if isinstance(item.get("title"), str) else "",
|
||||
"state": "open",
|
||||
"url": _safe_web_url(item.get("html_url")),
|
||||
})
|
||||
return dependencies
|
||||
|
||||
|
||||
async def update_assigned_issue(
|
||||
repository: str,
|
||||
number: int,
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
"""Process-shared live snapshot state and refresh coordination."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import stat
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable, Iterable
|
||||
|
||||
SECTIONS = ("context", "events", "notifications")
|
||||
|
||||
|
||||
class RefreshLeaseLost(RuntimeError):
|
||||
"""The refresh is no longer authorized to publish shared state."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LiveSnapshotState:
|
||||
value: dict | None
|
||||
created_at: dict[str, float | None]
|
||||
failure_count: dict[str, int]
|
||||
retry_at: dict[str, float | None]
|
||||
revisions: dict[str, int]
|
||||
generation: str
|
||||
refreshing_sections: set[str]
|
||||
lease_expires_at: float | None
|
||||
|
||||
|
||||
class LiveSnapshotStore:
|
||||
"""A private SQLite snapshot with an expiring, cross-process refresh lease."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
path: str | os.PathLike[str],
|
||||
*,
|
||||
clock: Callable[[], float] | None = None,
|
||||
):
|
||||
self.path = Path(path)
|
||||
self.clock = clock or time.time
|
||||
self._initialize()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
connection = sqlite3.connect(self.path, timeout=1.0, isolation_level=None)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA busy_timeout = 1000")
|
||||
return connection
|
||||
|
||||
def _initialize(self) -> None:
|
||||
self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
try:
|
||||
os.chmod(self.path.parent, stat.S_IRWXU)
|
||||
except OSError:
|
||||
pass
|
||||
old_umask = os.umask(0o077)
|
||||
try:
|
||||
with self._connect() as connection:
|
||||
connection.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS live_snapshot (
|
||||
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
||||
value_json TEXT,
|
||||
created_at_json TEXT NOT NULL,
|
||||
failure_count_json TEXT NOT NULL,
|
||||
retry_at_json TEXT NOT NULL,
|
||||
revisions_json TEXT NOT NULL,
|
||||
generation TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS live_refresh_lease (
|
||||
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
||||
owner TEXT NOT NULL,
|
||||
sections_json TEXT NOT NULL,
|
||||
expires_at REAL NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS live_read_notification (
|
||||
notification_id INTEGER PRIMARY KEY
|
||||
);
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""INSERT OR IGNORE INTO live_snapshot VALUES
|
||||
(1, NULL, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
json.dumps({section: None for section in SECTIONS}),
|
||||
json.dumps({section: 0 for section in SECTIONS}),
|
||||
json.dumps({section: None for section in SECTIONS}),
|
||||
json.dumps({section: 0 for section in SECTIONS}),
|
||||
secrets.token_hex(8),
|
||||
),
|
||||
)
|
||||
finally:
|
||||
os.umask(old_umask)
|
||||
os.chmod(self.path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
|
||||
def try_acquire_refresh(
|
||||
self, sections: Iterable[str], *, lease_seconds: float
|
||||
) -> str | None:
|
||||
requested = sorted(set(sections))
|
||||
if not requested or any(section not in SECTIONS for section in requested):
|
||||
raise ValueError("refresh lease requires known sections")
|
||||
if lease_seconds <= 0:
|
||||
raise ValueError("refresh lease duration must be positive")
|
||||
now = self.clock()
|
||||
owner = secrets.token_hex(16)
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
active = connection.execute(
|
||||
"SELECT expires_at FROM live_refresh_lease WHERE singleton = 1"
|
||||
).fetchone()
|
||||
if active is not None and active["expires_at"] > now:
|
||||
connection.rollback()
|
||||
return None
|
||||
connection.execute("DELETE FROM live_refresh_lease WHERE singleton = 1")
|
||||
connection.execute(
|
||||
"INSERT INTO live_refresh_lease VALUES (1, ?, ?, ?)",
|
||||
(owner, json.dumps(requested, separators=(",", ":")), now + lease_seconds),
|
||||
)
|
||||
connection.commit()
|
||||
return owner
|
||||
|
||||
def load(self) -> LiveSnapshotState:
|
||||
now = self.clock()
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM live_snapshot WHERE singleton = 1"
|
||||
).fetchone()
|
||||
lease = connection.execute(
|
||||
"SELECT sections_json, expires_at FROM live_refresh_lease "
|
||||
"WHERE singleton = 1 AND expires_at > ?",
|
||||
(now,),
|
||||
).fetchone()
|
||||
assert row is not None
|
||||
return LiveSnapshotState(
|
||||
value=json.loads(row["value_json"]) if row["value_json"] is not None else None,
|
||||
created_at=json.loads(row["created_at_json"]),
|
||||
failure_count=json.loads(row["failure_count_json"]),
|
||||
retry_at=json.loads(row["retry_at_json"]),
|
||||
revisions=json.loads(row["revisions_json"]),
|
||||
generation=row["generation"],
|
||||
refreshing_sections=set(json.loads(lease["sections_json"])) if lease else set(),
|
||||
lease_expires_at=lease["expires_at"] if lease else None,
|
||||
)
|
||||
|
||||
def publish_refresh(
|
||||
self,
|
||||
owner: str,
|
||||
*,
|
||||
value: dict,
|
||||
created_at: dict[str, float | None],
|
||||
failure_count: dict[str, int],
|
||||
retry_at: dict[str, float | None],
|
||||
changed_sections: Iterable[str],
|
||||
) -> LiveSnapshotState:
|
||||
changed = set(changed_sections)
|
||||
if changed - set(SECTIONS):
|
||||
raise ValueError("publication contains unknown sections")
|
||||
if any(set(mapping) != set(SECTIONS) for mapping in (created_at, failure_count, retry_at)):
|
||||
raise ValueError("publication metadata must contain every section")
|
||||
now = self.clock()
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
lease = connection.execute(
|
||||
"SELECT owner, expires_at FROM live_refresh_lease WHERE singleton = 1"
|
||||
).fetchone()
|
||||
if lease is None or lease["owner"] != owner or lease["expires_at"] <= now:
|
||||
connection.rollback()
|
||||
raise RefreshLeaseLost("live refresh lease expired or changed owner")
|
||||
row = connection.execute(
|
||||
"SELECT revisions_json FROM live_snapshot WHERE singleton = 1"
|
||||
).fetchone()
|
||||
revisions = json.loads(row["revisions_json"])
|
||||
notifications = value.get("notifications")
|
||||
if isinstance(notifications, list):
|
||||
returned_ids = {
|
||||
item.get("id") for item in notifications if isinstance(item, dict)
|
||||
}
|
||||
read_ids = {
|
||||
item["notification_id"]
|
||||
for item in connection.execute(
|
||||
"SELECT notification_id FROM live_read_notification"
|
||||
)
|
||||
}
|
||||
value = dict(value)
|
||||
value["notifications"] = [
|
||||
item for item in notifications
|
||||
if not isinstance(item, dict) or item.get("id") not in read_ids
|
||||
]
|
||||
if returned_ids:
|
||||
placeholders = ",".join("?" for _ in returned_ids)
|
||||
connection.execute(
|
||||
f"DELETE FROM live_read_notification WHERE notification_id NOT IN ({placeholders})",
|
||||
tuple(returned_ids),
|
||||
)
|
||||
else:
|
||||
connection.execute("DELETE FROM live_read_notification")
|
||||
for section in changed:
|
||||
revisions[section] += 1
|
||||
connection.execute(
|
||||
"""UPDATE live_snapshot SET value_json = ?, created_at_json = ?,
|
||||
failure_count_json = ?, retry_at_json = ?, revisions_json = ?
|
||||
WHERE singleton = 1""",
|
||||
(
|
||||
json.dumps(value, separators=(",", ":")),
|
||||
json.dumps(created_at, separators=(",", ":")),
|
||||
json.dumps(failure_count, separators=(",", ":")),
|
||||
json.dumps(retry_at, separators=(",", ":")),
|
||||
json.dumps(revisions, separators=(",", ":")),
|
||||
),
|
||||
)
|
||||
connection.execute(
|
||||
"DELETE FROM live_refresh_lease WHERE singleton = 1 AND owner = ?", (owner,)
|
||||
)
|
||||
connection.commit()
|
||||
return self.load()
|
||||
|
||||
def remove_notifications(self, notification_ids: Iterable[int]) -> LiveSnapshotState:
|
||||
"""Filter confirmed reads from every worker and subsequent stale refreshes."""
|
||||
read_ids = set(notification_ids)
|
||||
if not read_ids:
|
||||
return self.load()
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
connection.executemany(
|
||||
"INSERT OR IGNORE INTO live_read_notification VALUES (?)",
|
||||
((notification_id,) for notification_id in read_ids),
|
||||
)
|
||||
row = connection.execute(
|
||||
"SELECT value_json, revisions_json FROM live_snapshot WHERE singleton = 1"
|
||||
).fetchone()
|
||||
value = json.loads(row["value_json"]) if row["value_json"] else None
|
||||
revisions = json.loads(row["revisions_json"])
|
||||
if value is not None and isinstance(value.get("notifications"), list):
|
||||
previous = value["notifications"]
|
||||
retained = [
|
||||
item
|
||||
for item in previous
|
||||
if not isinstance(item, dict) or item.get("id") not in read_ids
|
||||
]
|
||||
if retained != previous:
|
||||
value["notifications"] = retained
|
||||
revisions["notifications"] += 1
|
||||
connection.execute(
|
||||
"UPDATE live_snapshot SET value_json = ?, revisions_json = ? WHERE singleton = 1",
|
||||
(
|
||||
json.dumps(value, separators=(",", ":")),
|
||||
json.dumps(revisions, separators=(",", ":")),
|
||||
),
|
||||
)
|
||||
connection.commit()
|
||||
return self.load()
|
||||
|
||||
def remove_notification(self, notification_id: int) -> LiveSnapshotState:
|
||||
"""Filter one confirmed read from every worker and subsequent stale refresh."""
|
||||
return self.remove_notifications([notification_id])
|
||||
|
||||
def release_refresh(self, owner: str) -> None:
|
||||
"""Relinquish a lease that became unnecessary after a coherent recheck."""
|
||||
with self._connect() as connection:
|
||||
connection.execute(
|
||||
"DELETE FROM live_refresh_lease WHERE singleton = 1 AND owner = ?",
|
||||
(owner,),
|
||||
)
|
||||
|
||||
def fail_refresh(
|
||||
self,
|
||||
owner: str,
|
||||
*,
|
||||
failure_count: dict[str, int],
|
||||
retry_at: dict[str, float | None],
|
||||
) -> LiveSnapshotState:
|
||||
"""Publish backoff metadata and relinquish a failed refresh atomically."""
|
||||
now = self.clock()
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
lease = connection.execute(
|
||||
"SELECT owner, expires_at FROM live_refresh_lease WHERE singleton = 1"
|
||||
).fetchone()
|
||||
if lease is None or lease["owner"] != owner or lease["expires_at"] <= now:
|
||||
connection.rollback()
|
||||
raise RefreshLeaseLost("live refresh lease expired or changed owner")
|
||||
connection.execute(
|
||||
"""UPDATE live_snapshot SET failure_count_json = ?, retry_at_json = ?
|
||||
WHERE singleton = 1""",
|
||||
(
|
||||
json.dumps(failure_count, separators=(",", ":")),
|
||||
json.dumps(retry_at, separators=(",", ":")),
|
||||
),
|
||||
)
|
||||
connection.execute("DELETE FROM live_refresh_lease WHERE singleton = 1")
|
||||
connection.commit()
|
||||
return self.load()
|
||||
+202
-36
@@ -34,6 +34,7 @@ from src.gitea_proxy import (
|
||||
)
|
||||
from src.idempotency import IdempotencyLedger, IdempotencyLedgerBusy
|
||||
from src.login_attempt_store import LoginAttemptStore, LoginAttemptStoreError, client_source
|
||||
from src.live_snapshot_store import LiveSnapshotState, LiveSnapshotStore, RefreshLeaseLost
|
||||
from src.models import Issue, Milestone, PullRequest, Repo, User
|
||||
from src.request_boundary import RequestBodyLimitMiddleware, request_body_limit
|
||||
from src.suggestion_engine import compute
|
||||
@@ -117,6 +118,11 @@ _authored_action_operations: dict[
|
||||
str, tuple[tuple[Any, ...], asyncio.Task, float]
|
||||
] = {}
|
||||
_state_dir = Path(os.getenv("STACKCHAIN_STATE_DIR", ".stackchain-state"))
|
||||
_live_snapshot_clock = time.time
|
||||
_live_snapshot_store = LiveSnapshotStore(
|
||||
os.getenv("STACKCHAIN_LIVE_SNAPSHOT_DB", str(_state_dir / "live-snapshot.sqlite3")),
|
||||
clock=lambda: _live_snapshot_clock(),
|
||||
)
|
||||
_idempotency_ledger = IdempotencyLedger(
|
||||
os.getenv("STACKCHAIN_IDEMPOTENCY_DB", str(_state_dir / "idempotency.sqlite3")),
|
||||
ttl_seconds=AUTHORED_ACTION_IDEMPOTENCY_TTL_SECONDS,
|
||||
@@ -1530,7 +1536,7 @@ def _record_live_section_failure(section: str) -> None:
|
||||
LIVE_SNAPSHOT_RETRY_BASE_SECONDS
|
||||
* (2 ** (_live_section_failure_count[section] - 1)),
|
||||
)
|
||||
_live_section_retry_at[section] = time.monotonic() + delay
|
||||
_live_section_retry_at[section] = _live_snapshot_clock() + delay
|
||||
|
||||
|
||||
def _due_live_sections(now: float) -> set[str]:
|
||||
@@ -1545,6 +1551,23 @@ def _due_live_sections(now: float) -> set[str]:
|
||||
return due
|
||||
|
||||
|
||||
def _apply_shared_live_state(state: LiveSnapshotState) -> None:
|
||||
"""Replace this worker's fast local view with one coherent SQLite read."""
|
||||
global _live_snapshot_value, _live_snapshot_created_at
|
||||
global _live_section_created_at, _live_section_failure_count, _live_section_retry_at
|
||||
global _live_section_revisions, _live_revision_generation
|
||||
global _live_snapshot_refreshing_sections
|
||||
_live_snapshot_value = state.value
|
||||
_live_section_created_at = state.created_at
|
||||
_live_section_failure_count = state.failure_count
|
||||
_live_section_retry_at = state.retry_at
|
||||
_live_section_revisions = state.revisions
|
||||
_live_revision_generation = state.generation
|
||||
_live_snapshot_refreshing_sections = state.refreshing_sections
|
||||
successful = [value for value in state.created_at.values() if value is not None]
|
||||
_live_snapshot_created_at = max(successful) if successful else None
|
||||
|
||||
|
||||
def _merge_live_snapshot(previous: dict | None, refreshed: dict) -> dict:
|
||||
if previous is None:
|
||||
return refreshed
|
||||
@@ -1567,15 +1590,32 @@ def _merge_live_snapshot(previous: dict | None, refreshed: dict) -> dict:
|
||||
return merged
|
||||
|
||||
|
||||
async def _refresh_live_snapshot(sections: set[str]) -> dict:
|
||||
async def _refresh_live_snapshot(sections: set[str], lease_owner: str) -> dict:
|
||||
global _live_snapshot_value, _live_snapshot_created_at
|
||||
try:
|
||||
refreshed = await _build_live_snapshot_before_deadline(sections)
|
||||
except asyncio.CancelledError:
|
||||
try:
|
||||
await asyncio.shield(
|
||||
asyncio.to_thread(_live_snapshot_store.release_refresh, lease_owner)
|
||||
)
|
||||
finally:
|
||||
raise
|
||||
except Exception:
|
||||
for section in sections:
|
||||
_record_live_section_failure(section)
|
||||
try:
|
||||
state = await asyncio.to_thread(
|
||||
_live_snapshot_store.fail_refresh,
|
||||
lease_owner,
|
||||
failure_count=_live_section_failure_count,
|
||||
retry_at=_live_section_retry_at,
|
||||
)
|
||||
_apply_shared_live_state(state)
|
||||
except RefreshLeaseLost:
|
||||
_apply_shared_live_state(await asyncio.to_thread(_live_snapshot_store.load))
|
||||
raise
|
||||
now = time.monotonic()
|
||||
now = _live_snapshot_clock()
|
||||
refreshed_states = refreshed.get("sections") or {}
|
||||
for section in sections:
|
||||
if refreshed_states.get(section) == "fresh":
|
||||
@@ -1587,6 +1627,7 @@ async def _refresh_live_snapshot(sections: set[str]) -> dict:
|
||||
previous = _live_snapshot_value
|
||||
result = _merge_live_snapshot(previous, refreshed)
|
||||
result = _without_read_notifications(result)
|
||||
changed_sections = set()
|
||||
for section in sections:
|
||||
if section not in refreshed_states:
|
||||
continue
|
||||
@@ -1596,11 +1637,24 @@ async def _refresh_live_snapshot(sections: set[str]) -> dict:
|
||||
"notification_pagination"
|
||||
) != result.get("notification_pagination")
|
||||
if changed:
|
||||
_live_section_revisions[section] += 1
|
||||
_live_snapshot_value = result
|
||||
successful_times = [value for value in _live_section_created_at.values() if value is not None]
|
||||
_live_snapshot_created_at = max(successful_times) if successful_times else None
|
||||
return result
|
||||
changed_sections.add(section)
|
||||
try:
|
||||
state = await asyncio.to_thread(
|
||||
_live_snapshot_store.publish_refresh,
|
||||
lease_owner,
|
||||
value=result,
|
||||
created_at=_live_section_created_at,
|
||||
failure_count=_live_section_failure_count,
|
||||
retry_at=_live_section_retry_at,
|
||||
changed_sections=changed_sections,
|
||||
)
|
||||
except RefreshLeaseLost:
|
||||
state = await asyncio.to_thread(_live_snapshot_store.load)
|
||||
if state.value is None:
|
||||
raise
|
||||
_apply_shared_live_state(state)
|
||||
assert state.value is not None
|
||||
return state.value
|
||||
|
||||
|
||||
def _consume_live_snapshot_failure(task: asyncio.Task) -> None:
|
||||
@@ -1609,12 +1663,22 @@ def _consume_live_snapshot_failure(task: asyncio.Task) -> None:
|
||||
task.exception()
|
||||
|
||||
|
||||
def _start_live_snapshot_refresh(sections: set[str]) -> asyncio.Task:
|
||||
def _start_live_snapshot_refresh(
|
||||
sections: set[str], lease_owner: str | None = None
|
||||
) -> asyncio.Task:
|
||||
global _live_snapshot_task
|
||||
global _live_snapshot_refreshing_sections
|
||||
if _live_snapshot_task is None or _live_snapshot_task.done():
|
||||
if lease_owner is None:
|
||||
lease_owner = _live_snapshot_store.try_acquire_refresh(
|
||||
sections, lease_seconds=CONTEXT_TIMEOUT_SECONDS + 1.0
|
||||
)
|
||||
if lease_owner is None:
|
||||
raise RuntimeError("live snapshot refresh lease is already held")
|
||||
_live_snapshot_refreshing_sections = set(sections)
|
||||
_live_snapshot_task = asyncio.create_task(_refresh_live_snapshot(sections))
|
||||
_live_snapshot_task = asyncio.create_task(
|
||||
_refresh_live_snapshot(sections, lease_owner)
|
||||
)
|
||||
_live_snapshot_task.add_done_callback(_consume_live_snapshot_failure)
|
||||
return _live_snapshot_task
|
||||
|
||||
@@ -1627,7 +1691,7 @@ def _live_snapshot_payload(
|
||||
known_revisions: dict[str, str | None] | None = None,
|
||||
) -> dict:
|
||||
payload = dict(value)
|
||||
now = time.monotonic()
|
||||
now = _live_snapshot_clock()
|
||||
section_freshness = {}
|
||||
for section in LIVE_SNAPSHOT_SECTIONS:
|
||||
created_at = _live_section_created_at[section]
|
||||
@@ -1671,23 +1735,30 @@ def _live_snapshot_payload(
|
||||
return payload
|
||||
|
||||
|
||||
def _remove_notification_from_live_snapshot(thread_id: int) -> None:
|
||||
async def _remove_notifications_from_live_snapshot(thread_ids: list[int]) -> None:
|
||||
global _live_snapshot_value, _read_notification_ids
|
||||
_read_notification_ids = _read_notification_ids | {thread_id}
|
||||
if _live_snapshot_value is None:
|
||||
read_ids = set(thread_ids)
|
||||
if not read_ids:
|
||||
return
|
||||
retained_notifications = _live_snapshot_value.get("notifications")
|
||||
if not isinstance(retained_notifications, list):
|
||||
return
|
||||
updated = dict(_live_snapshot_value)
|
||||
updated["notifications"] = [
|
||||
notification
|
||||
for notification in retained_notifications
|
||||
if not isinstance(notification, dict) or notification.get("id") != thread_id
|
||||
]
|
||||
if updated["notifications"] != retained_notifications:
|
||||
_live_section_revisions["notifications"] += 1
|
||||
_live_snapshot_value = updated
|
||||
_read_notification_ids = _read_notification_ids | read_ids
|
||||
if _live_snapshot_value is not None:
|
||||
retained_notifications = _live_snapshot_value.get("notifications")
|
||||
if isinstance(retained_notifications, list):
|
||||
updated = dict(_live_snapshot_value)
|
||||
updated["notifications"] = [
|
||||
notification
|
||||
for notification in retained_notifications
|
||||
if not isinstance(notification, dict)
|
||||
or notification.get("id") not in read_ids
|
||||
]
|
||||
if updated["notifications"] != retained_notifications:
|
||||
_live_section_revisions["notifications"] += 1
|
||||
_live_snapshot_value = updated
|
||||
try:
|
||||
await asyncio.to_thread(_live_snapshot_store.remove_notifications, read_ids)
|
||||
except (OSError, sqlite3.Error):
|
||||
# The upstream mutation already succeeded; keep process-local filtering.
|
||||
pass
|
||||
|
||||
|
||||
def _without_read_notifications(snapshot: dict) -> dict:
|
||||
@@ -1711,8 +1782,7 @@ def _without_read_notifications(snapshot: dict) -> dict:
|
||||
return updated
|
||||
|
||||
|
||||
@app.get("/api/v1/live")
|
||||
async def live_snapshot(
|
||||
async def _live_snapshot_response(
|
||||
context_revision: str | None = Query(
|
||||
default=None, max_length=64, pattern=r"^[0-9a-f]{16}\.[0-9]{1,20}$"
|
||||
),
|
||||
@@ -1730,12 +1800,10 @@ async def live_snapshot(
|
||||
"events": events_revision,
|
||||
"notifications": notifications_revision,
|
||||
}
|
||||
now = time.monotonic()
|
||||
_apply_shared_live_state(await asyncio.to_thread(_live_snapshot_store.load))
|
||||
now = _live_snapshot_clock()
|
||||
due_sections = _due_live_sections(now)
|
||||
if (
|
||||
_live_snapshot_value is not None
|
||||
and not due_sections
|
||||
):
|
||||
if _live_snapshot_value is not None and not due_sections:
|
||||
return JSONResponse(
|
||||
_live_snapshot_payload(
|
||||
_live_snapshot_value,
|
||||
@@ -1747,7 +1815,77 @@ async def live_snapshot(
|
||||
known_revisions=known_revisions,
|
||||
)
|
||||
)
|
||||
task = _start_live_snapshot_refresh(due_sections)
|
||||
if not due_sections:
|
||||
retries = [
|
||||
retry_at - now
|
||||
for retry_at in _live_section_retry_at.values()
|
||||
if retry_at is not None and retry_at > now
|
||||
]
|
||||
return JSONResponse(
|
||||
{"error": "Gitea live snapshot is temporarily unavailable"},
|
||||
status_code=503,
|
||||
headers={"Retry-After": str(max(1, math.ceil(min(retries, default=1.0))))},
|
||||
)
|
||||
|
||||
task = _live_snapshot_task
|
||||
if task is None or task.done():
|
||||
lease_owner = await asyncio.to_thread(
|
||||
_live_snapshot_store.try_acquire_refresh,
|
||||
due_sections,
|
||||
lease_seconds=CONTEXT_TIMEOUT_SECONDS + 1.0,
|
||||
)
|
||||
if lease_owner is not None:
|
||||
latest = await asyncio.to_thread(_live_snapshot_store.load)
|
||||
_apply_shared_live_state(latest)
|
||||
due_sections = _due_live_sections(_live_snapshot_clock())
|
||||
if not due_sections:
|
||||
await asyncio.to_thread(
|
||||
_live_snapshot_store.release_refresh, lease_owner
|
||||
)
|
||||
return JSONResponse(
|
||||
_live_snapshot_payload(
|
||||
_live_snapshot_value,
|
||||
stale=any(
|
||||
state != "fresh"
|
||||
for state in (_live_snapshot_value or {}).get("sections", {}).values()
|
||||
),
|
||||
revalidating=False,
|
||||
known_revisions=known_revisions,
|
||||
)
|
||||
)
|
||||
task = _start_live_snapshot_refresh(due_sections, lease_owner)
|
||||
else:
|
||||
shared = await asyncio.to_thread(_live_snapshot_store.load)
|
||||
_apply_shared_live_state(shared)
|
||||
if _live_snapshot_value is not None:
|
||||
return JSONResponse(
|
||||
_live_snapshot_payload(
|
||||
_live_snapshot_value,
|
||||
stale=bool(_due_live_sections(_live_snapshot_clock())),
|
||||
revalidating=bool(shared.refreshing_sections),
|
||||
known_revisions=known_revisions,
|
||||
)
|
||||
)
|
||||
deadline = time.perf_counter() + CONTEXT_TIMEOUT_SECONDS
|
||||
while time.perf_counter() < deadline:
|
||||
await asyncio.sleep(0.01)
|
||||
shared = await asyncio.to_thread(_live_snapshot_store.load)
|
||||
if shared.value is not None:
|
||||
_apply_shared_live_state(shared)
|
||||
return JSONResponse(
|
||||
_live_snapshot_payload(
|
||||
shared.value,
|
||||
stale=bool(_due_live_sections(_live_snapshot_clock())),
|
||||
revalidating=bool(shared.refreshing_sections),
|
||||
known_revisions=known_revisions,
|
||||
)
|
||||
)
|
||||
return JSONResponse(
|
||||
{"error": f"Gitea live snapshot timed out after {CONTEXT_TIMEOUT_SECONDS:g}s"},
|
||||
status_code=503,
|
||||
headers={"Retry-After": str(max(1, math.ceil(CONTEXT_TIMEOUT_SECONDS)))},
|
||||
)
|
||||
assert task is not None
|
||||
if _live_snapshot_value is not None:
|
||||
return JSONResponse(
|
||||
_live_snapshot_payload(
|
||||
@@ -1780,6 +1918,32 @@ async def live_snapshot(
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/live")
|
||||
async def live_snapshot(
|
||||
context_revision: str | None = Query(
|
||||
default=None, max_length=64, pattern=r"^[0-9a-f]{16}\.[0-9]{1,20}$"
|
||||
),
|
||||
events_revision: str | None = Query(
|
||||
default=None, max_length=64, pattern=r"^[0-9a-f]{16}\.[0-9]{1,20}$"
|
||||
),
|
||||
notifications_revision: str | None = Query(
|
||||
default=None, max_length=64, pattern=r"^[0-9a-f]{16}\.[0-9]{1,20}$"
|
||||
),
|
||||
) -> JSONResponse:
|
||||
try:
|
||||
return await _live_snapshot_response(
|
||||
context_revision=context_revision,
|
||||
events_revision=events_revision,
|
||||
notifications_revision=notifications_revision,
|
||||
)
|
||||
except (OSError, sqlite3.Error):
|
||||
return JSONResponse(
|
||||
{"error": "Gitea live snapshot state is temporarily unavailable"},
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@app.get("/api/v1/events")
|
||||
async def event_stream():
|
||||
@@ -1822,7 +1986,6 @@ async def _mark_notification_read_result(thread_id: int) -> tuple[int, bool]:
|
||||
)
|
||||
except Exception:
|
||||
return thread_id, False
|
||||
_remove_notification_from_live_snapshot(thread_id)
|
||||
return thread_id, True
|
||||
|
||||
|
||||
@@ -1852,6 +2015,9 @@ async def read_notifications(batch: NotificationReadBatch) -> JSONResponse:
|
||||
for thread_id, succeeded in [task.result()]
|
||||
if succeeded
|
||||
}
|
||||
await _remove_notifications_from_live_snapshot(
|
||||
[thread_id for thread_id in thread_ids if thread_id in succeeded_ids]
|
||||
)
|
||||
failed = [thread_id for thread_id in thread_ids if thread_id not in succeeded_ids]
|
||||
return JSONResponse(
|
||||
{
|
||||
@@ -1952,7 +2118,7 @@ async def read_notification(thread_id: int = PathParam(gt=0)) -> JSONResponse:
|
||||
{"error": "The update could not be marked read. Please retry."},
|
||||
status_code=503,
|
||||
)
|
||||
_remove_notification_from_live_snapshot(thread_id)
|
||||
await _remove_notifications_from_live_snapshot([thread_id])
|
||||
return JSONResponse({"id": thread_id, "status": "read"})
|
||||
|
||||
|
||||
|
||||
+14
-4
@@ -1,9 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, Response
|
||||
|
||||
from src.frontend_bundle import build_frontend
|
||||
from src.compression import _quality
|
||||
|
||||
router = APIRouter()
|
||||
DASHBOARD_FILE = Path(__file__).resolve().parent.parent / "frontend" / "index.html"
|
||||
@@ -51,11 +52,20 @@ async def service_worker() -> Response:
|
||||
|
||||
|
||||
@router.get("/runtime-{digest}.js")
|
||||
async def runtime_bundle(digest: str) -> Response:
|
||||
async def runtime_bundle(digest: str, request: Request) -> Response:
|
||||
if digest != FRONTEND_BUILD.runtime_digest:
|
||||
raise HTTPException(status_code=404, detail="Runtime revision not found")
|
||||
accepts_gzip = _quality(request.headers.get("Accept-Encoding", ""), "gzip") > 0
|
||||
return Response(
|
||||
FRONTEND_BUILD.runtime_bytes,
|
||||
(
|
||||
FRONTEND_BUILD.runtime_gzip_bytes
|
||||
if accepts_gzip
|
||||
else FRONTEND_BUILD.runtime_bytes
|
||||
),
|
||||
media_type="application/javascript",
|
||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
||||
headers={
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
"Vary": "Accept-Encoding",
|
||||
**({"Content-Encoding": "gzip"} if accepts_gzip else {}),
|
||||
},
|
||||
)
|
||||
@@ -77,6 +77,85 @@ outbox.flush('timmy').then(result => process.stdout.write(JSON.stringify({{persi
|
||||
assert output["remaining"] == []
|
||||
|
||||
|
||||
def test_authored_outbox_persists_and_delivers_complete_pull_review_payload():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values = new Map(); const calls = [];
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage, getOwnerLogin:()=> 'timmy',
|
||||
fetchJson: async (url, options) => {{ calls.push({{url, options}}); return {{id:44}}; }},
|
||||
}});
|
||||
let queued;
|
||||
try {{
|
||||
queued = outbox.enqueue({{
|
||||
kind:'pull-review', repository:'stackchain/web', number:8, operationId:'review-op',
|
||||
body:'Looks good', decision:'approve', expectedHeadSha:'abc123',
|
||||
comments:[{{path:'app.js',body:'Nice',new_position:4}}],
|
||||
draftKey:'stackchain.review-draft.v1:stackchain/web#8@abc123',
|
||||
progressKey:'stackchain.review-progress.v1:stackchain/web#8@abc123',
|
||||
draftFingerprint:'draft', progressFingerprint:'progress',
|
||||
}});
|
||||
}} catch (error) {{
|
||||
process.stdout.write(JSON.stringify({{error:error.message}}));
|
||||
}}
|
||||
if (queued) {{
|
||||
storage.setItem(queued.draftKey, 'draft'); storage.setItem(queued.progressKey, 'progress');
|
||||
outbox.flush('timmy').then(result => process.stdout.write(JSON.stringify({{
|
||||
queued, calls:calls.map(call=>({{url:call.url,key:call.options.headers['Idempotency-Key'],body:JSON.parse(call.options.body)}})),
|
||||
result, remaining:outbox.list(), draft:storage.getItem(queued.draftKey), progress:storage.getItem(queued.progressKey),
|
||||
}})));
|
||||
}}
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert "error" not in output, output.get("error")
|
||||
|
||||
assert output["queued"]["kind"] == "pull-review"
|
||||
assert output["queued"]["comments"] == [{"path": "app.js", "body": "Nice", "new_position": 4}]
|
||||
assert output["calls"] == [{
|
||||
"url": "api/v1/repos/stackchain/web/pulls/8/review",
|
||||
"key": "review-op",
|
||||
"body": {
|
||||
"body": "Looks good", "decision": "approve", "expected_head_sha": "abc123",
|
||||
"comments": [{"path": "app.js", "body": "Nice", "new_position": 4}],
|
||||
},
|
||||
}]
|
||||
assert output["remaining"] == []
|
||||
assert output["draft"] is None
|
||||
assert output["progress"] is None
|
||||
|
||||
|
||||
def test_authored_outbox_persists_and_delivers_idempotent_issue_closure():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values = new Map(); const calls = [];
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage, getOwnerLogin:()=> 'timmy',
|
||||
fetchJson: async (url, options) => {{ calls.push({{url,options}}); return {{number:27,state:'closed'}}; }},
|
||||
}});
|
||||
const queued = outbox.enqueue({{
|
||||
kind:'issue-close',repository:'stackchain/dashboard',number:27,operationId:'close-op'
|
||||
}});
|
||||
outbox.flush('timmy').then(result => process.stdout.write(JSON.stringify({{
|
||||
queued,calls,result,remaining:outbox.list()
|
||||
}})));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["queued"]["kind"] == "issue-close"
|
||||
assert output["calls"] == [{
|
||||
"url": "api/v1/repos/stackchain/dashboard/issues/27/close",
|
||||
"options": {
|
||||
"method": "PATCH",
|
||||
"headers": {"Accept": "application/json", "Idempotency-Key": "close-op"},
|
||||
},
|
||||
}]
|
||||
assert output["result"]["confirmed"] == [{"number": 27, "state": "closed"}]
|
||||
assert output["remaining"] == []
|
||||
|
||||
|
||||
def test_authored_outbox_classifies_failures_and_continues_past_attention_items():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
@@ -183,6 +262,52 @@ process.stdout.write(JSON.stringify({{first,second,items:outbox.list()}}));
|
||||
assert len(output["items"]) == 1
|
||||
|
||||
|
||||
def test_authored_outbox_deduplicates_pull_review_for_same_head_after_reload():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values=new Map();let sequence=0;
|
||||
const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const make=()=>createAuthoredOutbox({{storage,getOwnerLogin:()=>'timmy',createOperationId:()=> 'op-' + (++sequence)}});
|
||||
const first=make().enqueue({{kind:'pull-review',repository:'o/r',number:7,expectedHeadSha:'abc',decision:'approve',body:'Ready'}});
|
||||
const second=make().enqueue({{kind:'pull-review',repository:'o/r',number:7,expectedHeadSha:'abc',decision:'approve',body:'Ready'}});
|
||||
process.stdout.write(JSON.stringify({{first,second,items:make().list()}}));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["first"] == output["second"]
|
||||
assert len(output["items"]) == 1
|
||||
|
||||
|
||||
def test_authored_outbox_rejects_changed_feedback_while_same_head_is_queued():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values=new Map();const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const outbox=createAuthoredOutbox({{storage,getOwnerLogin:()=>'timmy'}});
|
||||
outbox.enqueue({{kind:'pull-review',repository:'o/r',number:7,expectedHeadSha:'abc',decision:'approve',body:'First'}});
|
||||
let error='';try{{outbox.enqueue({{kind:'pull-review',repository:'o/r',number:7,expectedHeadSha:'abc',decision:'request_changes',body:'Changed'}});}}catch(e){{error=e.message;}}
|
||||
process.stdout.write(JSON.stringify({{error,items:outbox.list()}}));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["error"] == "A review for this saved head is already queued. Open Drafts to inspect or discard it first."
|
||||
assert len(output["items"]) == 1
|
||||
|
||||
|
||||
def test_confirmed_review_keeps_draft_edits_made_after_it_was_queued():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values=new Map();const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
|
||||
const draftKey='draft-key';const progressKey='progress-key';storage.setItem(draftKey,'old-draft');storage.setItem(progressKey,'old-progress');
|
||||
const outbox=createAuthoredOutbox({{storage,getOwnerLogin:()=>'timmy',fetchJson:async()=>({{id:1}})}});
|
||||
outbox.enqueue({{kind:'pull-review',repository:'o/r',number:7,expectedHeadSha:'abc',body:'Queued',draftKey,progressKey,draftFingerprint:'old-draft',progressFingerprint:'old-progress'}});
|
||||
storage.setItem(draftKey,'newer-draft');storage.setItem(progressKey,'newer-progress');
|
||||
outbox.flush('timmy').then(()=>process.stdout.write(JSON.stringify({{draft:storage.getItem(draftKey),progress:storage.getItem(progressKey)}})));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output == {"draft": "newer-draft", "progress": "newer-progress"}
|
||||
|
||||
|
||||
def test_authored_outbox_mirrors_to_background_sync_and_reconciles_worker_results():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
|
||||
@@ -203,6 +203,69 @@ const fetchJson = async (url, options = {{}}) => {{
|
||||
assert output["result"]["confirmed"] == [{"id": 42}]
|
||||
|
||||
|
||||
def test_closed_app_sync_delivers_pull_review_with_stable_identity_and_full_payload():
|
||||
authored = {
|
||||
"id": "review-op", "operationId": "review-op", "ownerLogin": "timmy", "status": "queued",
|
||||
"kind": "pull-review", "repository": "stackchain/web", "number": 8,
|
||||
"body": "Looks good", "decision": "approve", "expectedHeadSha": "abc123",
|
||||
"comments": [{"path": "app.js", "body": "Nice", "new_position": 4}],
|
||||
}
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
let queued = {json.dumps(authored)}; const calls=[];
|
||||
const store = {{
|
||||
claimNext:async owner=>queued?.ownerLogin===owner?(queued=null,{json.dumps(authored)}):null,
|
||||
complete:async()=>{{}},release:async()=>{{}},fail:async()=>{{}},countBlocked:async()=>0,
|
||||
}};
|
||||
const fetchJson=async(url,options={{}})=>{{calls.push({{url,options}});return url==='api/v1/background-identity'?{{login:'timmy'}}:{{id:45}};}};
|
||||
createBackgroundIssueSync({{store,fetchJson}}).flush().then(result=>process.stdout.write(JSON.stringify({{calls,result}})));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
mutation = output["calls"][1]
|
||||
assert mutation["url"] == "api/v1/repos/stackchain/web/pulls/8/review"
|
||||
assert mutation["options"]["headers"]["Idempotency-Key"] == "review-op"
|
||||
assert json.loads(mutation["options"]["body"]) == {
|
||||
"body": "Looks good", "decision": "approve", "expected_head_sha": "abc123",
|
||||
"comments": [{"path": "app.js", "body": "Nice", "new_position": 4}],
|
||||
}
|
||||
assert output["result"]["confirmed"] == [{"id": 45}]
|
||||
assert output["result"]["receipts"] == [{
|
||||
"id": "review-op", "status": "confirmed", "kind": "message",
|
||||
"route": "#/my-work/review/stackchain/web/8",
|
||||
}]
|
||||
|
||||
|
||||
def test_closed_app_sync_delivers_issue_closure_and_returns_actionable_receipt():
|
||||
authored = {
|
||||
"id": "close-op", "operationId": "close-op", "ownerLogin": "timmy", "status": "queued",
|
||||
"kind": "issue-close", "repository": "stackchain/dashboard", "number": 27, "body": "",
|
||||
}
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
let queued = {json.dumps(authored)}; const calls=[];
|
||||
const store = {{
|
||||
claimNext:async owner=>queued?.ownerLogin===owner?(queued=null,{json.dumps(authored)}):null,
|
||||
complete:async()=>{{}},release:async()=>{{}},fail:async()=>{{}},countBlocked:async()=>0,
|
||||
}};
|
||||
const fetchJson=async(url,options={{}})=>{{calls.push({{url,options}});return url==='api/v1/background-identity'?{{login:'timmy'}}:{{number:27,state:'closed'}};}};
|
||||
createBackgroundIssueSync({{store,fetchJson}}).flush().then(result=>process.stdout.write(JSON.stringify({{calls,result}})));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
mutation = output["calls"][1]
|
||||
assert mutation["url"] == "api/v1/repos/stackchain/dashboard/issues/27/close"
|
||||
assert mutation["options"]["method"] == "PATCH"
|
||||
assert mutation["options"]["headers"] == {
|
||||
"Accept": "application/json", "Idempotency-Key": "close-op"
|
||||
}
|
||||
assert output["result"]["confirmed"] == [{"number": 27, "state": "closed"}]
|
||||
assert output["result"]["receipts"] == [{
|
||||
"id": "close-op", "status": "confirmed", "kind": "message",
|
||||
"route": "#/my-work/issue/stackchain/dashboard/27",
|
||||
}]
|
||||
|
||||
|
||||
def test_reconciling_one_outbox_lane_preserves_the_other_lane():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
@@ -778,6 +841,51 @@ const transaction=work=>{{const run=tail.then(()=>work({{
|
||||
assert "error" not in output
|
||||
|
||||
|
||||
def test_resume_after_purge_reopens_background_delivery_with_fresh_identity():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
const state={{closed:0,identityLookups:0,mutations:0,keys:[]}};
|
||||
let queued={{
|
||||
id:'capture-after-login',ownerLogin:'timmy',status:'queued',repository:'stackchain/dashboard',
|
||||
title:'Recovered capture',body:'Evidence',labelIds:[],operationId:'op-after-login',
|
||||
}};
|
||||
const store={{
|
||||
close:async()=>{{state.closed+=1;}},
|
||||
claimBatch:async login=>{{
|
||||
if(queued?.ownerLogin!==login)return [];
|
||||
const claimed=queued;queued=null;return [claimed];
|
||||
}},
|
||||
complete:async()=>{{}},release:async()=>{{}},fail:async()=>{{}},countBlocked:async()=>0,
|
||||
}};
|
||||
const fetchJson=async(url,options={{}})=>{{
|
||||
if(url==='api/v1/background-identity'){{state.identityLookups+=1;return {{login:'timmy'}};}}
|
||||
state.mutations+=1;state.keys.push(options.headers['Idempotency-Key']);
|
||||
return {{repository:'stackchain/dashboard',number:425,title:'Recovered capture'}};
|
||||
}};
|
||||
(async()=>{{
|
||||
const sync=createBackgroundIssueSync({{store,fetchJson}});
|
||||
await sync.purge();
|
||||
const blocked=await sync.flush();
|
||||
await sync.resume();
|
||||
const delivered=await sync.flush();
|
||||
process.stdout.write(JSON.stringify({{state,blocked,delivered}}));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["state"] == {
|
||||
"closed": 1,
|
||||
"identityLookups": 1,
|
||||
"mutations": 1,
|
||||
"keys": ["op-after-login"],
|
||||
}
|
||||
assert output["blocked"]["login"] == ""
|
||||
assert output["delivered"]["login"] == "timmy"
|
||||
assert output["delivered"]["confirmed"] == [
|
||||
{"repository": "stackchain/dashboard", "number": 425, "title": "Recovered capture"}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_background_identity_is_lightweight_and_never_cacheable(monkeypatch):
|
||||
calls = 0
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dashboard_bundle import dashboard
|
||||
|
||||
|
||||
COMMENT_NEXT = Path(__file__).parents[1] / "frontend" / "comment-next.js"
|
||||
MY_WORK = Path(__file__).parents[1] / "frontend" / "my-work.js"
|
||||
|
||||
|
||||
def run_node(script):
|
||||
return subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout
|
||||
|
||||
|
||||
def test_comment_and_next_posts_then_completes_current_today_item_once():
|
||||
script = f"""
|
||||
const createCommentNext = require({json.dumps(str(COMMENT_NEXT))});
|
||||
const calls = [];
|
||||
let finishPost;
|
||||
const controller = createCommentNext({{
|
||||
post: (item, body) => {{ calls.push(`post:${{item.number}}:${{body}}`); return new Promise(resolve => {{ finishPost = resolve; }}); }},
|
||||
queue: () => {{ throw new Error('must not queue'); }},
|
||||
canQueue: () => false,
|
||||
complete: item => {{ calls.push(`complete:${{item.number}}`); return true; }},
|
||||
}});
|
||||
const item = {{kind:'issue', repository:'stackchain/dashboard', number:429}};
|
||||
const first = controller.submit(item, 'Handoff ready');
|
||||
const second = controller.submit(item, 'Handoff ready');
|
||||
if (first !== second) throw new Error('submission was not single-flight');
|
||||
finishPost({{id:7, body:'Handoff ready'}});
|
||||
(async () => {{
|
||||
const result = await first;
|
||||
process.stdout.write(JSON.stringify({{result, calls, busy:controller.busy()}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"result": {
|
||||
"accepted": True,
|
||||
"delivery": "posted",
|
||||
"comment": {"id": 7, "body": "Handoff ready"},
|
||||
"completed": True,
|
||||
},
|
||||
"calls": ["post:429:Handoff ready", "complete:429"],
|
||||
"busy": False,
|
||||
}
|
||||
|
||||
|
||||
def test_comment_and_next_advances_after_durable_offline_admission():
|
||||
script = f"""
|
||||
const createCommentNext = require({json.dumps(str(COMMENT_NEXT))});
|
||||
const calls = [];
|
||||
const retryable = new Error('offline'); retryable.status = 503;
|
||||
const controller = createCommentNext({{
|
||||
post: () => Promise.reject(retryable),
|
||||
canQueue: error => error.status === 503,
|
||||
queue: message => {{ calls.push(message); return Promise.resolve({{durable:true, background:false}}); }},
|
||||
complete: item => {{ calls.push(`complete:${{item.number}}`); return true; }},
|
||||
}});
|
||||
(async () => {{
|
||||
const result = await controller.submit({{kind:'pull', repository:'stackchain/dashboard', number:12}}, 'Please review', 'op-12');
|
||||
process.stdout.write(JSON.stringify({{result, calls}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"result": {
|
||||
"accepted": True,
|
||||
"delivery": "saved",
|
||||
"background": False,
|
||||
"completed": True,
|
||||
},
|
||||
"calls": [
|
||||
{
|
||||
"kind": "pull-comment",
|
||||
"repository": "stackchain/dashboard",
|
||||
"number": 12,
|
||||
"body": "Please review",
|
||||
"operationId": "op-12",
|
||||
},
|
||||
"complete:12",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_comment_and_next_reads_retry_identity_after_the_failed_post():
|
||||
script = f"""
|
||||
const createCommentNext = require({json.dumps(str(COMMENT_NEXT))});
|
||||
let operationId = '';
|
||||
let queued;
|
||||
const controller = createCommentNext({{
|
||||
post: () => {{ operationId = 'post-attempt-id'; return Promise.reject(Object.assign(new Error('timeout'), {{status:503}})); }},
|
||||
canQueue: () => true,
|
||||
queue: message => {{ queued = message; return Promise.resolve({{durable:true}}); }},
|
||||
complete: () => true,
|
||||
}});
|
||||
(async () => {{
|
||||
const result = await controller.submit(
|
||||
{{kind:'issue', repository:'r', number:3}}, 'Status', () => operationId
|
||||
);
|
||||
process.stdout.write(JSON.stringify({{result, queued}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
|
||||
output = json.loads(run_node(script))
|
||||
assert output["result"]["accepted"] is True
|
||||
assert output["result"]["delivery"] == "saved"
|
||||
assert output["queued"]["operationId"] == "post-attempt-id"
|
||||
|
||||
|
||||
def test_comment_and_next_clears_the_completed_draft_before_opening_next_item():
|
||||
script = f"""
|
||||
const createCommentNext = require({json.dumps(str(COMMENT_NEXT))});
|
||||
const calls = [];
|
||||
const controller = createCommentNext({{
|
||||
post: () => Promise.resolve({{id:1}}), queue: () => null, canQueue: () => false,
|
||||
accept: item => calls.push(`clear:${{item.number}}`),
|
||||
complete: item => {{ calls.push(`complete:${{item.number}}`); return true; }},
|
||||
}});
|
||||
(async () => {{
|
||||
await controller.submit({{kind:'issue',repository:'r',number:8}}, 'Done');
|
||||
process.stdout.write(JSON.stringify(calls));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == ["clear:8", "complete:8"]
|
||||
|
||||
|
||||
def test_comment_and_next_keeps_today_position_when_delivery_or_completion_fails():
|
||||
script = f"""
|
||||
const createCommentNext = require({json.dumps(str(COMMENT_NEXT))});
|
||||
const failures = [];
|
||||
const permanent = createCommentNext({{
|
||||
post: () => Promise.reject(Object.assign(new Error('forbidden'), {{status:403}})),
|
||||
canQueue: () => false,
|
||||
queue: () => Promise.resolve({{durable:true}}),
|
||||
complete: () => {{ failures.push('advanced'); return true; }},
|
||||
}});
|
||||
const notDurable = createCommentNext({{
|
||||
post: () => Promise.reject(Object.assign(new Error('offline'), {{status:503}})),
|
||||
canQueue: () => true,
|
||||
queue: () => Promise.resolve({{durable:false, background:false}}),
|
||||
complete: () => {{ failures.push('advanced'); return true; }},
|
||||
}});
|
||||
const cannotComplete = createCommentNext({{
|
||||
post: () => Promise.resolve({{id:9}}), canQueue: () => false, queue: () => null,
|
||||
complete: () => false,
|
||||
}});
|
||||
(async () => {{
|
||||
for (const [name, controller] of [['permanent', permanent], ['notDurable', notDurable]]) {{
|
||||
try {{ await controller.submit({{kind:'issue',repository:'r',number:1}}, 'draft'); }}
|
||||
catch (error) {{ failures.push(`${{name}}:${{error.message}}`); }}
|
||||
}}
|
||||
const partial = await cannotComplete.submit({{kind:'issue',repository:'r',number:1}}, 'draft');
|
||||
process.stdout.write(JSON.stringify({{failures, partial}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"failures": ["permanent:forbidden", "notDurable:Comment was not saved for delivery."],
|
||||
"partial": {
|
||||
"accepted": True,
|
||||
"delivery": "posted",
|
||||
"comment": {"id": 9},
|
||||
"completed": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_today_checkpoint_only_matches_the_current_session_item():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
const items = [
|
||||
{{kind:'issue', repository:'r', number:1}},
|
||||
{{kind:'pull', repository:'r', number:2}},
|
||||
];
|
||||
const session = buildMyWork.createWorkSession({{
|
||||
getItems: () => items, getFilter: () => 'all', checkpointEnabled: () => true,
|
||||
checkpoint: {{save:()=>undefined, clear:()=>undefined, read:()=>null}},
|
||||
onOpen:()=>undefined, onProgress:()=>undefined, onFinish:()=>undefined,
|
||||
}});
|
||||
session.start();
|
||||
process.stdout.write(JSON.stringify({{
|
||||
current: session.checkpointed(items[0]),
|
||||
other: session.checkpointed(items[1]),
|
||||
generic: session.checkpointed(),
|
||||
}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"current": True,
|
||||
"other": False,
|
||||
"generic": True,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_composers_offer_comment_and_next_only_for_today_checkpoint():
|
||||
html = await dashboard()
|
||||
|
||||
assert 'id="send-issue-comment-next"' in html
|
||||
assert 'id="send-pull-comment-next"' in html
|
||||
assert html.count('>Comment & next</button>') == 2
|
||||
assert "setCommentNextVisibility('issue')" in html
|
||||
assert "setCommentNextVisibility('pull')" in html
|
||||
assert '.comment-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr));' in html
|
||||
assert '.comment-actions button { min-height:44px;' in html
|
||||
@@ -121,6 +121,48 @@ process.stdout.write(JSON.stringify(drafts));
|
||||
assert output[1]["label"] == "Queued issue"
|
||||
|
||||
|
||||
def test_draft_inbox_exposes_queued_review_with_review_route_and_actionable_state():
|
||||
script = f"""
|
||||
const createDraftInbox = require({json.dumps(str(DRAFTS))});
|
||||
const values=new Map([['stackchain.authored-outbox.v1',JSON.stringify({{version:2,items:[{{
|
||||
id:'review-1',kind:'pull-review',repository:'stackchain/web',number:8,body:'Looks good',
|
||||
decision:'approve',expectedHeadSha:'abc',comments:[{{path:'app.js',body:'Nice',new_position:4}}],ownerLogin:'timmy',status:'queued',queuedAt:200
|
||||
}}]}})]]);
|
||||
const storage={{get length(){{return values.size}},key:i=>Array.from(values.keys())[i]||null,getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const item=createDraftInbox({{storage,getCurrentLogin:()=>'timmy'}}).list()[0];
|
||||
process.stdout.write(JSON.stringify(item));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["label"] == "Queued review"
|
||||
assert output["outbox_kind"] == "pull-review"
|
||||
assert output["title"] == "stackchain/web#8"
|
||||
assert output["route"] == {"kind": "review", "repository": "stackchain/web", "number": 8}
|
||||
assert output["copy_text"] == "Looks good\n\nInline feedback\napp.js · new line 4: Nice"
|
||||
assert output["quarantined"] is False
|
||||
|
||||
|
||||
def test_draft_inbox_exposes_queued_issue_closure_for_retry_or_discard():
|
||||
script = f"""
|
||||
const createDraftInbox = require({json.dumps(str(DRAFTS))});
|
||||
const values=new Map([['stackchain.authored-outbox.v1',JSON.stringify({{version:2,items:[{{
|
||||
id:'close-1',kind:'issue-close',repository:'stackchain/dashboard',number:27,body:'',
|
||||
ownerLogin:'timmy',status:'attention',error:'Closure rejected',queuedAt:200
|
||||
}}]}})]]);
|
||||
const storage={{get length(){{return values.size}},key:i=>Array.from(values.keys())[i]||null,getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const item=createDraftInbox({{storage,getCurrentLogin:()=>'timmy'}}).list()[0];
|
||||
process.stdout.write(JSON.stringify(item));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["label"] == "Issue closure needs attention"
|
||||
assert output["outbox_kind"] == "issue-close"
|
||||
assert output["title"] == "stackchain/dashboard#27"
|
||||
assert output["preview"] == "Closure rejected"
|
||||
assert output["route"] == {"kind": "issue", "repository": "stackchain/dashboard", "number": 27}
|
||||
assert output["quarantined"] is False
|
||||
|
||||
|
||||
def test_draft_inbox_exposes_created_issue_waiting_for_create_and_start_continuation():
|
||||
script = f"""
|
||||
const createDraftInbox = require({json.dumps(str(DRAFTS))});
|
||||
@@ -197,6 +239,8 @@ async def test_mobile_dashboard_exposes_touch_safe_draft_recovery_lane():
|
||||
assert 'createDraftInbox({ storage: localStorage' in html
|
||||
assert "captureDraft.repository && !issueCaptureRepositories.includes(captureDraft.repository)" in html
|
||||
assert "Verified not posted — retry" in html
|
||||
assert "const closureOutbox = item.outbox_kind === 'issue-close';" in html
|
||||
assert "closureOutbox ? 'Open issue' : 'Open message'" in html
|
||||
assert "payload.detail?.message" in html
|
||||
assert "error.code = payload.detail?.code" in html
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from starlette.requests import Request
|
||||
|
||||
from src import main
|
||||
from src.frontend_bundle import build_frontend
|
||||
@@ -21,6 +22,8 @@ def test_page_runtime_is_one_deterministic_content_addressed_bundle(tmp_path):
|
||||
|
||||
assert first.runtime_name == second.runtime_name
|
||||
assert first.runtime_bytes == second.runtime_bytes
|
||||
assert first.runtime_gzip_bytes == second.runtime_gzip_bytes
|
||||
assert gzip.decompress(first.runtime_gzip_bytes) == first.runtime_bytes
|
||||
assert PAGE_SCRIPT.findall(first.dashboard_html) == []
|
||||
assert first.dashboard_html.count("<script src=") == 1
|
||||
assert f'<script src="{first.runtime_name}"></script>' in first.dashboard_html
|
||||
@@ -52,11 +55,46 @@ async def test_runtime_is_transferred_as_gzip_when_the_client_accepts_it():
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-encoding"] == "gzip"
|
||||
assert response.headers["vary"] == "Accept-Encoding"
|
||||
assert int(response.headers["content-length"]) <= 100 * 1024
|
||||
assert int(response.headers["content-length"]) == len(main.FRONTEND_BUILD.runtime_gzip_bytes)
|
||||
assert response.content == main.FRONTEND_BUILD.runtime_bytes
|
||||
assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_runtime_route_returns_the_precomputed_gzip_representation():
|
||||
build = build_frontend(FRONTEND)
|
||||
request = Request(
|
||||
{"type": "http", "method": "GET", "path": f"/{build.runtime_name}",
|
||||
"headers": [(b"accept-encoding", b"gzip")]}
|
||||
)
|
||||
|
||||
response = await runtime_bundle(build.runtime_digest, request)
|
||||
|
||||
assert response.body == build.runtime_gzip_bytes
|
||||
assert response.headers["content-encoding"] == "gzip"
|
||||
assert response.headers["content-length"] == str(len(build.runtime_gzip_bytes))
|
||||
assert response.headers["vary"] == "Accept-Encoding"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_runtime_requests_bypass_dynamic_gzip_compression(monkeypatch):
|
||||
class UnexpectedDynamicCompression:
|
||||
def __init__(self, *args, **kwargs):
|
||||
raise AssertionError("immutable runtime entered dynamic compression")
|
||||
|
||||
monkeypatch.setattr("src.compression.GZipResponder", UnexpectedDynamicCompression)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get(
|
||||
f"/{main.FRONTEND_BUILD.runtime_name}",
|
||||
headers={"Accept-Encoding": "gzip"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-encoding"] == "gzip"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("accept_encoding", ["identity", "gzip;q=0, identity;q=1"])
|
||||
async def test_runtime_stays_unencoded_when_the_client_declines_gzip(accept_encoding):
|
||||
@@ -108,9 +146,13 @@ def test_offline_shell_precaches_exact_runtime_without_superseded_page_modules()
|
||||
@pytest.mark.anyio
|
||||
async def test_runtime_asset_is_immutable_while_html_and_worker_revalidate():
|
||||
build = build_frontend(FRONTEND)
|
||||
request = Request(
|
||||
{"type": "http", "method": "GET", "path": f"/{build.runtime_name}",
|
||||
"headers": [(b"accept-encoding", b"identity")]}
|
||||
)
|
||||
|
||||
html = await dashboard()
|
||||
bundle = await runtime_bundle(build.runtime_digest)
|
||||
bundle = await runtime_bundle(build.runtime_digest, request)
|
||||
worker = await service_worker()
|
||||
|
||||
assert build.runtime_name in html
|
||||
|
||||
@@ -1543,6 +1543,25 @@ async def test_gitea_issue_detail_returns_normalized_context_and_recent_comments
|
||||
|
||||
async def handler(request):
|
||||
requests.append((request.method, request.url.path, request.url.query.decode()))
|
||||
if request.url.path.endswith("/dependencies"):
|
||||
return httpx.Response(
|
||||
200,
|
||||
json=[
|
||||
{
|
||||
"number": 3,
|
||||
"title": "Restore signing service",
|
||||
"state": "open",
|
||||
"html_url": "https://forge.example/stackchain/platform/issues/3",
|
||||
"repository": {"full_name": "stackchain/platform"},
|
||||
},
|
||||
{
|
||||
"number": 2,
|
||||
"title": "Completed prerequisite",
|
||||
"state": "closed",
|
||||
"repository": {"full_name": "stackchain/platform"},
|
||||
},
|
||||
],
|
||||
)
|
||||
if request.url.path.endswith("/comments"):
|
||||
return httpx.Response(
|
||||
200,
|
||||
@@ -1580,6 +1599,7 @@ async def test_gitea_issue_detail_returns_normalized_context_and_recent_comments
|
||||
assert requests == [
|
||||
("GET", "/api/v1/repos/stackchain/api/issues/7", ""),
|
||||
("GET", "/api/v1/repos/stackchain/api/issues/7/comments", "limit=20&page=1"),
|
||||
("GET", "/api/v1/repos/stackchain/api/issues/7/dependencies", "limit=20"),
|
||||
]
|
||||
assert result == {
|
||||
"repository": "stackchain/api",
|
||||
@@ -1593,6 +1613,16 @@ async def test_gitea_issue_detail_returns_normalized_context_and_recent_comments
|
||||
"url": "https://forge.example/stackchain/api/issues/7",
|
||||
"labels": ["P1"],
|
||||
"assignees": ["timmy"],
|
||||
"dependencies_available": True,
|
||||
"dependencies": [
|
||||
{
|
||||
"repository": "stackchain/platform",
|
||||
"number": 3,
|
||||
"title": "Restore signing service",
|
||||
"state": "open",
|
||||
"url": "https://forge.example/stackchain/platform/issues/3",
|
||||
}
|
||||
],
|
||||
"comments": [
|
||||
{
|
||||
"id": 81,
|
||||
@@ -1619,6 +1649,31 @@ async def test_gitea_issue_detail_returns_normalized_context_and_recent_comments
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_issue_detail_keeps_planning_usable_when_dependencies_are_unavailable():
|
||||
async def handler(request):
|
||||
if request.url.path.endswith("/dependencies"):
|
||||
return httpx.Response(503, json={"message": "upstream timeout"})
|
||||
if request.url.path.endswith("/comments"):
|
||||
return httpx.Response(200, json=[])
|
||||
return httpx.Response(200, json={
|
||||
"number": 7,
|
||||
"title": "Fix mobile flow",
|
||||
"state": "open",
|
||||
"assignees": [{"login": "timmy"}],
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.issue_detail("stackchain/api", 7)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert result["title"] == "Fix mobile flow"
|
||||
assert result["dependencies_available"] is False
|
||||
assert result["dependencies"] == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_conversation_page_opens_newest_page_and_reports_older_history():
|
||||
requests = []
|
||||
|
||||
@@ -347,5 +347,5 @@ async def test_dashboard_syncs_every_later_change_and_exposes_account_status():
|
||||
def test_later_sync_ships_atomically_in_the_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/later-sync.js'" in source
|
||||
+151
-19
@@ -1,14 +1,21 @@
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from src import main
|
||||
from src.live_snapshot_store import LiveSnapshotStore
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_live_snapshot_task():
|
||||
def reset_live_snapshot_task(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
main,
|
||||
"_live_snapshot_store",
|
||||
LiveSnapshotStore(tmp_path / "live.sqlite3", clock=lambda: main._live_snapshot_clock()),
|
||||
)
|
||||
main._live_snapshot_task = None
|
||||
main._live_snapshot_value = None
|
||||
main._live_snapshot_created_at = None
|
||||
@@ -131,7 +138,7 @@ async def test_live_snapshot_omits_section_bodies_at_known_revisions(monkeypatch
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_live_snapshot_token_from_another_worker_never_suppresses_content(monkeypatch):
|
||||
async def test_live_snapshot_token_from_another_worker_never_suppresses_content(monkeypatch, tmp_path):
|
||||
async def user():
|
||||
return {"id": 1, "login": "timmy"}
|
||||
|
||||
@@ -144,8 +151,6 @@ async def test_live_snapshot_token_from_another_worker_never_suppresses_content(
|
||||
monkeypatch.setattr(main, "pull_requests", empty)
|
||||
monkeypatch.setattr(main, "activity_events", lambda _user: empty())
|
||||
monkeypatch.setattr(main, "notifications", empty)
|
||||
monkeypatch.setattr(main, "_live_revision_generation", "worker-a")
|
||||
|
||||
worker_a = payload(await main.live_snapshot())
|
||||
worker_a_token = worker_a["revisions"]["context"]
|
||||
|
||||
@@ -157,12 +162,15 @@ async def test_live_snapshot_token_from_another_worker_never_suppresses_content(
|
||||
main._live_section_revisions = {
|
||||
section: 0 for section in main.LIVE_SNAPSHOT_SECTIONS
|
||||
}
|
||||
monkeypatch.setattr(main, "_live_revision_generation", "worker-b")
|
||||
main._live_snapshot_store = LiveSnapshotStore(
|
||||
tmp_path / "other-worker.sqlite3", clock=lambda: main._live_snapshot_clock()
|
||||
)
|
||||
|
||||
worker_b = payload(await main.live_snapshot(context_revision=worker_a_token))
|
||||
|
||||
assert worker_a_token == "worker-a.1"
|
||||
assert worker_b["revisions"]["context"] == "worker-b.1"
|
||||
assert worker_a_token.endswith(".1")
|
||||
assert worker_b["revisions"]["context"].endswith(".1")
|
||||
assert worker_b["revisions"]["context"] != worker_a_token
|
||||
assert worker_b["context"]["user"]["login"] == "timmy"
|
||||
|
||||
|
||||
@@ -302,7 +310,10 @@ async def test_live_snapshot_reuses_completed_snapshot_inside_freshness_window(m
|
||||
first = asyncio.create_task(main.live_snapshot())
|
||||
await asyncio.sleep(0)
|
||||
second = asyncio.create_task(main.live_snapshot())
|
||||
await asyncio.sleep(0)
|
||||
for _ in range(100):
|
||||
if user_calls:
|
||||
break
|
||||
await asyncio.to_thread(lambda: None)
|
||||
assert user_calls == 1
|
||||
|
||||
release.set()
|
||||
@@ -332,7 +343,7 @@ async def test_stale_snapshot_returns_immediately_while_one_refresh_revalidates(
|
||||
"sections": {},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.time, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: now)
|
||||
monkeypatch.setattr(main, "_build_live_snapshot", snapshot)
|
||||
|
||||
first = payload(await main.live_snapshot())
|
||||
@@ -373,13 +384,14 @@ async def test_failed_revalidation_enters_cooldown_and_keeps_last_snapshot(monke
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.time, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: now)
|
||||
monkeypatch.setattr(main, "_build_live_snapshot", snapshot)
|
||||
|
||||
await main.live_snapshot()
|
||||
now += main.LIVE_SNAPSHOT_FRESHNESS_SECONDS + 1
|
||||
stale = payload(await main.live_snapshot())
|
||||
await asyncio.sleep(0)
|
||||
assert main._live_snapshot_task is not None
|
||||
await asyncio.gather(main._live_snapshot_task, return_exceptions=True)
|
||||
degraded = payload(await main.live_snapshot())
|
||||
|
||||
assert stale["freshness"]["revalidating"] is True
|
||||
@@ -421,13 +433,14 @@ async def test_partial_refresh_updates_fresh_sections_and_retains_failed_section
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.time, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: now)
|
||||
monkeypatch.setattr(main, "_build_live_snapshot", snapshot)
|
||||
|
||||
await main.live_snapshot()
|
||||
now += main.LIVE_SNAPSHOT_FRESHNESS_SECONDS + 1
|
||||
await main.live_snapshot()
|
||||
await asyncio.sleep(0)
|
||||
assert main._live_snapshot_task is not None
|
||||
await main._live_snapshot_task
|
||||
result = payload(await main.live_snapshot())
|
||||
|
||||
assert result["context"] == {"generation": 2}
|
||||
@@ -470,7 +483,7 @@ async def test_notification_cooldown_does_not_stop_due_work_and_activity_refresh
|
||||
raise ConnectionError("notifications unavailable")
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(main.time, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: now)
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "repos", work)
|
||||
monkeypatch.setattr(main, "issues", empty_work)
|
||||
@@ -537,20 +550,19 @@ async def test_retry_window_starts_one_refresh_and_success_clears_degraded_state
|
||||
"sections": {"context": "fresh", "events": "fresh", "notifications": "fresh"},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.time, "monotonic", lambda: now)
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: now)
|
||||
monkeypatch.setattr(main, "_build_live_snapshot", snapshot)
|
||||
|
||||
await main.live_snapshot()
|
||||
now += main.LIVE_SNAPSHOT_FRESHNESS_SECONDS + 1
|
||||
await main.live_snapshot()
|
||||
await asyncio.sleep(0)
|
||||
assert main._live_snapshot_task is not None
|
||||
await main._live_snapshot_task
|
||||
now += main.LIVE_SNAPSHOT_RETRY_BASE_SECONDS
|
||||
|
||||
first = asyncio.create_task(main.live_snapshot())
|
||||
second = asyncio.create_task(main.live_snapshot())
|
||||
await asyncio.sleep(0)
|
||||
await asyncio.sleep(0)
|
||||
assert retry_started.is_set()
|
||||
await asyncio.wait_for(retry_started.wait(), timeout=1.0)
|
||||
assert builds == 3
|
||||
assert payload(await first)["freshness"]["revalidating"] is True
|
||||
assert payload(await second)["freshness"]["revalidating"] is True
|
||||
@@ -640,3 +652,123 @@ async def test_shared_snapshot_deadline_cancels_upstream_work_for_all_waiters(mo
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_cold_refresh_cooldown_remains_a_retryable_503(monkeypatch):
|
||||
now = 100.0
|
||||
|
||||
async def unavailable(_sections=None):
|
||||
raise ConnectionError("private upstream failure")
|
||||
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: now)
|
||||
monkeypatch.setattr(main, "_build_live_snapshot", unavailable)
|
||||
|
||||
first = await main.live_snapshot()
|
||||
second = await main.live_snapshot()
|
||||
|
||||
assert first.status_code == 503
|
||||
assert second.status_code == 503
|
||||
assert payload(second) == {
|
||||
"error": "Gitea live snapshot is temporarily unavailable"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_cancelled_refresh_releases_shared_lease(monkeypatch):
|
||||
started = asyncio.Event()
|
||||
|
||||
async def blocked(_sections=None):
|
||||
started.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
monkeypatch.setattr(main, "_build_live_snapshot", blocked)
|
||||
request = asyncio.create_task(main.live_snapshot())
|
||||
await started.wait()
|
||||
assert main._live_snapshot_task is not None
|
||||
|
||||
main._live_snapshot_task.cancel()
|
||||
await asyncio.gather(request, main._live_snapshot_task, return_exceptions=True)
|
||||
|
||||
replacement = main._live_snapshot_store.try_acquire_refresh(
|
||||
{"context"}, lease_seconds=1
|
||||
)
|
||||
assert replacement is not None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_shared_store_outage_returns_retryable_503(monkeypatch):
|
||||
def unavailable():
|
||||
raise sqlite3.OperationalError("private database detail")
|
||||
|
||||
monkeypatch.setattr(main._live_snapshot_store, "load", unavailable)
|
||||
|
||||
response = await main.live_snapshot()
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.headers["retry-after"] == "1"
|
||||
assert payload(response) == {
|
||||
"error": "Gitea live snapshot state is temporarily unavailable"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_independent_workers_reuse_shared_live_snapshot(monkeypatch, tmp_path):
|
||||
calls = 0
|
||||
|
||||
async def user():
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return {"id": 1, "login": "timmy"}
|
||||
|
||||
async def empty():
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "repos", empty)
|
||||
monkeypatch.setattr(main, "issues", empty)
|
||||
monkeypatch.setattr(main, "pull_requests", empty)
|
||||
monkeypatch.setattr(main, "activity_events", lambda _user: empty())
|
||||
monkeypatch.setattr(main, "notifications", empty)
|
||||
path = tmp_path / "worker-shared.sqlite3"
|
||||
monkeypatch.setattr(main, "_live_snapshot_store", LiveSnapshotStore(path, clock=lambda: 100.0))
|
||||
|
||||
first = payload(await main.live_snapshot())
|
||||
main._live_snapshot_value = None
|
||||
main._live_snapshot_created_at = None
|
||||
main._live_section_created_at = {section: None for section in main.LIVE_SNAPSHOT_SECTIONS}
|
||||
main._live_snapshot_store = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
second = payload(await main.live_snapshot())
|
||||
|
||||
assert calls == 1
|
||||
assert second["context"] == first["context"]
|
||||
assert second["revisions"] == first["revisions"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_live_snapshot_persists_reboot_stable_wall_timestamps(monkeypatch, tmp_path):
|
||||
epoch = 1_700_000_000.0
|
||||
|
||||
async def user():
|
||||
return {"id": 1, "login": "timmy"}
|
||||
|
||||
async def empty():
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(main, "_live_snapshot_clock", lambda: epoch, raising=False)
|
||||
monkeypatch.setattr(
|
||||
main,
|
||||
"_live_snapshot_store",
|
||||
LiveSnapshotStore(tmp_path / "wall.sqlite3", clock=lambda: main._live_snapshot_clock()),
|
||||
)
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "repos", empty)
|
||||
monkeypatch.setattr(main, "issues", empty)
|
||||
monkeypatch.setattr(main, "pull_requests", empty)
|
||||
monkeypatch.setattr(main, "activity_events", lambda _user: empty())
|
||||
monkeypatch.setattr(main, "notifications", empty)
|
||||
|
||||
response = await main.live_snapshot()
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(main._live_snapshot_store.load().created_at.values()) == {epoch}
|
||||
@@ -0,0 +1,157 @@
|
||||
import threading
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from src import live_snapshot_store
|
||||
from src.live_snapshot_store import LiveSnapshotStore, RefreshLeaseLost
|
||||
|
||||
|
||||
def test_independent_stores_racing_for_refresh_have_one_lease_winner(tmp_path):
|
||||
path = tmp_path / "live.sqlite3"
|
||||
first = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
second = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
barrier = threading.Barrier(2)
|
||||
results = []
|
||||
|
||||
def acquire(store):
|
||||
barrier.wait()
|
||||
results.append(store.try_acquire_refresh({"context", "events"}, lease_seconds=5))
|
||||
|
||||
threads = [threading.Thread(target=acquire, args=(store,)) for store in (first, second)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
assert sum(result is not None for result in results) == 1
|
||||
|
||||
|
||||
def test_snapshot_and_shared_revisions_publish_atomically(tmp_path):
|
||||
path = tmp_path / "live.sqlite3"
|
||||
writer = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
reader = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
lease = writer.try_acquire_refresh(set(("context", "events", "notifications")), lease_seconds=5)
|
||||
assert lease is not None
|
||||
|
||||
state = writer.publish_refresh(
|
||||
lease,
|
||||
value={
|
||||
"context": {"generation": 1},
|
||||
"events": [],
|
||||
"notifications": [],
|
||||
"sections": {section: "fresh" for section in ("context", "events", "notifications")},
|
||||
},
|
||||
created_at={section: 100.0 for section in ("context", "events", "notifications")},
|
||||
failure_count={section: 0 for section in ("context", "events", "notifications")},
|
||||
retry_at={section: None for section in ("context", "events", "notifications")},
|
||||
changed_sections=set(("context", "events", "notifications")),
|
||||
)
|
||||
|
||||
observed = reader.load()
|
||||
assert observed.value == state.value
|
||||
assert observed.revisions == {"context": 1, "events": 1, "notifications": 1}
|
||||
assert observed.refreshing_sections == set()
|
||||
with pytest.raises(RefreshLeaseLost):
|
||||
writer.publish_refresh(
|
||||
lease,
|
||||
value={"context": {"generation": 2}},
|
||||
created_at=observed.created_at,
|
||||
failure_count=observed.failure_count,
|
||||
retry_at=observed.retry_at,
|
||||
changed_sections={"context"},
|
||||
)
|
||||
|
||||
|
||||
def test_expired_refresh_lease_can_be_recovered(tmp_path):
|
||||
now = 100.0
|
||||
path = tmp_path / "live.sqlite3"
|
||||
abandoned = LiveSnapshotStore(path, clock=lambda: now)
|
||||
recovery = LiveSnapshotStore(path, clock=lambda: now)
|
||||
|
||||
first = abandoned.try_acquire_refresh({"context"}, lease_seconds=5)
|
||||
assert first is not None
|
||||
assert recovery.try_acquire_refresh({"context"}, lease_seconds=5) is None
|
||||
now = 106.0
|
||||
second = recovery.try_acquire_refresh({"context"}, lease_seconds=5)
|
||||
|
||||
assert second is not None
|
||||
assert second != first
|
||||
|
||||
|
||||
def test_default_store_clock_uses_reboot_stable_wall_time(tmp_path, monkeypatch):
|
||||
epoch = 1_700_000_000.0
|
||||
monkeypatch.setattr(live_snapshot_store.time, "time", lambda: epoch)
|
||||
store = LiveSnapshotStore(tmp_path / "live.sqlite3")
|
||||
|
||||
lease = store.try_acquire_refresh({"context"}, lease_seconds=5)
|
||||
|
||||
assert lease is not None
|
||||
assert store.load().lease_expires_at == epoch + 5
|
||||
|
||||
|
||||
def test_store_is_private_and_does_not_persist_upstream_token(tmp_path, monkeypatch):
|
||||
token = "gitea-super-secret-token-material"
|
||||
monkeypatch.setenv("GITEA_TOKEN", token)
|
||||
path = tmp_path / "private-state" / "live.sqlite3"
|
||||
|
||||
LiveSnapshotStore(path)
|
||||
|
||||
assert os.stat(path).st_mode & 0o777 == 0o600
|
||||
assert os.stat(path.parent).st_mode & 0o777 == 0o700
|
||||
assert token.encode() not in path.read_bytes()
|
||||
|
||||
|
||||
def test_remove_notifications_filters_batch_with_one_revision_advance(tmp_path):
|
||||
store = LiveSnapshotStore(tmp_path / "live.sqlite3", clock=lambda: 100.0)
|
||||
lease = store.try_acquire_refresh({"notifications"}, lease_seconds=5)
|
||||
assert lease is not None
|
||||
metadata = {section: None for section in ("context", "events", "notifications")}
|
||||
published = store.publish_refresh(
|
||||
lease,
|
||||
value={
|
||||
"notifications": [{"id": 7}, {"id": 8}, {"id": 9}],
|
||||
"sections": {"notifications": "fresh"},
|
||||
},
|
||||
created_at=metadata,
|
||||
failure_count={section: 0 for section in metadata},
|
||||
retry_at=metadata,
|
||||
changed_sections={"notifications"},
|
||||
)
|
||||
|
||||
removed = store.remove_notifications([7, 9, 7])
|
||||
|
||||
assert removed.value["notifications"] == [{"id": 8}]
|
||||
assert removed.revisions["notifications"] == published.revisions["notifications"] + 1
|
||||
|
||||
|
||||
def test_read_notification_filter_is_shared_with_future_publications(tmp_path):
|
||||
path = tmp_path / "live.sqlite3"
|
||||
first = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
second = LiveSnapshotStore(path, clock=lambda: 100.0)
|
||||
lease = first.try_acquire_refresh({"notifications"}, lease_seconds=5)
|
||||
assert lease is not None
|
||||
metadata = {section: None for section in ("context", "events", "notifications")}
|
||||
first.publish_refresh(
|
||||
lease,
|
||||
value={"notifications": [{"id": 7}, {"id": 8}], "sections": {"notifications": "fresh"}},
|
||||
created_at=metadata,
|
||||
failure_count={section: 0 for section in metadata},
|
||||
retry_at=metadata,
|
||||
changed_sections={"notifications"},
|
||||
)
|
||||
|
||||
removed = second.remove_notification(7)
|
||||
lease = first.try_acquire_refresh({"notifications"}, lease_seconds=5)
|
||||
assert lease is not None
|
||||
republished = first.publish_refresh(
|
||||
lease,
|
||||
value={"notifications": [{"id": 7}, {"id": 8}], "sections": {"notifications": "fresh"}},
|
||||
created_at=metadata,
|
||||
failure_count={section: 0 for section in metadata},
|
||||
retry_at=metadata,
|
||||
changed_sections={"notifications"},
|
||||
)
|
||||
|
||||
assert removed.value["notifications"] == [{"id": 8}]
|
||||
assert republished.value["notifications"] == [{"id": 8}]
|
||||
@@ -137,4 +137,4 @@ def test_markdown_work_bodies_are_mobile_safe_block_containers():
|
||||
assert ".markdown-content { min-width:0; max-width:100%; overflow-wrap:anywhere;" in css
|
||||
assert ".markdown-content pre { max-width:100%; overflow-x:auto;" in css
|
||||
assert ".markdown-content a { min-height:44px;" in css
|
||||
assert "stackchain-dashboard-shell-v67" in worker
|
||||
assert "stackchain-dashboard-shell-v73" in worker
|
||||
@@ -35,4 +35,4 @@ def test_offline_shell_contains_every_local_dashboard_runtime_asset():
|
||||
shell_assets = set(re.findall(r"BASE \+ '([^']+)'", worker.split("async function sessionCsrf", 1)[0]))
|
||||
|
||||
assert local_assets <= shell_assets, f"Offline shell is missing: {sorted(local_assets - shell_assets)}"
|
||||
assert "stackchain-dashboard-shell-v67" in worker
|
||||
assert "stackchain-dashboard-shell-v73" in worker
|
||||
@@ -180,7 +180,8 @@ async def test_dashboard_wires_mobile_work_dock_into_today_session_lifecycle():
|
||||
assert "startToday: startTodaySession" in html
|
||||
assert "work: () => mobileWorkEntry.open()" in html
|
||||
assert "mobileTaskDock.updateWork(mobileWorkEntry.mode(), countMyWork(activeMyWork).attention)" in html
|
||||
assert "workSession.reopen()" in html
|
||||
assert "workSession.reopen(item)" in html
|
||||
assert "runTodayTransition('continue')" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
+23
-10
@@ -1648,7 +1648,8 @@ async def test_dashboard_offers_account_safe_resume_and_end_today_controls():
|
||||
assert 'checkpointEnabled: () => selectedWorkFilter === \'today\'' in html
|
||||
assert "qs('#resume-today-session').addEventListener('click'" in html
|
||||
assert "qs('#end-today-session').addEventListener('click'" in html
|
||||
assert "workSession.resume()" in html
|
||||
assert "workSession.resume(item)" in html
|
||||
assert "runTodayTransition('resume')" in html
|
||||
assert "workSession.end()" in html
|
||||
assert '.resume-today-session, .end-today-session { min-height:44px;' in html
|
||||
|
||||
@@ -1662,7 +1663,7 @@ async def test_dashboard_wires_work_session_to_existing_sheet_flows_and_completi
|
||||
assert "qs('#start-work-session').addEventListener('click'" in html
|
||||
assert "document.querySelectorAll('[data-work-session-previous]')" in html
|
||||
assert "document.querySelectorAll('[data-work-session-next]')" in html
|
||||
assert 'workSession.complete();' in html
|
||||
assert "runTodayTransition('complete')" in html
|
||||
assert 'workSession.reconcile();' in html
|
||||
for opener in ('openIssueSheet(item', 'openPullSheet(item', 'openReviewSheet(item', 'notificationReader.open(item'):
|
||||
assert opener in html
|
||||
@@ -1672,17 +1673,18 @@ async def test_dashboard_wires_work_session_to_existing_sheet_flows_and_completi
|
||||
async def test_closing_issue_advances_active_session_once_and_exposes_close_and_next():
|
||||
html = await dashboard()
|
||||
|
||||
assert "qs('#close-issue').textContent = workSession.active() ? 'Close & next' : 'Close issue';" in html
|
||||
assert "workSession.active() ? 'Close & next' : 'Close issue'" in html
|
||||
assert "workSession.active() ? 'Queue close & next' : 'Queue issue closure'" in html
|
||||
close_handler = html.split("qs('#close-issue').addEventListener('click'", 1)[1].split(
|
||||
"qs('#close-pull-sheet').addEventListener", 1
|
||||
)[0]
|
||||
assert "refreshMyWorkView({ reconcileSession:false });" in close_handler
|
||||
assert "if (workSession.active()) workSession.complete();" in close_handler
|
||||
assert "workSession.active() ? await runTodayTransition('complete') : null" in close_handler
|
||||
assert close_handler.index("await issueController.close(selectedIssue)") < close_handler.index(
|
||||
"if (workSession.active()) workSession.complete();"
|
||||
"await runTodayTransition('complete')"
|
||||
)
|
||||
assert close_handler.index("lastMyWork = lastMyWork.filter") < close_handler.index(
|
||||
"if (workSession.active()) workSession.complete();"
|
||||
"await runTodayTransition('complete')"
|
||||
)
|
||||
|
||||
|
||||
@@ -1696,13 +1698,13 @@ async def test_merging_pull_advances_active_session_once_and_exposes_merge_and_n
|
||||
)[0]
|
||||
assert "refreshMyWorkView({ reconcileSession:false });" in merge_handler
|
||||
assert "const continuingSession = workSession.active();" in merge_handler
|
||||
assert "if (workSession.active()) workSession.complete();" in merge_handler
|
||||
assert "workSession.active() ? await runTodayTransition('complete') : null" in merge_handler
|
||||
assert "merged. Next work item opened." in merge_handler
|
||||
assert merge_handler.index("await pullController.merge") < merge_handler.index(
|
||||
"if (workSession.active()) workSession.complete();"
|
||||
"await runTodayTransition('complete')"
|
||||
)
|
||||
assert merge_handler.index("lastMyWork = lastMyWork.filter") < merge_handler.index(
|
||||
"if (workSession.active()) workSession.complete();"
|
||||
"await runTodayTransition('complete')"
|
||||
)
|
||||
|
||||
|
||||
@@ -1729,7 +1731,7 @@ async def test_failed_pull_merge_does_not_remove_or_advance_the_session():
|
||||
success_path, failure_path = merge_handler.split("} catch (error) {", 1)
|
||||
|
||||
assert "lastMyWork = lastMyWork.filter" in success_path
|
||||
assert "workSession.complete()" in success_path
|
||||
assert "runTodayTransition('complete')" in success_path
|
||||
assert "lastMyWork = lastMyWork.filter" not in failure_path
|
||||
assert "workSession.complete()" not in failure_path
|
||||
assert "The pull request remains in My Work; refresh and retry." in failure_path
|
||||
@@ -4205,6 +4207,17 @@ async def test_review_requests_open_an_accessible_mobile_detail_sheet():
|
||||
assert '.review-diff' in html and 'overflow-x:auto' in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_review_attention_drafts_require_revision_instead_of_resending_stale_payload():
|
||||
html = await dashboard()
|
||||
|
||||
assert "const reviewOutbox = item.outbox_kind === 'pull-review';" in html
|
||||
assert "reviewOutbox && item.status === 'attention'" in html
|
||||
assert ">Open current review</button>" in html
|
||||
assert ">Copy feedback</button>" in html
|
||||
assert "item.kind === 'authored-outbox' && !reviewOutbox" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_review_sheet_loads_details_and_preserves_safe_gitea_handoff():
|
||||
html = await dashboard()
|
||||
|
||||
@@ -5,6 +5,17 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from src import gitea_proxy, main
|
||||
from src.live_snapshot_store import LiveSnapshotStore
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_live_snapshot_store(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
main,
|
||||
"_live_snapshot_store",
|
||||
LiveSnapshotStore(tmp_path / "live.sqlite3", clock=lambda: main._live_snapshot_clock()),
|
||||
)
|
||||
monkeypatch.setattr(main, "_read_notification_ids", set())
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -50,6 +61,37 @@ async def test_mark_notification_read_api_is_bounded_and_never_cacheable(monkeyp
|
||||
assert marked == [42]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_snapshot_maintenance_does_not_block_the_event_loop(monkeypatch):
|
||||
async def mark(_thread_id):
|
||||
return None
|
||||
|
||||
calls = []
|
||||
|
||||
class BlockingStore:
|
||||
def remove_notification(self, thread_id):
|
||||
calls.append([thread_id])
|
||||
time.sleep(0.08)
|
||||
|
||||
def remove_notifications(self, thread_ids):
|
||||
calls.append(list(thread_ids))
|
||||
time.sleep(0.08)
|
||||
|
||||
monkeypatch.setattr(main, "mark_notification_read", mark)
|
||||
monkeypatch.setattr(main, "_live_snapshot_store", BlockingStore())
|
||||
monkeypatch.setattr(main, "_live_snapshot_value", None)
|
||||
started_at = asyncio.get_running_loop().time()
|
||||
|
||||
request = asyncio.create_task(main.read_notification(42))
|
||||
await asyncio.sleep(0.01)
|
||||
heartbeat_delay = asyncio.get_running_loop().time() - started_at
|
||||
response = await request
|
||||
|
||||
assert heartbeat_delay < 0.05
|
||||
assert response.status_code == 200
|
||||
assert calls == [[42]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_bulk_mark_read_reports_partial_progress_and_retains_only_failures(monkeypatch):
|
||||
calls = []
|
||||
@@ -78,6 +120,33 @@ async def test_bulk_mark_read_reports_partial_progress_and_retains_only_failures
|
||||
assert main._live_snapshot_value == {"notifications": [{"id": 43}]}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_bulk_mark_read_updates_shared_snapshot_once_for_successes(monkeypatch):
|
||||
async def mark(thread_id):
|
||||
if thread_id == 43:
|
||||
raise httpx.HTTPError("upstream unavailable")
|
||||
|
||||
calls = []
|
||||
|
||||
class RecordingStore:
|
||||
def remove_notifications(self, thread_ids):
|
||||
calls.append(tuple(sorted(thread_ids)))
|
||||
|
||||
monkeypatch.setattr(main, "mark_notification_read", mark)
|
||||
monkeypatch.setattr(main, "_live_snapshot_store", RecordingStore())
|
||||
monkeypatch.setattr(
|
||||
main,
|
||||
"_live_snapshot_value",
|
||||
{"notifications": [{"id": 42}, {"id": 43}, {"id": 44}]},
|
||||
)
|
||||
|
||||
response = await main.read_notifications(main.NotificationReadBatch(ids=[42, 43, 44]))
|
||||
|
||||
assert response.status_code == 200
|
||||
assert calls == [(42, 44)]
|
||||
assert main._live_snapshot_value == {"notifications": [{"id": 43}]}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_bulk_mark_read_limits_upstream_concurrency(monkeypatch):
|
||||
active = 0
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
OFFLINE_CLOSE = Path(__file__).parents[1] / "frontend" / "offline-issue-close.js"
|
||||
|
||||
|
||||
def run_node(script: str):
|
||||
result = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def test_offline_issue_close_waits_for_durable_admission_before_advancing_today():
|
||||
script = f"""
|
||||
const createOfflineIssueClose = require({json.dumps(str(OFFLINE_CLOSE))});
|
||||
const events=[]; let release;
|
||||
const gate=new Promise(resolve=>release=resolve);
|
||||
const close=createOfflineIssueClose({{
|
||||
enqueueDurably:async message=>{{events.push('admit');await gate;events.push('durable');return {{item:message,background:true}};}},
|
||||
completeToday:item=>{{events.push('complete:' + item.number);return true;}},
|
||||
}});
|
||||
const item={{kind:'issue',repository:'stackchain/dashboard',number:27}};
|
||||
const pending=close(item).then(result=>{{events.push('resolved');return result;}});
|
||||
Promise.resolve().then(async()=>{{
|
||||
const before=events.slice();release();const result=await pending;
|
||||
process.stdout.write(JSON.stringify({{before,events,result}}));
|
||||
}});
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["before"] == ["admit"]
|
||||
assert output["events"] == ["admit", "durable", "complete:27", "resolved"]
|
||||
assert output["result"]["advanced"] is True
|
||||
assert output["result"]["admission"]["background"] is True
|
||||
@@ -264,7 +264,7 @@ async def test_saved_unread_update_opens_offline_with_queued_reply_and_read_cont
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_saved_requested_review_opens_offline_for_sha_scoped_drafting_only():
|
||||
async def test_saved_requested_review_queues_complete_sha_scoped_feedback_offline():
|
||||
html = await dashboard()
|
||||
|
||||
assert "item.is_review ? reviewController.load(item)" in html
|
||||
@@ -272,6 +272,51 @@ async def test_saved_requested_review_opens_offline_for_sha_scoped_drafting_only
|
||||
assert "async function openReviewSheet(item, trigger, cachedDetail = null)" in html
|
||||
assert "cachedDetail || await reviewController.load(selectedReview)" in html
|
||||
assert "Offline review · saved " in html
|
||||
assert "Reconnect to validate & submit" in html
|
||||
assert "qs('#submit-review').disabled = offlineReview;" in html
|
||||
assert "Queue review for reconnect" in html
|
||||
assert "kind: 'pull-review'" in html
|
||||
assert "await authoredOutbox.enqueueDurably" in html
|
||||
assert "expectedHeadSha: selectedReviewHead" in html
|
||||
assert "comments: snapshot.comments" in html
|
||||
assert "draftKey: draft.storageKey" in html
|
||||
assert "progressKey: progress?.storageKey" in html
|
||||
assert "draftFingerprint: localStorage.getItem(draft.storageKey) || ''" in html
|
||||
assert "progressFingerprint: localStorage.getItem(progress?.storageKey) || ''" in html
|
||||
assert "Review queued · it will submit after reconnect." in html
|
||||
assert "if (selectedReview && offlineReview) openReviewSheet(selectedReview, reviewTrigger);" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_offline_today_review_queues_durably_before_completing_and_advancing():
|
||||
html = await dashboard()
|
||||
|
||||
assert "function reviewingActiveTodayItem()" in html
|
||||
assert "offlineReview && reviewingActiveTodayItem() ? 'Queue review & next'" in html
|
||||
handler = html.split("qs('#submit-review').addEventListener('click'", 1)[1].split(
|
||||
"qs('#continue-review-to-merge').addEventListener", 1
|
||||
)[0]
|
||||
admission = handler.index("await authoredOutbox.enqueueDurably")
|
||||
completion = handler.index("completeTodayItem(selectedReview")
|
||||
assert admission < completion
|
||||
assert "successMessage: 'Review queued. Next Today item opened.'" in handler
|
||||
assert "failureMessage: 'Review queued, but Today still needs completion.'" in handler
|
||||
assert "if (!advanced)" in handler
|
||||
assert "Review queued, but Today still needs completion." in handler
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_offline_today_issue_queues_closure_before_completing_and_advancing():
|
||||
html = await dashboard()
|
||||
|
||||
assert '<script src="static/offline-issue-close.js"></script>' in html
|
||||
assert "const closeOfflineIssue = createOfflineIssueClose({" in html
|
||||
assert "enqueueDurably: message => authoredOutbox.enqueueDurably(message)" in html
|
||||
assert "completeToday: (item, options) => completeTodayItem(item, options)" in html
|
||||
assert "workSession.active() ? 'Queue close & next' : 'Queue issue closure'" in html
|
||||
handler = html.split("qs('#close-issue').addEventListener('click'", 1)[1].split(
|
||||
"qs('#close-pull-sheet').addEventListener", 1
|
||||
)[0]
|
||||
admission = handler.index("await closeOfflineIssue(closing)")
|
||||
sheet_close = handler.index("closeIssueSheet()")
|
||||
assert admission < sheet_close
|
||||
assert "Issue closure queued for reconnect." in handler
|
||||
assert "The issue remains in Today; retry." in handler
|
||||
@@ -126,6 +126,64 @@ process.stdout.write(JSON.stringify({{first, second, scroll, events, planner:pla
|
||||
}
|
||||
|
||||
|
||||
def test_plan_today_preview_requires_explicit_override_for_blocked_or_unknown_issue():
|
||||
script = f"""
|
||||
const createPlanToday = require({json.dumps(str(PLAN_TODAY))});
|
||||
const createPlanTodayPreview = require({json.dumps(str(PLAN_TODAY_PREVIEW))});
|
||||
const item = number => ({{kind:'issue', repository:'stackchain/dashboard', number, title:'Issue ' + number}});
|
||||
const planner = createPlanToday({{
|
||||
identity: value => 'issue:stackchain/dashboard:' + value.number + ':',
|
||||
save: () => true,
|
||||
}});
|
||||
planner.open([], [item(2), item(3)]);
|
||||
const preview = createPlanTodayPreview({{
|
||||
planner,
|
||||
identity: value => 'issue:stackchain/dashboard:' + value.number + ':',
|
||||
}});
|
||||
preview.open(item(2));
|
||||
preview.setDependencies({{available:true, dependencies:[{{repository:'stackchain/api', number:9, title:'Restore API', state:'open'}}]}});
|
||||
const blockedState = preview.snapshot();
|
||||
const blocked = preview.close({{add:true}});
|
||||
const overridden = preview.close({{add:true, override:true}});
|
||||
preview.open(item(3));
|
||||
preview.setDependencies({{available:false, dependencies:[]}});
|
||||
const unavailableState = preview.snapshot();
|
||||
const unavailable = preview.close({{add:true}});
|
||||
const unavailableOverride = preview.close({{add:true, override:true}});
|
||||
process.stdout.write(JSON.stringify({{blockedState, blocked, overridden, unavailableState, unavailable, unavailableOverride, planner:planner.snapshot()}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"blockedState": {
|
||||
"open": True,
|
||||
"item": {"kind": "issue", "repository": "stackchain/dashboard", "number": 2, "title": "Issue 2"},
|
||||
"trigger": None,
|
||||
"scroll": 0,
|
||||
"dependencies_available": True,
|
||||
"dependencies": [{"repository": "stackchain/api", "number": 9, "title": "Restore API", "state": "open"}],
|
||||
"requires_override": True,
|
||||
},
|
||||
"blocked": "blocked",
|
||||
"overridden": "added",
|
||||
"unavailableState": {
|
||||
"open": True,
|
||||
"item": {"kind": "issue", "repository": "stackchain/dashboard", "number": 3, "title": "Issue 3"},
|
||||
"trigger": None,
|
||||
"scroll": 0,
|
||||
"dependencies_available": False,
|
||||
"dependencies": [],
|
||||
"requires_override": True,
|
||||
},
|
||||
"unavailable": "dependencies-unavailable",
|
||||
"unavailableOverride": "added",
|
||||
"planner": {
|
||||
"open": True,
|
||||
"ids": ["issue:stackchain/dashboard:2:", "issue:stackchain/dashboard:3:"],
|
||||
"count": 2,
|
||||
"limit": 5,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_dashboard_wires_focused_plan_today_sheet():
|
||||
html = await dashboard()
|
||||
@@ -150,6 +208,12 @@ async def test_mobile_dashboard_wires_focused_plan_today_sheet():
|
||||
assert 'id="add-plan-preview"' in html
|
||||
assert "taskOverlayHistory.open('plan-today-preview')" in html
|
||||
assert "planTodayPreview.close({ add:true })" in html
|
||||
assert 'id="issue-blockers"' in html
|
||||
assert "planTodayPreview.setDependencies({" in html
|
||||
assert "Add blocked item anyway & back" in html
|
||||
assert "Blocker status unavailable" in html
|
||||
assert ".issue-blockers { max-width:100%; overflow-x:hidden;" in html
|
||||
assert ".issue-blocker { min-width:0; overflow-wrap:anywhere;" in html
|
||||
assert "Preview unavailable offline" in html
|
||||
|
||||
|
||||
@@ -168,6 +232,6 @@ async def test_plan_today_wires_cancel_back_and_success_through_overlay_history(
|
||||
def test_plan_today_controller_is_available_in_the_offline_shell():
|
||||
source = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/plan-today.js'" in source
|
||||
assert "BASE + 'static/plan-today-preview.js'" in source
|
||||
@@ -13,7 +13,7 @@ def run_worker_scenario(scenario: str) -> dict:
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const listeners = {{}};
|
||||
const state = {{ added: [], deleted: [], claimed: false, skipped: false, fetches: [], puts: [], backgroundFlushes: 0, outboxPurges: 0, notifications: [], focused: [], opened: [], failFetch: false, stallFetch: false, lateFetch: false, fetchAborted: false, fetchStatus: 200, fetchRedirected: false, cachedBody: null }};
|
||||
const state = {{ added: [], deleted: [], claimed: false, skipped: false, fetches: [], puts: [], backgroundFlushes: 0, backgroundResumes: 0, outboxPurges: 0, outboxLifecycle: [], notifications: [], focused: [], opened: [], failFetch: false, stallFetch: false, lateFetch: false, fetchAborted: false, fetchStatus: 200, fetchRedirected: false, cachedBody: null }};
|
||||
const storedResponses = new Map();
|
||||
storedResponses.set(
|
||||
'https://forge.example/dashboard/__offline-session-lease',
|
||||
@@ -47,8 +47,9 @@ const context = {{
|
||||
}},
|
||||
registration: {{showNotification: async (title, options) => state.notifications.push({{title,options}})}},
|
||||
__issueSync: {{
|
||||
flush: async () => {{ state.backgroundFlushes += 1; return state.flushResult; }},
|
||||
purge: async () => {{ state.outboxPurges += 1; }},
|
||||
flush: async () => {{ state.backgroundFlushes += 1; state.outboxLifecycle.push('flush'); return state.flushResult; }},
|
||||
purge: async () => {{ state.outboxPurges += 1; state.outboxLifecycle.push('purge'); }},
|
||||
resume: async () => {{ state.backgroundResumes += 1; state.outboxLifecycle.push('resume'); }},
|
||||
getReceiptPreference: async login => state.receiptLogin === login,
|
||||
}},
|
||||
}},
|
||||
@@ -121,16 +122,24 @@ async function dispatchNotificationClick(route) {{
|
||||
def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/my-work.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
|
||||
|
||||
def test_offline_review_next_ships_today_completion_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/today-completion.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
|
||||
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/create-issue-sheet.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -138,14 +147,14 @@ def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/later-picker.js'" in source
|
||||
|
||||
|
||||
def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -154,21 +163,21 @@ def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
def test_today_convergence_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
def test_mobile_search_viewport_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/mobile-search-viewport.js'" in source
|
||||
|
||||
|
||||
def test_update_ownership_flow_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
@@ -232,6 +241,21 @@ def test_authenticated_page_message_resumes_queued_background_delivery():
|
||||
assert result["backgroundFlushes"] == 1
|
||||
|
||||
|
||||
def test_authenticated_resume_rearms_a_previously_purged_worker_before_flushing():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
const replies = [];
|
||||
await dispatchMessage({type:'stackchain-purge-outbox'}, [{postMessage:value=>replies.push(value)}]);
|
||||
await dispatchMessage({type:'stackchain-resume-outbox'});
|
||||
process.stdout.write(JSON.stringify({state,replies}));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["replies"] == [{"ok": True}]
|
||||
assert result["state"]["outboxLifecycle"] == ["purge", "resume", "flush"]
|
||||
assert result["state"]["backgroundResumes"] == 1
|
||||
|
||||
|
||||
def test_background_mutation_abort_also_cancels_stalled_csrf_lookup():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
@@ -334,7 +358,7 @@ def test_one_session_bound_csrf_proof_is_reused_for_a_background_drain():
|
||||
def test_queue_today_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/queue-today.js'" in source
|
||||
|
||||
|
||||
@@ -365,12 +389,16 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/outbox-coordinator.js",
|
||||
"/dashboard/static/issue-outbox.js",
|
||||
"/dashboard/static/authored-outbox.js",
|
||||
"/dashboard/static/offline-issue-close.js",
|
||||
"/dashboard/static/notification-read-outbox.js",
|
||||
"/dashboard/static/offline-work.js",
|
||||
"/dashboard/static/offline-today.js",
|
||||
"/dashboard/static/my-work.js",
|
||||
"/dashboard/static/card-planning.js",
|
||||
"/dashboard/static/today-work.js",
|
||||
"/dashboard/static/today-completion.js",
|
||||
"/dashboard/static/today-readiness.js",
|
||||
"/dashboard/static/comment-next.js",
|
||||
"/dashboard/static/plan-today.js",
|
||||
"/dashboard/static/plan-today-preview.js",
|
||||
"/dashboard/static/today-sync.js",
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.dashboard_bundle import dashboard
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[1]
|
||||
READINESS = ROOT / "frontend" / "today-readiness.js"
|
||||
SERVICE_WORKER = ROOT / "frontend" / "service-worker.js"
|
||||
|
||||
|
||||
def run_node(script):
|
||||
return subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout
|
||||
|
||||
|
||||
def test_readiness_opens_ready_target_without_showing_a_gate():
|
||||
script = f"""
|
||||
const createTodayReadiness = require({json.dumps(str(READINESS))});
|
||||
const calls = [];
|
||||
const item = (number, kind='issue') => ({{kind, repository:'stackchain/dashboard', number, title:'Item ' + number}});
|
||||
const readiness = createTodayReadiness({{
|
||||
inspect: async candidate => ({{available:true, dependencies:[]}}),
|
||||
onOpen: (action, candidate) => calls.push(['open', action, candidate.number]),
|
||||
onGate: state => calls.push(['gate', state.status]),
|
||||
}});
|
||||
readiness.run('start', [item(1), item(2)]).then(result =>
|
||||
process.stdout.write(JSON.stringify({{result, calls}}))
|
||||
);
|
||||
"""
|
||||
assert json.loads(run_node(script)) == {
|
||||
"result": "opened",
|
||||
"calls": [["open", "start", 1]],
|
||||
}
|
||||
|
||||
|
||||
def test_readiness_gates_blocked_target_and_offers_earliest_ready_without_reordering():
|
||||
script = f"""
|
||||
const createTodayReadiness = require({json.dumps(str(READINESS))});
|
||||
const calls = [];
|
||||
const items = [1, 2, 3].map(number => ({{kind:'issue', repository:'r', number, title:'Issue ' + number}}));
|
||||
const readiness = createTodayReadiness({{
|
||||
inspect: async candidate => candidate.number === 1
|
||||
? {{available:true, dependencies:[{{repository:'r', number:99, title:'Prerequisite', state:'open', url:'https://forge.example/r/issues/99'}}]}}
|
||||
: {{available:true, dependencies:[]}},
|
||||
onOpen: (action, candidate) => calls.push(['open', action, candidate.number]),
|
||||
onGate: state => calls.push(['gate', state.status, state.target.number, state.nextReady.number, state.items.map(item => item.number)]),
|
||||
}});
|
||||
readiness.run('resume', items, items[0]).then(async result => {{
|
||||
const opened = readiness.startNextReady();
|
||||
process.stdout.write(JSON.stringify({{result, opened, calls, order:items.map(item => item.number)}}));
|
||||
}});
|
||||
"""
|
||||
assert json.loads(run_node(script)) == {
|
||||
"result": "gated",
|
||||
"opened": True,
|
||||
"calls": [
|
||||
["gate", "blocked", 1, 2, [1, 2, 3]],
|
||||
["open", "resume", 2],
|
||||
],
|
||||
"order": [1, 2, 3],
|
||||
}
|
||||
|
||||
|
||||
def test_readiness_never_calls_unknown_ready_and_supports_retry_or_explicit_override():
|
||||
script = f"""
|
||||
const createTodayReadiness = require({json.dumps(str(READINESS))});
|
||||
const calls = [];
|
||||
const target = {{kind:'issue', repository:'r', number:1}};
|
||||
let available = false;
|
||||
const readiness = createTodayReadiness({{
|
||||
inspect: async () => available ? {{available:true, dependencies:[]}} : {{available:false, dependencies:[]}},
|
||||
onOpen: (action, candidate) => calls.push(['open', action, candidate.number]),
|
||||
onGate: state => calls.push(['gate', state.status]),
|
||||
}});
|
||||
readiness.run('next', [target], target).then(async result => {{
|
||||
available = true;
|
||||
const retried = await readiness.retry();
|
||||
available = false;
|
||||
await readiness.run('continue', [target], target);
|
||||
const overridden = readiness.workAnyway();
|
||||
process.stdout.write(JSON.stringify({{result, retried, overridden, calls}}));
|
||||
}});
|
||||
"""
|
||||
assert json.loads(run_node(script)) == {
|
||||
"result": "gated",
|
||||
"retried": "opened",
|
||||
"overridden": True,
|
||||
"calls": [
|
||||
["gate", "unknown"],
|
||||
["open", "next", 1],
|
||||
["gate", "unknown"],
|
||||
["open", "continue", 1],
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_readiness_treats_non_issue_work_as_runnable_without_dependency_io():
|
||||
script = f"""
|
||||
const createTodayReadiness = require({json.dumps(str(READINESS))});
|
||||
let inspections = 0;
|
||||
const pull = {{kind:'pull', repository:'r', number:7}};
|
||||
const readiness = createTodayReadiness({{
|
||||
inspect: async () => {{ inspections += 1; throw new Error('not expected'); }},
|
||||
onOpen: () => undefined,
|
||||
onGate: () => undefined,
|
||||
}});
|
||||
readiness.run('start', [pull]).then(result =>
|
||||
process.stdout.write(JSON.stringify({{result, inspections}}))
|
||||
);
|
||||
"""
|
||||
assert json.loads(run_node(script)) == {"result": "opened", "inspections": 0}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_exposes_mobile_today_readiness_gate_and_runtime():
|
||||
html = await dashboard()
|
||||
|
||||
assert '<script src="static/today-readiness.js"></script>' in html
|
||||
assert 'id="today-readiness-sheet"' in html
|
||||
assert 'id="today-readiness-next"' in html
|
||||
assert 'id="today-readiness-anyway"' in html
|
||||
assert 'id="today-readiness-retry"' in html
|
||||
assert 'id="today-readiness-plan"' in html
|
||||
assert "createTodayReadiness({" in html
|
||||
assert "runTodayTransition('start'" in html
|
||||
assert "runTodayTransition('resume'" in html
|
||||
assert "runTodayTransition('continue'" in html
|
||||
assert "runTodayTransition('next'" in html
|
||||
assert "runTodayTransition('complete'" in html
|
||||
|
||||
|
||||
def test_readiness_runtime_is_available_in_offline_shell():
|
||||
assert "BASE + 'static/today-readiness.js'" in SERVICE_WORKER.read_text()
|
||||
|
||||
|
||||
def test_mobile_readiness_gate_has_touch_safe_wrapping_actions():
|
||||
css = (ROOT / "frontend" / "dashboard.css").read_text()
|
||||
|
||||
assert ".today-readiness-actions button" in css
|
||||
assert "min-height:44px" in css
|
||||
assert ".today-readiness-item" in css
|
||||
assert "overflow-wrap:anywhere" in css
|
||||
assert "env(safe-area-inset-bottom)" in css
|
||||
@@ -86,7 +86,7 @@ sync.enqueue('add', 'issue:r:1:');
|
||||
def test_inflight_today_drain_ships_in_a_new_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v67" in source
|
||||
assert "stackchain-dashboard-shell-v73" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ from tests.dashboard_bundle import dashboard
|
||||
|
||||
|
||||
TODAY_WORK = Path(__file__).parents[1] / "frontend" / "today-work.js"
|
||||
TODAY_COMPLETION = Path(__file__).parents[1] / "frontend" / "today-completion.js"
|
||||
SERVICE_WORKER = Path(__file__).parents[1] / "frontend" / "service-worker.js"
|
||||
|
||||
|
||||
def run_node(script):
|
||||
@@ -87,6 +89,102 @@ process.stdout.write(JSON.stringify([
|
||||
]
|
||||
|
||||
|
||||
def test_done_for_today_removes_current_plan_item_syncs_and_advances_without_gitea_mutation():
|
||||
script = f"""
|
||||
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
|
||||
const calls = [];
|
||||
const current = {{kind:'issue', repository:'stackchain/dashboard', number:421}};
|
||||
const complete = createTodayCompletion({{
|
||||
todayWork: {{
|
||||
identity: item => `issue:${{item.repository}}:${{item.number}}:`,
|
||||
remove: item => {{ calls.push(`remove:${{item.number}}`); return true; }},
|
||||
}},
|
||||
todaySync: {{
|
||||
enqueue: (action, identity) => {{ calls.push(`sync:${{action}}:${{identity}}`); return true; }},
|
||||
flush: () => calls.push('flush'),
|
||||
}},
|
||||
refresh: () => calls.push('refresh'),
|
||||
warm: () => calls.push('warm'),
|
||||
workSession: {{ complete: () => calls.push('advance') }},
|
||||
announce: message => calls.push(`announce:${{message}}`),
|
||||
}});
|
||||
const completed = complete(current);
|
||||
process.stdout.write(JSON.stringify({{completed, calls}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"completed": True,
|
||||
"calls": [
|
||||
"remove:421",
|
||||
"sync:remove:issue:stackchain/dashboard:421:",
|
||||
"flush",
|
||||
"refresh",
|
||||
"warm",
|
||||
"advance",
|
||||
"announce:Done for Today. The Gitea item is unchanged.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_done_for_today_does_not_advance_when_local_plan_persistence_fails():
|
||||
script = f"""
|
||||
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
|
||||
const calls = [];
|
||||
const complete = createTodayCompletion({{
|
||||
todayWork: {{identity: () => 'issue:r:1:', remove: () => false}},
|
||||
todaySync: {{enqueue: () => calls.push('sync'), flush: () => calls.push('flush')}},
|
||||
refresh: () => calls.push('refresh'),
|
||||
warm: () => calls.push('warm'),
|
||||
workSession: {{complete: () => calls.push('advance')}},
|
||||
announce: message => calls.push(message),
|
||||
}});
|
||||
const completed = complete({{kind:'issue', repository:'r', number:1}});
|
||||
process.stdout.write(JSON.stringify({{completed, calls}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"completed": False,
|
||||
"calls": ["Could not update Today on this device. Try again."],
|
||||
}
|
||||
|
||||
|
||||
def test_today_completion_reports_context_specific_success_and_partial_failure():
|
||||
script = f"""
|
||||
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
|
||||
const messages = [];
|
||||
let removable = false;
|
||||
const complete = createTodayCompletion({{
|
||||
todayWork: {{identity: () => 'review:r:7:', remove: () => removable}},
|
||||
todaySync: {{enqueue: () => true, flush: () => undefined}},
|
||||
refresh: () => undefined,
|
||||
warm: () => undefined,
|
||||
workSession: {{complete: () => undefined}},
|
||||
announce: message => messages.push(message),
|
||||
}});
|
||||
const options = {{
|
||||
successMessage: 'Review queued. Next Today item opened.',
|
||||
failureMessage: 'Review queued, but Today still needs completion.',
|
||||
}};
|
||||
const failed = complete({{kind:'review', repository:'r', number:7}}, options);
|
||||
removable = true;
|
||||
const completed = complete({{kind:'review', repository:'r', number:7}}, options);
|
||||
process.stdout.write(JSON.stringify({{failed, completed, messages}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"failed": False,
|
||||
"completed": True,
|
||||
"messages": [
|
||||
"Review queued, but Today still needs completion.",
|
||||
"Review queued. Next Today item opened.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_done_for_today_logic_is_available_in_the_offline_app_shell():
|
||||
assert "BASE + 'static/today-completion.js'" in SERVICE_WORKER.read_text()
|
||||
|
||||
|
||||
def test_authoritative_reconciliation_reports_retired_ids_before_local_prune():
|
||||
script = f"""
|
||||
const createTodayWork = require({json.dumps(str(TODAY_WORK))});
|
||||
@@ -183,6 +281,22 @@ async def test_dashboard_runs_the_curated_today_queue_as_a_mobile_work_flow():
|
||||
assert "Another device filled Today · showing its saved plan." in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_session_sheets_offer_a_touch_safe_plan_only_completion_action():
|
||||
html = await dashboard()
|
||||
|
||||
assert '<script src="static/today-completion.js"></script>' in html
|
||||
assert html.count('data-work-session-complete=') == 4
|
||||
assert html.count('Done for Today & next') == 4
|
||||
assert "button.hidden = !workSession.checkpointed();" in html
|
||||
assert "const completeTodayItem = createTodayCompletion({" in html
|
||||
assert "refresh: () => refreshMyWorkView({ reconcileSession:false })," in html
|
||||
assert "document.querySelectorAll('[data-work-session-complete]')" in html
|
||||
assert "completeTodayItem(selectedSessionItem(button.dataset.workSessionComplete))" in html
|
||||
assert ".work-session-nav button { min-height:44px; width:100%; }" in html
|
||||
assert "grid-template-columns:repeat(3,minmax(0,1fr))" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_activates_today_lifecycle_convergence():
|
||||
html = await dashboard()
|
||||
|
||||
Reference in new issue
Block a user