Archived
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2082fbd5eb | ||
|
|
55156f45c9 | ||
|
|
5bf0f97df8 | ||
|
|
ce2f04ab6d | ||
|
|
f7b2a96206 | ||
|
|
a6550f8b1f | ||
|
|
66968d90c0 | ||
|
|
442d0a157d | ||
|
|
4a85f02eae | ||
|
|
dfd33aee1c | ||
|
|
c5b466f281 | ||
|
|
1d242bab75 | ||
|
|
40284a7e30 | ||
|
|
ea08f566ff | ||
|
|
ca671f0d00 | ||
|
|
6e677f8857 | ||
|
|
e47e6329cc | ||
|
|
11395b655a | ||
|
|
ca520d2eb6 | ||
|
|
25dda21811 | ||
|
|
8a57ea73fb | ||
|
|
6729359ba2 | ||
|
|
f687389046 | ||
|
|
a7f4f9714f | ||
|
|
7ba238fb53 | ||
|
|
b845f8ba95 | ||
|
|
996309f52f | ||
|
|
8d12a0384b |
No files matched your search
@@ -82,7 +82,7 @@ jobs:
|
||||
RELEASE_URL="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
|
||||
|
||||
(cd dist && sha256sum -c ./*.sha256)
|
||||
python3 scripts/verify_release.py --input-dir dist --commit "$TARGET"
|
||||
python3 scripts/verify_release.py --input-dir dist --commit "$TARGET" --repository .
|
||||
|
||||
printf '{"tag_name":"%s","target_commitish":"%s","name":"Release Candidate %s","body":"CI-tested release candidate for commit %s. Verify downloads with the attached SHA-256 checksum.","draft":true,"prerelease":true}\n' \
|
||||
"$TAG" "$TARGET" "$TAG" "$TARGET" > /tmp/release.json
|
||||
|
||||
@@ -117,8 +117,11 @@ time. An over-capacity plan requires a second explicit save, legacy plans migrat
|
||||
and an active Today session shows the current estimate plus estimated remaining runway. 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 and starts an account-bound actual-time timer for the exact item. The sticky mobile session controls show elapsed time beside the estimate and let the operator pause or resume it. Switching items preserves each item's elapsed value, while wall-clock checkpoints keep a running timer accurate through app backgrounding, reloads, and installed-app restarts without double counting. **End session** stops accumulation but retains measured time with the private device data. The recap identifies each item by title and repository, reports per-item estimate variance, and **Save recap & adjust plan** continues into the current ordered Today plan without changing Gitea time entries. Eligible non-zero rows also offer an unchecked **Log Xm to Gitea** control. **Log selected time to Gitea** saves the recap and sends only those corrected durations to each canonical issue or pull request; confirmed account-scoped receipts prevent a completed row from being posted again, while definite failures retain the draft for an explicit retry. If the upstream response is lost after sending, Stackchain marks the row for verification in Gitea instead of risking an automatic duplicate. Actual time appears in planning as an explicit estimate recommendation; it changes only the planning draft until the operator chooses **Save plan** or **Save & start**. After the recap is confirmed, this recommendation handoff remains account-bound on the device through reloads, app restarts, planner cancellation, and failed plan admission. Opening **Plan Today** resumes it without reposting the recap; a successful plan save clears it, while **Discard recap feedback** removes only the handoff and leaves recap history unchanged. The recap and any corrected actual minutes are also saved as an account-bound device draft: an offline save failure can survive a reload and retry with the same idempotent session ID, while another account cannot view it. The draft and timer are cleared only after the account confirms the recap.
|
||||
as unknown rather than unblocked. Completing any Today item now exposes a 10-second, touch-safe
|
||||
**Undo** receipt. Undo restores the item's original order and estimate, queues the inverse cross-device
|
||||
plan changes, and leaves the already-advanced work session on its current item; expiry, capacity, or a
|
||||
concurrently changed plan is reported without overwriting newer work. Starting a Today work session also
|
||||
stores an account-bound checkpoint on the current device and starts an account-bound actual-time timer for the exact item. The sticky mobile session controls show elapsed time beside the estimate and let the operator pause or resume it. An opt-in, privacy-safe lock-screen notification mirrors the current pause/resume control and adds **Finish current**: its opaque one-shot action is bound to the exact active item, reuses **Done & next** or recap, and never changes the underlying Gitea issue or pull request. Switching items preserves each item's elapsed value, while wall-clock checkpoints keep a running timer accurate through app backgrounding, reloads, and installed-app restarts without double counting. **End session** stops accumulation but retains measured time with the private device data. The recap identifies each item by title and repository, reports per-item estimate variance, and **Save recap & adjust plan** continues into the current ordered Today plan without changing Gitea time entries. Eligible non-zero rows also offer an unchecked **Log Xm to Gitea** control. **Log selected time to Gitea** saves the recap and sends only those corrected durations to each canonical issue or pull request; confirmed account-scoped receipts prevent a completed row from being posted again, while definite failures retain the draft for an explicit retry. If the upstream response is lost after sending, Stackchain marks the row for verification in Gitea instead of risking an automatic duplicate. Actual time appears in planning as an explicit estimate recommendation; it changes only the planning draft until the operator chooses **Save plan** or **Save & start**. After the recap is confirmed, this recommendation handoff remains account-bound on the device through reloads, app restarts, planner cancellation, and failed plan admission. Opening **Plan Today** resumes it without reposting the recap; a successful plan save clears it, while **Discard recap feedback** removes only the handoff and leaves recap history unchanged. The recap and any corrected actual minutes are also saved as an account-bound device draft: an offline save failure can survive a reload and retry with the same idempotent session ID, while another account cannot view it. The draft and timer are cleared only after the account confirms the recap.
|
||||
After a reload or installed-app
|
||||
restart, **Resume Today** reopens the saved item (or the next surviving item if work changed). In an open
|
||||
assigned issue, the mobile detail sheet renders Markdown checklist items as touch-safe controls and keeps
|
||||
|
||||
+27
-3
@@ -28,9 +28,11 @@ header { position: sticky; top: 0; z-index: 20; padding: 12px 16px; display:flex
|
||||
.app-menu-panel { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
|
||||
#open-insights { display:none; }
|
||||
button { background: linear-gradient(180deg,#1f3a5f,#15324d); border:1px solid #2a496e; color:#e5e7eb; padding:8px 12px; border-radius:10px; cursor:pointer; }
|
||||
.notification-undo { position:fixed; z-index:110; left:50%; bottom:calc(88px + env(safe-area-inset-bottom)); transform:translateX(-50%); box-sizing:border-box; width:min(520px,calc(100vw - 24px)); display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 12px; border:1px solid #60a5fa; border-radius:12px; background:#10233d; box-shadow:0 12px 36px rgba(0,0,0,.5); overflow-wrap:anywhere; }
|
||||
.notification-undo[hidden] { display:none; }
|
||||
.notification-undo button { min-height:44px; min-width:64px; flex:none; }
|
||||
.notification-undo { position:fixed; }
|
||||
.notification-undo button { min-height:44px; }
|
||||
.notification-undo, .today-completion-undo { position:fixed; z-index:110; left:50%; bottom:calc(88px + env(safe-area-inset-bottom)); transform:translateX(-50%); box-sizing:border-box; width:min(520px,calc(100vw - 24px)); display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 12px; border:1px solid #60a5fa; border-radius:12px; background:#10233d; box-shadow:0 12px 36px rgba(0,0,0,.5); overflow-wrap:anywhere; }
|
||||
.notification-undo[hidden], .today-completion-undo[hidden] { display:none; }
|
||||
.notification-undo button, .today-completion-undo button { min-height:44px; min-width:64px; flex:none; }
|
||||
.draft-capacity-sheet { position:fixed; inset:0; z-index:96; display:flex; align-items:flex-end; justify-content:center; background:rgba(5,12,21,.82); backdrop-filter:blur(4px); }
|
||||
.draft-capacity-sheet[hidden] { display:none; }
|
||||
.draft-capacity-panel { box-sizing:border-box; width:min(620px,100%); max-height:100dvh; 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; }
|
||||
@@ -252,6 +254,21 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.today-interruption-panel h2 { margin:.25rem 0; overflow-wrap:anywhere; }
|
||||
.today-interruption-actions { display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:16px; }
|
||||
.today-interruption-actions button { min-height:44px; width:100%; }
|
||||
.today-break-sheet { position:fixed; inset:0; width:100%; max-width:none; height:100%; max-height:none; margin:0; padding:0; border:0; background:rgba(5,12,21,.82); color:#e5e7eb; }
|
||||
.today-break-sheet::backdrop { background:rgba(5,12,21,.82); backdrop-filter:blur(4px); }
|
||||
.today-break-panel { position:absolute; left:0; right:0; bottom:0; box-sizing:border-box; width:min(620px,100%); max-height:100dvh; margin:auto; overflow:auto; overflow-x:hidden; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); border:1px solid #31577f; border-radius:18px 18px 0 0; background:#0b1526; }
|
||||
.today-break-panel header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
|
||||
.today-break-panel h2, .today-break-panel p { margin-top:0; }
|
||||
.today-break-panel header button, .today-break-actions button, .today-break-custom button { min-height:44px; }
|
||||
.today-break-actions { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; margin:16px 0; }
|
||||
.today-break-actions button { min-width:0; width:100%; }
|
||||
.today-break-custom { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:8px; align-items:end; }
|
||||
.today-break-custom label, .today-break-custom p { grid-column:1 / -1; }
|
||||
.today-break-custom input { box-sizing:border-box; width:100%; min-height:44px; }
|
||||
.today-break-status { position:fixed; z-index:46; left:12px; right:12px; bottom:calc(224px + env(safe-area-inset-bottom)); box-sizing:border-box; display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:8px; padding:10px 12px; border:1px solid #60a5fa; border-radius:12px; background:#102641; }
|
||||
.today-break-status:has(> span[hidden]) { display:none; }
|
||||
.today-break-status button { min-height:44px; min-width:112px; }
|
||||
@media(max-width:359px) { .today-break-actions { grid-template-columns:1fr; } }
|
||||
.today-recap-sheet { position:fixed; inset:0; z-index:88; display:flex; align-items:flex-end; justify-content:center; background:rgba(5,12,21,.82); backdrop-filter:blur(4px); }
|
||||
.today-recap-sheet[hidden] { display:none; }
|
||||
.today-recap-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 #2a496e; border-radius:18px 18px 0 0; background:#0b1526; }
|
||||
@@ -926,6 +943,10 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
|
||||
.mobile-today-hud { display:none; }
|
||||
.mobile-today-hud[hidden], .mobile-today-hud[data-overlay-hidden="true"] { display:none; }
|
||||
.today-session-handoff { position:fixed; left:12px; right:12px; bottom:calc(68px + env(safe-area-inset-bottom)); z-index:45; display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:10px; padding:12px; border:1px solid #60a5fa; border-radius:12px; background:rgba(16,38,65,.98); box-shadow:0 8px 28px rgba(0,0,0,.35); }
|
||||
.today-session-handoff[hidden] { display:none; }
|
||||
.today-session-handoff button { min-height:44px; }
|
||||
@media(max-width:420px) { .today-session-handoff { grid-template-columns:1fr; } .today-session-handoff button { width:100%; } }
|
||||
.mobile-task-action { min-width:0; min-height:44px; padding:6px 2px; border:0; border-radius:8px; background:transparent; display:grid; place-items:center; gap:2px; font-size:12px; }
|
||||
.mobile-task-action[hidden] { display:none; }
|
||||
.mobile-task-action[aria-current="page"] { color:#bfdbfe; background:#17365a; outline:1px solid #31577f; }
|
||||
@@ -1066,7 +1087,10 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.mobile-today-hud [data-mobile-today-complete] { grid-area:complete; }
|
||||
.mobile-today-hud [data-mobile-today-toggle] { grid-area:toggle; }
|
||||
.mobile-today-hud button { min-height:44px; max-width:100%; }
|
||||
.mobile-today-hud [data-today-break-open] { grid-column:1 / -1; }
|
||||
|
||||
.mobile-today-hud [data-work-session-adjust-plan] { grid-column:1 / -1; }
|
||||
.today-completion-undo { bottom:calc(224px + env(safe-area-inset-bottom)); }
|
||||
}
|
||||
@media (min-width:701px) { .update-gesture-status { display:none; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
+88
-6
@@ -97,6 +97,7 @@
|
||||
(authored ? applyAuthoredOutboxResult : applyOutboxResult)(result);
|
||||
}
|
||||
let mobileQueueCounts = {};
|
||||
let mobilePreparationItems = {};
|
||||
const mobileDeliveryRecovery = createMobileDeliveryRecovery({
|
||||
getItems: () => draftInbox.partition(lastDrafts).deliveries,
|
||||
getIndex: item => lastDrafts.indexOf(item),
|
||||
@@ -131,21 +132,31 @@
|
||||
getCounts: () => mobileQueueCounts,
|
||||
openFindWork: () => qs('#find-work').click(),
|
||||
});
|
||||
function openMobileStartDay() {
|
||||
const state = mobileStartDay.state();
|
||||
mobileStartDay.render();
|
||||
qs('#mobile-queue-heading').textContent = state.active ? 'Resume Prepare Today' : 'Prepare Today';
|
||||
const sheet = qs('#mobile-queue-sheet');
|
||||
if (!sheet.open) qs('#mobile-queue-sheet').showModal();
|
||||
qs('#mobile-start-day-action').focus();
|
||||
}
|
||||
const mobileWorkEntry = createMobileWorkEntry({
|
||||
isTodayActive: () => workSession.checkpointed(),
|
||||
isTodayResumable: () => workSession.resumable(),
|
||||
getTodayCount: () => todayMyWork.length,
|
||||
getEligibleCount: () => activeMyWork.length,
|
||||
getPreparationState: () => mobileStartDay.state(),
|
||||
queueLauncher: mobileQueueLauncher,
|
||||
continueToday: continueTodaySession,
|
||||
resumeToday: resumeTodaySession,
|
||||
startToday: startTodaySession,
|
||||
planToday: () => openPlanToday(mobileTaskButtons.work),
|
||||
|
||||
prepareToday: openMobileStartDay,
|
||||
findWork: () => qs('#find-work').click(),
|
||||
});
|
||||
const mobileStartDay = createMobileStartDay({
|
||||
getCounts: () => mobileQueueCounts,
|
||||
getPhaseItems: () => mobilePreparationItems,
|
||||
getLogin: () => confirmedOwnerLogin,
|
||||
openQueue: name => {
|
||||
const sheet = qs('#mobile-queue-sheet');
|
||||
@@ -365,11 +376,12 @@
|
||||
onStatus: (state, detail = {}) => {
|
||||
const status = qs('#today-sync-status');
|
||||
status.textContent = state === 'saved' ? 'Today saved to account.' :
|
||||
(state === 'retrying' ? `Today saved on this device · retrying in ${Math.ceil(detail.delayMs / 1000)}s.` :
|
||||
(state === 'pending' ? 'Today saved on this device · sync pending.' :
|
||||
(state === 'full' ? 'Another device filled Today · showing its saved plan.' :
|
||||
(state === 'expired' ? `Today edit expired after 30 days offline${detail.count > 1 ? 's' : ''} · account plan kept.` :
|
||||
'Today sync unavailable · changes stay on this device.'))));
|
||||
(state === 'recovered' ? `Today queue recovered · discarded ${detail.discarded} unreadable device record${detail.discarded === 1 ? '' : 's'}.` :
|
||||
(state === 'retrying' ? `Today saved on this device · retrying in ${Math.ceil(detail.delayMs / 1000)}s.` :
|
||||
(state === 'pending' ? 'Today saved on this device · sync pending.' :
|
||||
(state === 'full' ? 'Another device filled Today · showing its saved plan.' :
|
||||
(state === 'expired' ? `Today edit expired after 30 days offline${detail.count > 1 ? 's' : ''} · account plan kept.` :
|
||||
'Today sync unavailable · changes stay on this device.')))));
|
||||
},
|
||||
});
|
||||
todaySync.startLifecycle({ window, document });
|
||||
@@ -1795,9 +1807,17 @@
|
||||
'Agenda progress could not be saved on this device. You can keep working.';
|
||||
},
|
||||
});
|
||||
let todaySessionSync = null;
|
||||
let todayLockScreen = null;
|
||||
const timer = createTodayTimer({
|
||||
storage: localStorage,
|
||||
getLogin: () => confirmedOwnerLogin,
|
||||
onChange: snapshot => {
|
||||
todaySessionSync?.publish(snapshot);
|
||||
queueMicrotask(() => {
|
||||
if (todayLockScreen) todayLockScreen.sync(snapshot, workSession.checkpointed());
|
||||
});
|
||||
},
|
||||
});
|
||||
const timerView = createTodayTimerView({
|
||||
timer,
|
||||
@@ -1809,11 +1829,25 @@
|
||||
selectTodayWork();
|
||||
workSession.reopen(todayMyWork.find(item => todayWork.identity(item) === identity));
|
||||
},
|
||||
onResume: identity => {
|
||||
selectTodayWork();
|
||||
const item = todayMyWork.find(entry => todayWork.identity(entry) === identity);
|
||||
if (!workSession.resume(item)) resumeTodaySession();
|
||||
},
|
||||
onComplete: identity => {
|
||||
const item = todayMyWork.find(entry => todayWork.identity(entry) === identity);
|
||||
return completeTodayItem(item);
|
||||
},
|
||||
});
|
||||
todaySessionSync = attachTodaySessionHandoff({
|
||||
fetchJson:fetchReviewJson, storage:localStorage, timer, qs,
|
||||
items:() => [...todayMyWork, ...activeMyWork],
|
||||
identity:item => todayWork.identity(item),
|
||||
selectToday:() => selectTodayWork(),
|
||||
startItem:item => workSession.start(item),
|
||||
announce:message => { qs('#my-work-action-status').textContent = message; },
|
||||
renderTimer:() => timerView.render(),
|
||||
});
|
||||
renderAttentionInterruption();
|
||||
qs('#return-to-today').addEventListener('click', () => {
|
||||
const returned = timer.returnFromAttention();
|
||||
@@ -2115,6 +2149,47 @@
|
||||
announce: message => { qs('#my-work-action-status').textContent = message; },
|
||||
advance: () => runTodayTransition('complete'),
|
||||
});
|
||||
todayLockScreen = createTodayLockScreen({
|
||||
storage:localStorage,
|
||||
getLogin:() => confirmedOwnerLogin,
|
||||
serviceWorker:navigator.serviceWorker,
|
||||
NotificationRef:window.Notification,
|
||||
control:qs('#today-lock-screen'),
|
||||
status:qs('#today-lock-screen-status'),
|
||||
locationRef:window.location,
|
||||
historyRef:window.history,
|
||||
onAction:(action, expectedIdentity) => {
|
||||
const state = timer.snapshot();
|
||||
if (action === 'complete') {
|
||||
selectTodayWork();
|
||||
if (!state.identity || state.identity !== expectedIdentity) {
|
||||
qs('#my-work-action-status').textContent =
|
||||
'That lock-screen action is stale. The current Today item was not changed.';
|
||||
return;
|
||||
}
|
||||
const item = todayMyWork.find(entry => todayWork.identity(entry) === expectedIdentity);
|
||||
if (!item) {
|
||||
qs('#my-work-action-status').textContent =
|
||||
'That Today item is no longer available. Nothing was changed.';
|
||||
return;
|
||||
}
|
||||
workSession.reopen(item);
|
||||
completeTodayItem(item);
|
||||
timerView.render();
|
||||
return;
|
||||
}
|
||||
if (!state.identity || (action === 'pause' && !state.running) ||
|
||||
(action === 'resume' && state.running)) return;
|
||||
const changed = action === 'pause' ? timer.pause() : timer.resume();
|
||||
if (changed === false) return;
|
||||
selectTodayWork();
|
||||
const item = todayMyWork.find(entry => todayWork.identity(entry) === state.identity);
|
||||
if (item) workSession.reopen(item);
|
||||
timerView.render();
|
||||
},
|
||||
});
|
||||
await todayLockScreen.sync(timer.snapshot(), workSession.checkpointed());
|
||||
await todayLockScreen.consumeLaunchAction();
|
||||
async function completeOwnershipExitToday(item) {
|
||||
if (!item || !todayWork.remove(item)) return null;
|
||||
todaySync.enqueue('remove', todayWork.identity(item));
|
||||
@@ -3042,6 +3117,13 @@
|
||||
counts.later = laterMyWork.length;
|
||||
counts.draft = lastDrafts.length;
|
||||
counts.delivery = draftInbox.partition(lastDrafts).actionable;
|
||||
mobilePreparationItems = {
|
||||
delivery:draftInbox.partition(lastDrafts).deliveries,
|
||||
agenda:agendaMyWork(activeMyWork),
|
||||
attention:activeMyWork.filter(item => item.needs_attention),
|
||||
update:activeMyWork.filter(item => item.has_update),
|
||||
filed:activeMyWork.filter(item => item.is_filed),
|
||||
};
|
||||
if (!launchFilterResolved) {
|
||||
selectedWorkFilter = mobileLaunch.chooseFilter({
|
||||
saved: savedWorkFilter, today: counts.today, attention: counts.attention,
|
||||
|
||||
@@ -182,6 +182,8 @@
|
||||
<label for="push-deadline-hour">Reminder hour <select id="push-deadline-hour" aria-label="Deadline reminder local hour"></select></label>
|
||||
<label for="push-deadline-days">Warn me <select id="push-deadline-days" aria-label="Deadline reminder horizon"><option value="0">Due today</option><option value="2" selected>Next 2 days</option><option value="7">Next 7 days</option></select></label>
|
||||
<span class="small" id="push-deadline-status" role="status" aria-live="polite"></span>
|
||||
<label class="push-update-control" for="today-lock-screen"><input id="today-lock-screen" type="checkbox" /> Show active Today controls on my lock screen</label>
|
||||
<span class="small" id="today-lock-screen-status" role="status" aria-live="polite"></span>
|
||||
<button id="clear-offline-work" type="button">Clear offline work data</button>
|
||||
<button id="retry-offline-storage" type="button" hidden>Retry offline saving</button>
|
||||
<span class="small" id="offline-work-status" role="status" aria-live="polite"></span>
|
||||
@@ -283,6 +285,7 @@
|
||||
<div class="small" id="my-work-action-status" aria-live="assertive"></div>
|
||||
<button class="retry-work-route" id="retry-unfiled-draft-sync" type="button" hidden>Retry Draft sync</button>
|
||||
<div class="small" id="today-sync-status" aria-live="polite">Today is saved on this device.</div>
|
||||
<div class="small" id="today-session-sync-status" role="status" aria-live="polite" hidden></div>
|
||||
<div class="small" id="later-sync-status" aria-live="polite">Later is saved on this device.</div>
|
||||
<button class="retry-work-route" id="retry-work-route" type="button" hidden>Retry shared work item</button>
|
||||
<div class="small" id="work-route-share-status" aria-live="polite"></div>
|
||||
@@ -1305,6 +1308,11 @@
|
||||
<button id="undo-notification" type="button" aria-label="Undo marking update read">Undo</button>
|
||||
</div>
|
||||
|
||||
<div class="today-completion-undo" id="today-completion-undo" role="status" aria-live="assertive" hidden>
|
||||
<span>Removed from Today. Undo?</span>
|
||||
<button id="undo-today-completion" type="button" aria-label="Undo removing the completed item from Today">Undo</button>
|
||||
</div>
|
||||
|
||||
<div class="pull-sheet" id="pull-sheet" role="dialog" aria-modal="true" aria-labelledby="pull-sheet-title">
|
||||
<section class="pull-sheet-panel">
|
||||
<div class="pull-sheet-header">
|
||||
@@ -1515,13 +1523,43 @@
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<section class="today-session-handoff" id="today-session-handoff" aria-live="polite" hidden>
|
||||
<div>
|
||||
<strong>Today is active on another device</strong>
|
||||
<div class="small" id="today-session-handoff-summary"></div>
|
||||
</div>
|
||||
<button id="continue-today-session" type="button">Continue here</button>
|
||||
</section>
|
||||
|
||||
<section class="mobile-today-hud" data-mobile-today-hud aria-label="Active Today session" hidden>
|
||||
<button class="mobile-today-summary" data-mobile-today-open type="button" aria-label="Open current Today item"></button>
|
||||
<button data-mobile-today-complete type="button" hidden>Done & next</button>
|
||||
<div class="small" data-work-session-progress aria-live="polite"></div>
|
||||
<button data-mobile-today-toggle data-work-session-timer-toggle type="button">Pause timer</button>
|
||||
<button data-today-break-open type="button">Take break</button>
|
||||
<button data-work-session-adjust-plan type="button" hidden>Adjust remaining plan</button>
|
||||
</section>
|
||||
<div class="today-break-status" role="status" aria-live="polite">
|
||||
<span id="today-break-status" hidden></span>
|
||||
<button id="resume-today-break" type="button" hidden>Resume Today</button>
|
||||
</div>
|
||||
<dialog class="today-break-sheet" id="today-break-sheet" aria-labelledby="today-break-title">
|
||||
<section class="today-break-panel">
|
||||
<header><div><p class="small muted">Today timer</p><h2 id="today-break-title">Take a timed break</h2></div><button id="cancel-today-break" type="button">Cancel</button></header>
|
||||
<p class="small">Your current item stays selected and tracked time remains paused until you explicitly resume.</p>
|
||||
<div class="today-break-actions" aria-label="Break duration">
|
||||
<button type="button" data-today-break-minutes="5">5 minutes</button>
|
||||
<button type="button" data-today-break-minutes="15">15 minutes</button>
|
||||
<button type="button" data-today-break-minutes="30">30 minutes</button>
|
||||
</div>
|
||||
<form id="today-break-custom-form" class="today-break-custom">
|
||||
<label for="today-break-custom-minutes">Custom minutes</label>
|
||||
<input id="today-break-custom-minutes" type="number" inputmode="numeric" min="1" max="120" step="1" required />
|
||||
<button type="submit">Start break</button>
|
||||
<p id="today-break-error" class="small" role="alert"></p>
|
||||
</form>
|
||||
</section>
|
||||
</dialog>
|
||||
<dialog class="mobile-queue-sheet" id="mobile-queue-sheet" aria-labelledby="mobile-queue-heading">
|
||||
<section class="mobile-queue-panel">
|
||||
<header><h2 id="mobile-queue-heading">Work queues</h2><button id="close-mobile-queues" type="button">Close</button></header>
|
||||
@@ -1616,6 +1654,9 @@
|
||||
<script src="static/work-selection.js"></script>
|
||||
<script src="static/today-work.js"></script>
|
||||
<script src="static/today-timer.js"></script>
|
||||
<script src="static/today-break.js"></script>
|
||||
<script src="static/today-lock-screen.js"></script>
|
||||
<script src="static/today-session-sync.js"></script>
|
||||
<script src="static/today-recap.js"></script>
|
||||
<script src="static/today-wrap-up.js"></script>
|
||||
<script src="static/today-handoff.js"></script>
|
||||
|
||||
@@ -11,11 +11,44 @@
|
||||
['update', 'Updates'],
|
||||
['filed', 'Filed'],
|
||||
];
|
||||
const anonymousItems = new WeakMap();
|
||||
let anonymousItemSequence = 0;
|
||||
|
||||
function count(value) {
|
||||
return Math.max(0, Number(value) || 0);
|
||||
}
|
||||
|
||||
function itemIdentity(item) {
|
||||
if (item === null || item === undefined) return '';
|
||||
if (typeof item !== 'object') return String(item);
|
||||
const explicit = item.outbox_id || item.id || item.key || item.url;
|
||||
if (explicit !== null && explicit !== undefined && String(explicit)) {
|
||||
return String(item.kind || 'item') + ':' + String(explicit);
|
||||
}
|
||||
if (!anonymousItems.has(item)) anonymousItems.set(item, 'anonymous:' + (++anonymousItemSequence));
|
||||
return anonymousItems.get(item);
|
||||
}
|
||||
|
||||
function reviewPhases(counts) {
|
||||
if (!options.getPhaseItems) {
|
||||
return reviewOrder
|
||||
.map(([name, label]) => ({name, label, count: count(counts[name])}))
|
||||
.filter(phase => phase.count > 0);
|
||||
}
|
||||
const items = options.getPhaseItems() || {};
|
||||
const seen = new Set();
|
||||
return reviewOrder.flatMap(([name, label]) => {
|
||||
let phaseCount = 0;
|
||||
(items[name] || []).forEach(item => {
|
||||
const identity = itemIdentity(item);
|
||||
if (!identity || seen.has(identity)) return;
|
||||
seen.add(identity);
|
||||
phaseCount += 1;
|
||||
});
|
||||
return phaseCount ? [{name, label, count:phaseCount}] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function localDay() {
|
||||
const now = new Date();
|
||||
const pad = value => String(value).padStart(2, '0');
|
||||
@@ -69,12 +102,10 @@
|
||||
|
||||
function briefing() {
|
||||
const counts = options.getCounts ? options.getCounts() : {};
|
||||
const phases = reviewOrder
|
||||
.map(([name, label]) => ({name, label, count: count(counts[name])}))
|
||||
.filter(phase => phase.count > 0);
|
||||
const phases = reviewPhases(counts);
|
||||
const total = phases.reduce((sum, phase) => sum + phase.count, 0);
|
||||
const today = count(counts.today);
|
||||
const delivery = count(counts.delivery);
|
||||
const delivery = phases.find(phase => phase.name === 'delivery')?.count || 0;
|
||||
const other = total - delivery;
|
||||
const next = phases.length ? phases[0].name : (today ? 'today' : 'find');
|
||||
const nextLabel = next === 'delivery' ? 'Review Delivery' :
|
||||
|
||||
@@ -66,13 +66,16 @@
|
||||
function updateWork(mode) {
|
||||
const text = {
|
||||
continue:'Continue', resume:'Resume', start:'Start', plan:'Plan', find:'Find',
|
||||
prepare:'Prepare', 'prepare-resume':'Resume prep',
|
||||
delivery:'Delivery', attention:'Attention', update:'Updates', agenda:'Agenda', filed:'Filed', later:'Later', draft:'Drafts',
|
||||
}[mode] || 'Work';
|
||||
const queue = ['Delivery', 'Attention', 'Updates', 'Agenda', 'Filed', 'Later', 'Drafts'].includes(text);
|
||||
if (options.workLabel) options.workLabel.textContent = text;
|
||||
if (buttons.work) buttons.work.setAttribute('aria-label', queue
|
||||
? (mode === 'update' ? 'Resume ' : 'Open ') + text
|
||||
: mode === 'find' ? 'Find work' : text + (mode === 'work' ? '' : ' Today'));
|
||||
const actionLabel = mode === 'prepare' ? 'Prepare Today' :
|
||||
mode === 'prepare-resume' ? 'Resume preparation' :
|
||||
queue ? (mode === 'update' ? 'Resume ' : 'Open ') + text :
|
||||
mode === 'find' ? 'Find work' : text + (mode === 'work' ? '' : ' Today');
|
||||
if (buttons.work) buttons.work.setAttribute('aria-label', actionLabel);
|
||||
}
|
||||
|
||||
function updateAttention(count) {
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
})(typeof self !== 'undefined' ? self : this, function createMobileWorkEntry(options) {
|
||||
function mode() {
|
||||
if (options.isTodayActive()) return 'continue';
|
||||
const preparation = options.getPreparationState?.();
|
||||
if (preparation?.active) return 'prepare-resume';
|
||||
if (preparation?.next && !['today', 'find'].includes(preparation.next)) return 'prepare';
|
||||
const recommended = options.queueLauncher && options.queueLauncher.recommend();
|
||||
if (recommended && !['today', 'find'].includes(recommended.name)) return recommended.name;
|
||||
if (options.getTodayCount() > 0 && options.isTodayResumable()) return 'resume';
|
||||
@@ -15,6 +18,7 @@
|
||||
function open() {
|
||||
const current = mode();
|
||||
if (current === 'continue') options.continueToday();
|
||||
else if (['prepare', 'prepare-resume'].includes(current)) options.prepareToday();
|
||||
else if (current === 'resume') options.resumeToday();
|
||||
else if (current === 'start') options.startToday();
|
||||
else if (current === 'plan') options.planToday();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const BASE = new URL('./', self.location.href).pathname;
|
||||
importScripts(BASE + 'static/private-data-registry.js');
|
||||
importScripts(BASE + 'static/background-issue-sync.js');
|
||||
const CACHE = 'stackchain-dashboard-shell-v117';
|
||||
const CACHE = 'stackchain-dashboard-shell-v120';
|
||||
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;
|
||||
@@ -51,6 +51,9 @@ const SHELL = [
|
||||
BASE + 'static/work-selection.js',
|
||||
BASE + 'static/today-work.js',
|
||||
BASE + 'static/today-timer.js',
|
||||
BASE + 'static/today-break.js',
|
||||
BASE + 'static/today-lock-screen.js',
|
||||
BASE + 'static/today-session-sync.js',
|
||||
BASE + 'static/today-recap.js',
|
||||
BASE + 'static/today-wrap-up.js',
|
||||
BASE + 'static/today-handoff.js',
|
||||
@@ -418,6 +421,27 @@ self.addEventListener('sync', event => {
|
||||
if (event.tag === 'stackchain-issue-outbox-v1') event.waitUntil(flushAndNotify());
|
||||
});
|
||||
|
||||
async function updateTodayLockScreen(active, running, rawActionToken = '') {
|
||||
const tag = 'stackchain-today-session';
|
||||
if (!active) {
|
||||
const notifications = await self.registration.getNotifications({ tag });
|
||||
notifications.forEach(notification => notification.close());
|
||||
return;
|
||||
}
|
||||
const actionToken = /^[A-Za-z0-9_-]{16,128}$/.test(rawActionToken) ? rawActionToken : '';
|
||||
await self.registration.showNotification(running ? 'Today session running' : 'Today session paused', {
|
||||
body: running ? 'Your active Today timer is running.' : 'Your active Today timer is paused.',
|
||||
tag,
|
||||
renotify:false,
|
||||
silent:true,
|
||||
actions: [
|
||||
{ action:running ? 'pause-today' : 'resume-today', title:running ? 'Pause' : 'Resume' },
|
||||
...(actionToken ? [{ action:'finish-today', title:'Finish current' }] : []),
|
||||
],
|
||||
data: { route:'#/my-work/today', ...(actionToken ? { actionToken } : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
self.addEventListener('message', event => {
|
||||
if (event.data?.type === 'stackchain-resume-outbox') event.waitUntil((async () => {
|
||||
await issueSync.resume();
|
||||
@@ -430,11 +454,19 @@ self.addEventListener('message', event => {
|
||||
try {
|
||||
await issueSync.purge();
|
||||
await deletePrivateDatabases();
|
||||
await updateTodayLockScreen(false, false);
|
||||
event.ports?.[0]?.postMessage({ ok: true });
|
||||
} catch (error) {
|
||||
event.ports?.[0]?.postMessage({ ok: false, error: String(error?.message || 'Outbox purge failed.') });
|
||||
}
|
||||
})());
|
||||
if (event.data?.type === 'stackchain-today-lock-screen') {
|
||||
event.waitUntil(updateTodayLockScreen(
|
||||
event.data.active === true,
|
||||
event.data.running === true,
|
||||
String(event.data.actionToken || '')
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener('push', event => {
|
||||
@@ -527,9 +559,43 @@ async function openCanonicalIssueUrl(rawUrl) {
|
||||
return client.focus();
|
||||
}
|
||||
|
||||
async function applyTodayTimerAction(action, actionToken = '') {
|
||||
if (!['pause', 'resume', 'complete'].includes(action)) return;
|
||||
if (action === 'complete' && !/^[A-Za-z0-9_-]{16,128}$/.test(actionToken)) return;
|
||||
const route = '#/my-work/today';
|
||||
const windows = await self.clients.matchAll({ type:'window', includeUncontrolled:true });
|
||||
const client = windows.find(candidate => candidate.url.startsWith(self.location.origin + BASE));
|
||||
if (client) {
|
||||
client.postMessage?.({
|
||||
type:'stackchain-today-timer-action', action,
|
||||
...(action === 'complete' ? { actionToken } : {}),
|
||||
});
|
||||
return client.focus?.();
|
||||
}
|
||||
const query = '?today_timer_action=' + action +
|
||||
(action === 'complete' ? '&today_action_token=' + encodeURIComponent(actionToken) : '');
|
||||
const target = new URL(BASE + query + route, self.location.origin).href;
|
||||
return self.clients.openWindow(target);
|
||||
}
|
||||
|
||||
self.addEventListener('notificationclick', event => {
|
||||
const route = String(event.notification.data?.route || '');
|
||||
const issueUrl = String(event.notification.data?.url || '');
|
||||
if (
|
||||
event.notification.tag === 'stackchain-today-session'
|
||||
&& route === '#/my-work/today'
|
||||
&& ['pause-today', 'resume-today', 'finish-today', 'open-today', ''].includes(event.action)
|
||||
) {
|
||||
event.notification.close();
|
||||
if (['pause-today', 'resume-today', 'finish-today'].includes(event.action)) {
|
||||
const action = event.action === 'pause-today' ? 'pause' :
|
||||
event.action === 'resume-today' ? 'resume' : 'complete';
|
||||
event.waitUntil(applyTodayTimerAction(action, String(event.notification.data?.actionToken || '')));
|
||||
} else {
|
||||
event.waitUntil(openWorkRoute(route));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (issueUrl) {
|
||||
event.notification.close();
|
||||
event.waitUntil(openCanonicalIssueUrl(issueUrl));
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
function createTodayBreak({
|
||||
timer, sheet, openButtons = null, cancelButton, presetButtons = null, form = null,
|
||||
minutesInput = null, error = null, status, resumeButton,
|
||||
qs = null, queryAll = null,
|
||||
historyRef = null, windowRef = null,
|
||||
now = () => Date.now(), setIntervalRef = setInterval, clearIntervalRef = clearInterval,
|
||||
onChange = () => {}, onResume = () => {},
|
||||
}) {
|
||||
queryAll ||= selector => globalThis.document?.querySelectorAll(selector) || [];
|
||||
historyRef ||= globalThis.history;
|
||||
windowRef ||= globalThis.window;
|
||||
sheet ||= qs?.('#today-break-sheet');
|
||||
openButtons ||= queryAll?.('[data-today-break-open]') || [];
|
||||
cancelButton ||= qs?.('#cancel-today-break');
|
||||
presetButtons ||= queryAll?.('[data-today-break-minutes]') || [];
|
||||
form ||= qs?.('#today-break-custom-form');
|
||||
minutesInput ||= qs?.('#today-break-custom-minutes');
|
||||
error ||= qs?.('#today-break-error');
|
||||
status ||= qs?.('#today-break-status');
|
||||
resumeButton ||= qs?.('#resume-today-break');
|
||||
let ticker = null;
|
||||
let historyEntry = false;
|
||||
|
||||
const stopTicker = () => {
|
||||
if (ticker !== null) clearIntervalRef(ticker);
|
||||
ticker = null;
|
||||
};
|
||||
const render = () => {
|
||||
const pending = timer.breakSnapshot();
|
||||
if (!pending) {
|
||||
stopTicker();
|
||||
status.hidden = true;
|
||||
resumeButton.hidden = true;
|
||||
openButtons.forEach(button => { button.hidden = false; });
|
||||
return false;
|
||||
}
|
||||
status.hidden = false;
|
||||
resumeButton.hidden = false;
|
||||
openButtons.forEach(button => { button.hidden = true; });
|
||||
const remaining = Math.max(0, pending.deadline_at - now());
|
||||
if (pending.expired || remaining <= 0) {
|
||||
status.textContent = 'Break over · ready to resume';
|
||||
} else {
|
||||
const seconds = Math.ceil(remaining / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
status.textContent = 'On break · resume in ' + minutes + ':' + String(seconds % 60).padStart(2, '0');
|
||||
}
|
||||
if (ticker === null) ticker = setIntervalRef(render, 1000);
|
||||
return true;
|
||||
};
|
||||
const close = () => {
|
||||
if (sheet.open) sheet.close();
|
||||
if (historyEntry) {
|
||||
historyEntry = false;
|
||||
historyRef?.back();
|
||||
}
|
||||
};
|
||||
const start = minutes => {
|
||||
if (!timer.startBreak(Number(minutes))) return false;
|
||||
if (error) error.textContent = '';
|
||||
close();
|
||||
render();
|
||||
onChange();
|
||||
return true;
|
||||
};
|
||||
const open = () => {
|
||||
if (!timer.snapshot().identity) return false;
|
||||
if (!sheet.open) {
|
||||
sheet.showModal();
|
||||
if (historyRef) {
|
||||
historyRef.pushState({...(historyRef.state || {}), todayBreak:true}, '');
|
||||
historyEntry = true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
openButtons.forEach(button => button.addEventListener('click', open));
|
||||
cancelButton?.addEventListener('click', close);
|
||||
windowRef?.addEventListener('popstate', () => {
|
||||
historyEntry = false;
|
||||
if (sheet.open) sheet.close();
|
||||
});
|
||||
presetButtons.forEach(button => button.addEventListener('click', () =>
|
||||
start(button.dataset.todayBreakMinutes)
|
||||
));
|
||||
form?.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
if (!start(Number(minutesInput?.value))) {
|
||||
if (error) error.textContent = 'Choose a whole number from 1 to 120 minutes.';
|
||||
minutesInput?.focus();
|
||||
}
|
||||
});
|
||||
resumeButton.addEventListener('click', () => {
|
||||
const pending = timer.breakSnapshot();
|
||||
if (!timer.resumeBreak()) return;
|
||||
onResume(pending.identity);
|
||||
render();
|
||||
onChange();
|
||||
});
|
||||
render();
|
||||
|
||||
return { open, close, start, render };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createTodayBreak;
|
||||
@@ -1,6 +1,25 @@
|
||||
function createTodayCompletion({ todayWork, todaySync, workSession, refresh, warm, announce, advance = null }) {
|
||||
return function completeTodayItem(item, options = {}) {
|
||||
if (!item || !todayWork.remove(item)) {
|
||||
function createTodayCompletion({ todayWork, todaySync, workSession, refresh, warm, announce, advance = null,
|
||||
now = Date.now, ttlMs = 10000, onOffer = null, onClear = null,
|
||||
setTimer = globalThis.setTimeout, clearTimer = globalThis.clearTimeout,
|
||||
undo = [globalThis.document?.getElementById('today-completion-undo'),
|
||||
globalThis.document?.getElementById('undo-today-completion')] }) {
|
||||
const [undoReceipt, undoControl] = undo;
|
||||
let pending = null;
|
||||
let expiryTimer = null;
|
||||
|
||||
function clear() {
|
||||
if (expiryTimer !== null) clearTimer?.(expiryTimer);
|
||||
expiryTimer = null;
|
||||
pending = null;
|
||||
if (undoReceipt) undoReceipt.hidden = true;
|
||||
onClear?.();
|
||||
}
|
||||
|
||||
function completeTodayItem(item, options = {}) {
|
||||
const identity = item && todayWork.identity(item);
|
||||
const snapshot = item && (todayWork.capture?.(item) ||
|
||||
(identity ? { id: identity, index: 0, ids: [identity], plan: { capacity_minutes: null, estimates: {} } } : null));
|
||||
if (!snapshot || !todayWork.remove(item)) {
|
||||
announce(options.failureMessage || 'Could not update Today on this device. Try again.');
|
||||
return false;
|
||||
}
|
||||
@@ -10,8 +29,51 @@ function createTodayCompletion({ todayWork, todaySync, workSession, refresh, war
|
||||
warm();
|
||||
(advance || (() => workSession.complete()))();
|
||||
announce(options.successMessage || 'Done for Today. The Gitea item is unchanged.');
|
||||
pending = { snapshot, expires_at: now() + ttlMs };
|
||||
if (undoReceipt) undoReceipt.hidden = false;
|
||||
if (undoControl) undoControl.disabled = false;
|
||||
onOffer?.({ identity: snapshot.id, expires_at: pending.expires_at });
|
||||
expiryTimer = setTimer?.(clear, ttlMs) ?? null;
|
||||
expiryTimer?.unref?.();
|
||||
return true;
|
||||
}
|
||||
|
||||
completeTodayItem.undo = () => {
|
||||
if (!pending) return 'missing';
|
||||
if (now() >= pending.expires_at) {
|
||||
clear();
|
||||
announce('Undo expired. Add the item back to Today from My Work.');
|
||||
return 'expired';
|
||||
}
|
||||
const snapshot = pending.snapshot;
|
||||
const result = todayWork.restore?.(snapshot) || 'unavailable';
|
||||
if (result !== 'restored') {
|
||||
const messages = {
|
||||
full: 'Today is full. Remove another item before adding this work back.',
|
||||
changed: 'Today changed on this device. Add the item back from My Work.',
|
||||
unavailable: 'Could not restore Today on this device. Add the item back from My Work.',
|
||||
};
|
||||
clear();
|
||||
announce(messages[result] || messages.unavailable);
|
||||
return result;
|
||||
}
|
||||
todaySync.enqueue('add', snapshot.id);
|
||||
for (let index = snapshot.ids.length - 1; index > snapshot.index; index -= 1) {
|
||||
todaySync.enqueue('move', snapshot.id, 'up');
|
||||
}
|
||||
todaySync.flush();
|
||||
refresh();
|
||||
warm();
|
||||
clear();
|
||||
announce('Restored to Today. Your current work session is unchanged.');
|
||||
return 'restored';
|
||||
};
|
||||
completeTodayItem.clear = clear;
|
||||
undoControl?.addEventListener?.('click', () => {
|
||||
undoControl.disabled = true;
|
||||
if (completeTodayItem.undo() !== 'restored') undoControl.disabled = false;
|
||||
});
|
||||
return completeTodayItem;
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createTodayCompletion;
|
||||
@@ -0,0 +1,170 @@
|
||||
function createTodayLockScreen({
|
||||
storage,
|
||||
getLogin,
|
||||
serviceWorker,
|
||||
NotificationRef,
|
||||
control,
|
||||
status,
|
||||
locationRef,
|
||||
historyRef,
|
||||
randomToken = () => {
|
||||
const bytes = new Uint8Array(16);
|
||||
globalThis.crypto.getRandomValues(bytes);
|
||||
return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
||||
},
|
||||
fingerprint = async (token, identity) => {
|
||||
const input = new TextEncoder().encode(token + '\0' + identity);
|
||||
const digest = await globalThis.crypto.subtle.digest('SHA-256', input);
|
||||
return Array.from(new Uint8Array(digest), value =>
|
||||
value.toString(16).padStart(2, '0')).join('');
|
||||
},
|
||||
onAction = () => {},
|
||||
}) {
|
||||
let activeIdentity = '';
|
||||
const preferenceKey = () => {
|
||||
const login = String(getLogin?.() || '').trim().toLowerCase();
|
||||
return login ? 'stackchain.today-lock-screen.v1.' + encodeURIComponent(login) : '';
|
||||
};
|
||||
const supported = Boolean(serviceWorker && NotificationRef);
|
||||
const actionKey = () => {
|
||||
const login = String(getLogin?.() || '').trim().toLowerCase();
|
||||
return login ? 'stackchain.today-lock-screen-action.v1.' + encodeURIComponent(login) : '';
|
||||
};
|
||||
const readAction = () => {
|
||||
const key = actionKey();
|
||||
if (!key) return null;
|
||||
try {
|
||||
const value = JSON.parse(storage?.getItem(key) || 'null');
|
||||
return typeof value?.token === 'string' && value.token &&
|
||||
typeof value.fingerprint === 'string' && value.fingerprint ? value : null;
|
||||
} catch (_error) { return null; }
|
||||
};
|
||||
const clearAction = () => {
|
||||
const key = actionKey();
|
||||
try { if (key) storage?.removeItem(key); }
|
||||
catch (_error) { return false; }
|
||||
return true;
|
||||
};
|
||||
const actionFor = async identity => {
|
||||
const existing = readAction();
|
||||
if (existing && await fingerprint(existing.token, identity) === existing.fingerprint) return existing;
|
||||
const key = actionKey();
|
||||
if (!key) return null;
|
||||
try {
|
||||
const token = String(randomToken() || '');
|
||||
const value = { token, fingerprint:token ? await fingerprint(token, identity) : '' };
|
||||
if (!value.token) return null;
|
||||
storage?.setItem(key, JSON.stringify(value));
|
||||
return value;
|
||||
} catch (_error) { return null; }
|
||||
};
|
||||
const enabled = () => {
|
||||
const key = preferenceKey();
|
||||
return Boolean(key && storage?.getItem(key) === '1');
|
||||
};
|
||||
const setStatus = message => {
|
||||
if (status) status.textContent = message;
|
||||
};
|
||||
const post = async message => {
|
||||
const target = serviceWorker?.controller || (await serviceWorker?.ready)?.active;
|
||||
target?.postMessage?.(message);
|
||||
};
|
||||
const hide = () => post({
|
||||
type:'stackchain-today-lock-screen', active:false, running:false,
|
||||
});
|
||||
const render = () => {
|
||||
if (control) {
|
||||
control.checked = enabled();
|
||||
control.disabled = !supported;
|
||||
}
|
||||
if (!supported) setStatus('Lock-screen controls are not supported on this device.');
|
||||
else if (enabled()) setStatus('Lock-screen Today controls are on.');
|
||||
};
|
||||
const consumeAction = async (action, token = '') => {
|
||||
if (!enabled() || !['pause', 'resume', 'complete'].includes(action)) return false;
|
||||
if (action !== 'complete') {
|
||||
onAction(action, null);
|
||||
return true;
|
||||
}
|
||||
const pending = readAction();
|
||||
if (!pending || !token || !activeIdentity || pending.token !== token ||
|
||||
await fingerprint(token, activeIdentity) !== pending.fingerprint) return false;
|
||||
if (!clearAction()) return false;
|
||||
onAction(action, activeIdentity);
|
||||
return true;
|
||||
};
|
||||
const api = {
|
||||
enabled,
|
||||
async enable() {
|
||||
if (!supported) {
|
||||
render();
|
||||
return false;
|
||||
}
|
||||
const permission = NotificationRef.permission === 'granted' ?
|
||||
'granted' : await NotificationRef.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
if (control) control.checked = false;
|
||||
setStatus(permission === 'denied' ?
|
||||
'Lock-screen controls are blocked in browser settings.' :
|
||||
'Lock-screen controls were not enabled.');
|
||||
return false;
|
||||
}
|
||||
const key = preferenceKey();
|
||||
if (!key) return false;
|
||||
storage?.setItem(key, '1');
|
||||
render();
|
||||
return true;
|
||||
},
|
||||
async disable() {
|
||||
const key = preferenceKey();
|
||||
if (key) storage?.removeItem(key);
|
||||
clearAction();
|
||||
if (control) control.checked = false;
|
||||
setStatus('Lock-screen Today controls are off.');
|
||||
await hide();
|
||||
return true;
|
||||
},
|
||||
async sync(snapshot, active) {
|
||||
if (!enabled() || NotificationRef?.permission !== 'granted') return false;
|
||||
const visible = Boolean(active && snapshot?.identity);
|
||||
activeIdentity = visible ? snapshot.identity : '';
|
||||
const pending = visible ? await actionFor(activeIdentity) : null;
|
||||
if (!visible) clearAction();
|
||||
await post({
|
||||
type:'stackchain-today-lock-screen',
|
||||
active:visible,
|
||||
running:visible && Boolean(snapshot.running),
|
||||
...(pending?.token ? { actionToken:pending.token } : {}),
|
||||
});
|
||||
if (visible && !pending) setStatus('Finish current is unavailable because its one-time action could not be saved.');
|
||||
return true;
|
||||
},
|
||||
consumeAction,
|
||||
async consumeLaunchAction() {
|
||||
let url;
|
||||
try { url = new URL(locationRef?.href || ''); }
|
||||
catch (_error) { return false; }
|
||||
const action = url.searchParams.get('today_timer_action');
|
||||
if (!['pause', 'resume', 'complete'].includes(action)) return false;
|
||||
const token = url.searchParams.get('today_action_token') || '';
|
||||
url.searchParams.delete('today_timer_action');
|
||||
url.searchParams.delete('today_action_token');
|
||||
historyRef?.replaceState?.(null, '', url.pathname + url.search + url.hash);
|
||||
return await consumeAction(action, token);
|
||||
},
|
||||
render,
|
||||
};
|
||||
control?.addEventListener?.('change', () => {
|
||||
if (control.checked) api.enable();
|
||||
else api.disable();
|
||||
});
|
||||
serviceWorker?.addEventListener?.('message', event => {
|
||||
if (event.data?.type === 'stackchain-today-timer-action') {
|
||||
consumeAction(String(event.data.action || ''), String(event.data.actionToken || ''));
|
||||
}
|
||||
});
|
||||
render();
|
||||
return api;
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createTodayLockScreen;
|
||||
@@ -0,0 +1,225 @@
|
||||
function createTodaySessionSync({
|
||||
fetchJson, getDeviceId, timer, onRemote = () => {}, onTransferred = () => {}, onStatus = () => {},
|
||||
setInterval = globalThis.setInterval, clearInterval = globalThis.clearInterval,
|
||||
}) {
|
||||
let current = null;
|
||||
let ownedRevision = 0;
|
||||
let pollTimer = null;
|
||||
let requestTail = Promise.resolve();
|
||||
let latestSnapshot = null;
|
||||
let publishRequested = 0;
|
||||
let publishSent = 0;
|
||||
const endpoint = 'api/v1/today/session';
|
||||
const deviceId = () => String(getDeviceId?.() || '').trim();
|
||||
|
||||
function serialize(operation) {
|
||||
const result = requestTail.then(operation, operation);
|
||||
requestTail = result.catch(() => null);
|
||||
return result;
|
||||
}
|
||||
|
||||
function adopt(session) {
|
||||
if (!session || !Number.isInteger(session.revision)) return null;
|
||||
const previousOwned = current?.device_id === deviceId() &&
|
||||
(current?.running || Number.isFinite(current?.break_deadline_at));
|
||||
current = session;
|
||||
if (session.device_id === deviceId()) {
|
||||
ownedRevision = session.revision;
|
||||
onRemote(null);
|
||||
} else if ((session.running || Number.isFinite(session.break_deadline_at)) && session.identity) {
|
||||
if (previousOwned) {
|
||||
timer?.pause?.();
|
||||
onTransferred(session);
|
||||
}
|
||||
onRemote(session);
|
||||
} else {
|
||||
onRemote(null);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
async function refreshNow() {
|
||||
try {
|
||||
onStatus('syncing');
|
||||
const session = await fetchJson(endpoint);
|
||||
onStatus('online');
|
||||
return adopt(session);
|
||||
} catch (error) {
|
||||
onStatus('offline', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const refresh = () => serialize(refreshNow);
|
||||
|
||||
function claim() {
|
||||
return serialize(async () => {
|
||||
if ((!current?.running && !Number.isFinite(current?.break_deadline_at)) ||
|
||||
!current.identity || current.device_id === deviceId() || !deviceId()) return null;
|
||||
try {
|
||||
onStatus('syncing');
|
||||
const body = {
|
||||
base_revision:current.revision, device_id:deviceId(), identity:current.identity,
|
||||
elapsed_ms:current.elapsed_ms, running:true,
|
||||
};
|
||||
if (Object.hasOwn(current, 'break_deadline_at')) body.break_deadline_at = null;
|
||||
const session = await fetchJson(endpoint, {
|
||||
method:'PATCH', headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify(body),
|
||||
});
|
||||
adopt(session);
|
||||
timer?.adopt?.(session.identity, session.elapsed_ms, session.running);
|
||||
return session;
|
||||
} catch (error) {
|
||||
if (error?.status === 409 || error?.code === 'session_changed') {
|
||||
onStatus('conflict', error);
|
||||
await refreshNow();
|
||||
} else {
|
||||
onStatus('offline', error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function publishNow(snapshot) {
|
||||
if (!snapshot?.identity || !deviceId()) return null;
|
||||
try {
|
||||
onStatus('syncing');
|
||||
const body = {
|
||||
base_revision:ownedRevision, device_id:deviceId(), identity:snapshot.identity,
|
||||
elapsed_ms:Math.max(0, Math.floor(Number(snapshot.elapsed_ms) || 0)),
|
||||
running:Boolean(snapshot.running),
|
||||
};
|
||||
if (Object.hasOwn(snapshot, 'break_deadline_at') || Object.hasOwn(current || {}, 'break_deadline_at')) {
|
||||
body.break_deadline_at = Number.isFinite(snapshot.break_deadline_at) ?
|
||||
Math.floor(snapshot.break_deadline_at) : null;
|
||||
}
|
||||
const session = await fetchJson(endpoint, {
|
||||
method:'PATCH', headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify(body),
|
||||
});
|
||||
adopt(session);
|
||||
return session;
|
||||
} catch (error) {
|
||||
if (error?.status === 409 || error?.code === 'session_changed') {
|
||||
onStatus('conflict', error);
|
||||
await refreshNow();
|
||||
} else {
|
||||
onStatus('offline', error);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function publish(snapshot = timer?.snapshot?.()) {
|
||||
snapshot = snapshot?.identity ? snapshot : latestSnapshot;
|
||||
if (!snapshot?.identity || !deviceId()) return Promise.resolve(null);
|
||||
latestSnapshot = snapshot;
|
||||
publishRequested += 1;
|
||||
return serialize(async () => {
|
||||
if (publishSent === publishRequested) return current;
|
||||
if (current?.device_id && current.device_id !== deviceId()) {
|
||||
publishSent = publishRequested;
|
||||
return current;
|
||||
}
|
||||
const version = publishRequested;
|
||||
const result = await publishNow(latestSnapshot);
|
||||
publishSent = current?.device_id && current.device_id !== deviceId()
|
||||
? publishRequested
|
||||
: version;
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
const pulse = () => current?.device_id === deviceId() && current?.running
|
||||
? publish()
|
||||
: refresh();
|
||||
|
||||
return {
|
||||
refresh, claim, publish,
|
||||
session:() => current,
|
||||
start(intervalMs = 15000) {
|
||||
if (pollTimer !== null) return false;
|
||||
pulse();
|
||||
pollTimer = setInterval?.(pulse, intervalMs);
|
||||
pollTimer?.unref?.();
|
||||
return true;
|
||||
},
|
||||
stop() {
|
||||
if (pollTimer === null) return false;
|
||||
clearInterval?.(pollTimer);
|
||||
pollTimer = null;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function todaySessionHandoffSummary(session, item) {
|
||||
if (Number.isFinite(session?.break_deadline_at)) {
|
||||
const end = new Date(session.break_deadline_at).toLocaleTimeString([], {
|
||||
hour:'numeric', minute:'2-digit',
|
||||
});
|
||||
return `On break until ${end} · ready to resume here`;
|
||||
}
|
||||
const minutes = Math.max(0, Math.floor(Number(session?.elapsed_ms || 0) / 60000));
|
||||
return `${item?.title || 'Current Today item'} · ${minutes} min elapsed`;
|
||||
}
|
||||
|
||||
function attachTodaySessionHandoff({
|
||||
fetchJson, storage, timer, qs, items, identity, selectToday, startItem, announce, renderTimer,
|
||||
}) {
|
||||
const deviceKey = 'stackchain.today-session-device.v1';
|
||||
const getDeviceId = () => {
|
||||
let value = storage.getItem(deviceKey);
|
||||
if (!value) {
|
||||
value = globalThis.crypto?.randomUUID?.() || Math.random().toString(36).slice(2);
|
||||
storage.setItem(deviceKey, value);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
let offered = null;
|
||||
const sessionStatus = qs('#today-session-sync-status');
|
||||
const showSessionStatus = message => {
|
||||
sessionStatus.textContent = message;
|
||||
sessionStatus.hidden = !message;
|
||||
};
|
||||
const sync = createTodaySessionSync({
|
||||
fetchJson, getDeviceId, timer,
|
||||
onStatus:state => showSessionStatus(
|
||||
state === 'syncing' ? 'Session syncing…' :
|
||||
(state === 'offline' ? 'Session offline · will retry.' : '')
|
||||
),
|
||||
onRemote:session => {
|
||||
offered = session;
|
||||
const handoff = qs('#today-session-handoff');
|
||||
handoff.hidden = !session;
|
||||
if (!session) return;
|
||||
const item = items().find(entry => identity(entry) === session.identity);
|
||||
qs('#today-session-handoff-summary').textContent = todaySessionHandoffSummary(session, item);
|
||||
qs('#continue-today-session').textContent = Number.isFinite(session.break_deadline_at) ?
|
||||
'Resume Today here' : 'Continue here';
|
||||
},
|
||||
onTransferred:() => {
|
||||
showSessionStatus('Session continued on another device.');
|
||||
announce('Today continued on another device. Timer paused here.');
|
||||
renderTimer();
|
||||
},
|
||||
});
|
||||
qs('#continue-today-session').addEventListener('click', async () => {
|
||||
const target = offered;
|
||||
const claimed = await sync.claim();
|
||||
if (!claimed || !target) return;
|
||||
selectToday();
|
||||
const item = items().find(entry => identity(entry) === claimed.identity);
|
||||
if (item) startItem(item);
|
||||
else announce('Today session moved here; refresh work to open its item.');
|
||||
renderTimer();
|
||||
});
|
||||
sync.start(5000);
|
||||
return sync;
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = {
|
||||
createTodaySessionSync, attachTodaySessionHandoff, todaySessionHandoffSummary,
|
||||
};
|
||||
+38
-9
@@ -10,6 +10,8 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
|
||||
let retryTimer = null;
|
||||
let retryAttempt = 0;
|
||||
let expiredCount = 0;
|
||||
let discardedCount = 0;
|
||||
let recoveryNotice = { discarded: 0, until: 0 };
|
||||
const knownOperationKeys = new Set();
|
||||
|
||||
function cancelRetry() {
|
||||
@@ -108,10 +110,28 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
|
||||
const candidate = storage.key?.(index);
|
||||
if (candidate?.startsWith(recordPrefix)) keys.add(candidate);
|
||||
}
|
||||
const records = [...keys].map(recordKey => {
|
||||
const record = JSON.parse(storage.getItem(recordKey) || 'null');
|
||||
return record ? { ...record, recordKey } : null;
|
||||
}).filter(record => record?.operation);
|
||||
const records = [];
|
||||
for (const recordKey of keys) {
|
||||
let record;
|
||||
try {
|
||||
record = JSON.parse(storage.getItem(recordKey) || 'null');
|
||||
} catch (_error) {
|
||||
storage.removeItem(recordKey);
|
||||
knownOperationKeys.delete(recordKey);
|
||||
discardedCount += 1;
|
||||
continue;
|
||||
}
|
||||
const operation = record?.operation;
|
||||
const valid = operation && typeof operation.operation_id === 'string' &&
|
||||
['add', 'remove', 'move', 'configure', 'rollover'].includes(operation.action) &&
|
||||
typeof operation.item_id === 'string' && Number.isFinite(Number(record.queued_at));
|
||||
if (valid) records.push({ ...record, recordKey });
|
||||
else {
|
||||
storage.removeItem(recordKey);
|
||||
knownOperationKeys.delete(recordKey);
|
||||
discardedCount += 1;
|
||||
}
|
||||
}
|
||||
const expired = records.filter(record => Number(record.queued_at) >= 1_000_000_000_000 &&
|
||||
now() - Number(record.queued_at) > maxOfflineMs);
|
||||
expired.forEach(record => {
|
||||
@@ -173,7 +193,7 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
|
||||
const recordKey = storageKey + '.operation.' + encodeURIComponent(operation.operation_id);
|
||||
let saved = false;
|
||||
try {
|
||||
storage.setItem(recordKey, JSON.stringify({ operation, queued_at: now() }));
|
||||
storage.setItem(recordKey, JSON.stringify({ operation, queued_at: now() + operations.length }));
|
||||
knownOperationKeys.add(recordKey);
|
||||
saved = true;
|
||||
coordinator?.notify('today');
|
||||
@@ -272,14 +292,23 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
|
||||
operations = pending();
|
||||
}
|
||||
adopt(plan);
|
||||
onStatus?.(pending().length ? 'pending' : hadConflict ? 'full' :
|
||||
expiredCount ? 'expired' : 'saved', expiredCount ? { count: expiredCount } : {});
|
||||
const stillPending = pending().length;
|
||||
if (discardedCount) recoveryNotice = { discarded: discardedCount, until: now() + 5000 };
|
||||
const recovered = recoveryNotice.until > now() ? recoveryNotice.discarded : 0;
|
||||
onStatus?.(stillPending ? 'pending' : hadConflict ? 'full' :
|
||||
expiredCount ? 'expired' : recovered ? 'recovered' : 'saved',
|
||||
expiredCount ? { count: expiredCount } : recovered ? { discarded: recovered } : {});
|
||||
if (!stillPending) discardedCount = 0;
|
||||
retryAttempt = 0;
|
||||
cancelRetry();
|
||||
return !hadConflict;
|
||||
} catch (error) {
|
||||
if (pending().length) scheduleRetry(error, ownerKey);
|
||||
else onStatus?.('error');
|
||||
const stillPending = pending().length;
|
||||
if (discardedCount) recoveryNotice = { discarded: discardedCount, until: now() + 5000 };
|
||||
const recovered = recoveryNotice.until > now() ? recoveryNotice.discarded : 0;
|
||||
if (stillPending) scheduleRetry(error, ownerKey);
|
||||
else onStatus?.(recovered ? 'recovered' : 'error', recovered ? { discarded: recovered } : {});
|
||||
discardedCount = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+71
-7
@@ -1,11 +1,11 @@
|
||||
function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
function createTodayTimer({ storage, getLogin, now = () => Date.now(), onChange = () => {} }) {
|
||||
const key = () => {
|
||||
const login = String(getLogin?.() || '').trim().toLowerCase();
|
||||
return login ? 'stackchain.today-timer.v1.' + encodeURIComponent(login) : '';
|
||||
};
|
||||
const empty = () => ({
|
||||
version:1, active_identity:'', entries:{}, away_at:null,
|
||||
pending_interruption:null, attention_interruption:null,
|
||||
pending_interruption:null, attention_interruption:null, timed_break:null,
|
||||
});
|
||||
const read = () => {
|
||||
const ownerKey = key();
|
||||
@@ -24,6 +24,7 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
if (!ownerKey || !storage) return false;
|
||||
try {
|
||||
storage.setItem(ownerKey, JSON.stringify(state));
|
||||
onChange(snapshot());
|
||||
return true;
|
||||
} catch (_error) {
|
||||
return false;
|
||||
@@ -41,6 +42,12 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
typeof pending.resume === 'boolean' ?
|
||||
{ identity:pending.identity, resume:pending.resume } : null;
|
||||
};
|
||||
const validBreak = state => {
|
||||
const value = state.timed_break;
|
||||
return value && typeof value.identity === 'string' && value.identity &&
|
||||
Number.isFinite(value.deadline_at) && value.deadline_at >= 0 ?
|
||||
{ identity:value.identity, deadline_at:value.deadline_at, expired:now() >= value.deadline_at } : null;
|
||||
};
|
||||
const settle = (state, at = now()) => {
|
||||
const entry = state.entries[state.active_identity];
|
||||
if (!entry?.running) return state;
|
||||
@@ -54,12 +61,36 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
const state = read();
|
||||
const selected = identity || state.active_identity;
|
||||
const entry = state.entries[selected];
|
||||
if (!selected || !entry) return { identity:selected, elapsed_ms:0, running:false };
|
||||
const elapsed = Math.max(0, Number(entry.elapsed_ms) || 0) + (entry.running ?
|
||||
Math.max(0, now() - Number(entry.started_at ?? now())) : 0);
|
||||
return { identity:selected, elapsed_ms:elapsed, running:Boolean(entry.running) };
|
||||
const result = !selected || !entry ?
|
||||
{ identity:selected, elapsed_ms:0, running:false } :
|
||||
{
|
||||
identity:selected,
|
||||
elapsed_ms:Math.max(0, Number(entry.elapsed_ms) || 0) + (entry.running ?
|
||||
Math.max(0, now() - Number(entry.started_at ?? now())) : 0),
|
||||
running:Boolean(entry.running),
|
||||
};
|
||||
const timedBreak = validBreak(state);
|
||||
if (timedBreak?.identity === selected) result.break_deadline_at = timedBreak.deadline_at;
|
||||
return result;
|
||||
};
|
||||
return {
|
||||
adopt(identity, elapsedMs, running) {
|
||||
if (!key() || typeof identity !== 'string' || !identity ||
|
||||
!Number.isFinite(Number(elapsedMs)) || Number(elapsedMs) < 0) return false;
|
||||
const state = read();
|
||||
settle(state);
|
||||
state.active_identity = identity;
|
||||
state.entries[identity] = {
|
||||
elapsed_ms:Math.floor(Number(elapsedMs)),
|
||||
started_at:running ? now() : null,
|
||||
running:Boolean(running),
|
||||
};
|
||||
state.away_at = null;
|
||||
state.pending_interruption = null;
|
||||
state.attention_interruption = null;
|
||||
state.timed_break = null;
|
||||
return write(state);
|
||||
},
|
||||
activate(identity) {
|
||||
if (!key() || typeof identity !== 'string' || !identity) return false;
|
||||
const state = read();
|
||||
@@ -73,6 +104,7 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
state.away_at = null;
|
||||
state.pending_interruption = null;
|
||||
state.attention_interruption = null;
|
||||
state.timed_break = null;
|
||||
return write(state);
|
||||
},
|
||||
pause() {
|
||||
@@ -89,6 +121,32 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
entry.started_at = now();
|
||||
entry.running = true;
|
||||
}
|
||||
state.timed_break = null;
|
||||
return write(state);
|
||||
},
|
||||
startBreak(minutes) {
|
||||
const duration = Number(minutes);
|
||||
if (!Number.isInteger(duration) || duration < 1 || duration > 120) return false;
|
||||
const state = read();
|
||||
const identity = state.active_identity;
|
||||
if (!identity || !state.entries[identity]) return false;
|
||||
settle(state);
|
||||
state.away_at = null;
|
||||
state.pending_interruption = null;
|
||||
state.timed_break = { identity, deadline_at:now() + duration * 60000 };
|
||||
return write(state) ? validBreak(state) : false;
|
||||
},
|
||||
breakSnapshot() {
|
||||
return validBreak(read());
|
||||
},
|
||||
resumeBreak() {
|
||||
const state = read();
|
||||
const pending = validBreak(state);
|
||||
const entry = pending && state.entries[pending.identity];
|
||||
if (!pending || !entry || state.active_identity !== pending.identity || entry.running) return false;
|
||||
state.timed_break = null;
|
||||
entry.started_at = now();
|
||||
entry.running = true;
|
||||
return write(state);
|
||||
},
|
||||
stop() {
|
||||
@@ -97,6 +155,7 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
state.away_at = null;
|
||||
state.pending_interruption = null;
|
||||
state.attention_interruption = null;
|
||||
state.timed_break = null;
|
||||
return write(state);
|
||||
},
|
||||
beginAttention() {
|
||||
@@ -200,9 +259,13 @@ function createTodayTimer({ storage, getLogin, now = () => Date.now() }) {
|
||||
};
|
||||
}
|
||||
|
||||
function createTodayTimerView({ timer, isActive, queryAll, formatEstimate, getRunway, getItem, onReopen, onComplete }) {
|
||||
function createTodayTimerView({ timer, isActive, queryAll, formatEstimate, getRunway, getItem, onReopen, onResume, onComplete }) {
|
||||
let progress = null;
|
||||
let runway = null;
|
||||
let breakView = null;
|
||||
if (typeof createTodayBreak === 'function') {
|
||||
breakView = createTodayBreak({timer, qs:selector => queryAll(selector)[0], queryAll, onChange:() => render(), onResume:onResume || onReopen});
|
||||
}
|
||||
queryAll('[data-mobile-today-open]').forEach(button =>
|
||||
button.addEventListener('click', () => {
|
||||
const identity = timer.snapshot().identity;
|
||||
@@ -248,6 +311,7 @@ function createTodayTimerView({ timer, isActive, queryAll, formatEstimate, getRu
|
||||
};
|
||||
const render = () => {
|
||||
const snapshot = timer.snapshot();
|
||||
breakView?.render();
|
||||
const active = Boolean(progress && isActive() && snapshot.identity);
|
||||
queryAll('[data-mobile-today-hud]').forEach(element => { element.hidden = !active; });
|
||||
queryAll('[data-mobile-today-open]').forEach(element => {
|
||||
|
||||
+24
-1
@@ -127,6 +127,29 @@ function createTodayWork({ storage, getLogin, limit = 5 }) {
|
||||
return saved;
|
||||
}
|
||||
|
||||
function capture(item) {
|
||||
const id = identity(item);
|
||||
const ids = read();
|
||||
const index = ids.indexOf(id);
|
||||
if (index < 0) return null;
|
||||
return { id, index, ids: ids.slice(), plan: planning() };
|
||||
}
|
||||
|
||||
function restore(snapshot) {
|
||||
if (!snapshot || typeof snapshot.id !== 'string' || !Array.isArray(snapshot.ids)) return 'unavailable';
|
||||
const current = read();
|
||||
const expected = snapshot.ids.filter(id => id !== snapshot.id);
|
||||
if (current.includes(snapshot.id)) return 'changed';
|
||||
if (current.length >= limit) return 'full';
|
||||
if (current.length !== expected.length || current.some((id, index) => id !== expected[index])) return 'changed';
|
||||
if (!write(snapshot.ids)) return 'unavailable';
|
||||
if (!replacePlanning(snapshot.plan)) {
|
||||
write(current);
|
||||
return 'unavailable';
|
||||
}
|
||||
return 'restored';
|
||||
}
|
||||
|
||||
function move(item, direction) {
|
||||
const ids = read();
|
||||
const index = ids.indexOf(identity(item));
|
||||
@@ -177,7 +200,7 @@ function createTodayWork({ storage, getLogin, limit = 5 }) {
|
||||
};
|
||||
}
|
||||
|
||||
return { identity, read, replace, planning, replacePlanning, runway, add, addMany, remove, move, reconcile, contains, position, limit };
|
||||
return { identity, read, replace, planning, replacePlanning, runway, add, addMany, remove, capture, restore, move, reconcile, contains, position, limit };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createTodayWork;
|
||||
+74
-28
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a reproducible, verifiable Stackchain Dashboard release bundle."""
|
||||
"""Build a reproducible release bundle from an exact Git commit."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -8,37 +8,88 @@ import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
|
||||
RUNTIME_DIRECTORIES = ("docs", "frontend", "src")
|
||||
RUNTIME_FILES = ("README.md", "requirements.txt")
|
||||
EXCLUDED_PARTS = {"__pycache__", ".pytest_cache"}
|
||||
EXCLUDED_SUFFIXES = (".pyc", ".pyo")
|
||||
COMMIT_PATTERN = re.compile(r"[0-9a-f]{40}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeFile:
|
||||
name: str
|
||||
data: bytes
|
||||
executable: bool
|
||||
|
||||
|
||||
def sha256(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def runtime_files(root: Path) -> list[Path]:
|
||||
files = [root / name for name in RUNTIME_FILES if (root / name).is_file()]
|
||||
for name in RUNTIME_DIRECTORIES:
|
||||
directory = root / name
|
||||
if directory.is_dir():
|
||||
files.extend(path for path in directory.rglob("*") if path.is_file())
|
||||
return sorted(files, key=lambda path: path.relative_to(root).as_posix())
|
||||
def _git(root: Path, *args: str, text: bool = False) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["git", "-C", str(root), *args],
|
||||
capture_output=True,
|
||||
check=False,
|
||||
text=text,
|
||||
)
|
||||
|
||||
|
||||
def manifest_for(root: Path, files: list[Path], commit: str) -> dict:
|
||||
def runtime_files_at_commit(root: Path, commit: str) -> list[RuntimeFile]:
|
||||
"""Read the runtime allowlist directly from the declared Git tree."""
|
||||
root = root.resolve()
|
||||
if not COMMIT_PATTERN.fullmatch(commit):
|
||||
raise ValueError("declared commit must be a full 40-character Git object ID")
|
||||
resolved = _git(root, "rev-parse", "--verify", f"{commit}^{{commit}}", text=True)
|
||||
if resolved.returncode != 0 or resolved.stdout.strip() != commit:
|
||||
raise ValueError("declared commit is unavailable")
|
||||
|
||||
listing = _git(root, "ls-tree", "-rz", "--full-tree", commit)
|
||||
if listing.returncode != 0:
|
||||
raise ValueError("could not inspect the declared commit")
|
||||
|
||||
files: list[RuntimeFile] = []
|
||||
for record in listing.stdout.split(b"\0"):
|
||||
if not record:
|
||||
continue
|
||||
metadata, raw_name = record.split(b"\t", 1)
|
||||
mode, object_type, object_id = metadata.decode("ascii").split()
|
||||
name = raw_name.decode("utf-8")
|
||||
path = PurePosixPath(name)
|
||||
selected = name in RUNTIME_FILES or (path.parts and path.parts[0] in RUNTIME_DIRECTORIES)
|
||||
if not selected or object_type != "blob":
|
||||
continue
|
||||
if mode not in {"100644", "100755"}:
|
||||
raise ValueError(f"release member is not a regular file: {name}")
|
||||
if EXCLUDED_PARTS.intersection(path.parts) or name.endswith(EXCLUDED_SUFFIXES):
|
||||
raise ValueError(f"declared commit contains generated release member: {name}")
|
||||
blob = _git(root, "cat-file", "blob", object_id)
|
||||
if blob.returncode != 0:
|
||||
raise ValueError(f"could not read release member: {name}")
|
||||
files.append(RuntimeFile(name, blob.stdout, mode == "100755"))
|
||||
|
||||
names = {item.name for item in files}
|
||||
missing = [name for name in RUNTIME_FILES if name not in names]
|
||||
if missing or not any(name.startswith("src/") for name in names) or not any(
|
||||
name.startswith("frontend/") for name in names
|
||||
):
|
||||
raise ValueError("declared commit is missing required runtime files")
|
||||
return sorted(files, key=lambda item: item.name)
|
||||
|
||||
|
||||
def manifest_for(files: list[RuntimeFile], commit: str) -> dict:
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"commit": commit,
|
||||
"files": {
|
||||
path.relative_to(root).as_posix(): {
|
||||
"sha256": sha256(path.read_bytes()),
|
||||
"size": path.stat().st_size,
|
||||
}
|
||||
for path in files
|
||||
item.name: {"sha256": sha256(item.data), "size": len(item.data)} for item in files
|
||||
},
|
||||
}
|
||||
|
||||
@@ -58,19 +109,10 @@ def tar_info(name: str, size: int, epoch: int, executable: bool = False) -> tarf
|
||||
|
||||
|
||||
def build(root: Path, output_dir: Path, commit: str, epoch: int) -> tuple[Path, Path, Path]:
|
||||
root = root.resolve()
|
||||
files = runtime_files(root)
|
||||
missing = [name for name in RUNTIME_FILES if not (root / name).is_file()]
|
||||
if missing or not (root / "src").is_dir() or not (root / "frontend").is_dir():
|
||||
raise ValueError("release root is missing required runtime files")
|
||||
|
||||
embedded_manifest = manifest_for(root, files, commit)
|
||||
files = runtime_files_at_commit(root, commit)
|
||||
embedded_manifest = manifest_for(files, commit)
|
||||
archive_members: dict[str, tuple[bytes, bool]] = {
|
||||
path.relative_to(root).as_posix(): (
|
||||
path.read_bytes(),
|
||||
bool(path.stat().st_mode & 0o111),
|
||||
)
|
||||
for path in files
|
||||
item.name: (item.data, item.executable) for item in files
|
||||
}
|
||||
archive_members["release-manifest.json"] = (json_bytes(embedded_manifest), False)
|
||||
|
||||
@@ -112,7 +154,11 @@ def parse_args() -> argparse.Namespace:
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
for path in build(args.root, args.output_dir, args.commit, args.source_date_epoch):
|
||||
try:
|
||||
paths = build(args.root, args.output_dir, args.commit, args.source_date_epoch)
|
||||
except (OSError, ValueError) as error:
|
||||
raise SystemExit(f"release build failed: {error}") from error
|
||||
for path in paths:
|
||||
print(path)
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import sys
|
||||
import tarfile
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from build_release import manifest_for, runtime_files_at_commit
|
||||
|
||||
|
||||
def one(directory: Path, pattern: str) -> Path:
|
||||
matches = sorted(directory.glob(pattern))
|
||||
@@ -22,7 +24,7 @@ def digest(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def verify(input_dir: Path, commit: str) -> None:
|
||||
def verify(input_dir: Path, commit: str, repository: Path) -> None:
|
||||
archive_path = one(input_dir, "*.tar.gz")
|
||||
manifest_path = one(input_dir, "*.manifest.json")
|
||||
checksum_path = one(input_dir, "*.sha256")
|
||||
@@ -45,6 +47,11 @@ def verify(input_dir: Path, commit: str) -> None:
|
||||
expected_files = manifest.get("files")
|
||||
if not isinstance(expected_files, dict):
|
||||
raise ValueError("manifest files must be an object")
|
||||
source_files = runtime_files_at_commit(repository, commit)
|
||||
source_manifest = manifest_for(source_files, commit)["files"]
|
||||
if expected_files != source_manifest:
|
||||
raise ValueError("bundle manifest does not match the declared Git commit")
|
||||
source_by_name = {item.name: item for item in source_files}
|
||||
with tarfile.open(archive_path, "r:gz") as archive:
|
||||
members = archive.getmembers()
|
||||
for member in members:
|
||||
@@ -67,19 +74,22 @@ def verify(input_dir: Path, commit: str) -> None:
|
||||
data = bundled.read()
|
||||
if metadata != {"sha256": digest(data), "size": len(data)}:
|
||||
raise ValueError(f"bundle member failed verification: {name}")
|
||||
if data != source_by_name[name].data:
|
||||
raise ValueError(f"bundle member differs from the declared Git commit: {name}")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--input-dir", type=Path, required=True)
|
||||
parser.add_argument("--commit", required=True)
|
||||
parser.add_argument("--repository", type=Path, default=Path.cwd())
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
try:
|
||||
verify(args.input_dir, args.commit)
|
||||
verify(args.input_dir, args.commit, args.repository)
|
||||
except (OSError, ValueError, json.JSONDecodeError, tarfile.TarError) as error:
|
||||
print(f"release verification failed: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from error
|
||||
|
||||
@@ -34,11 +34,11 @@ FEATURE_SOURCES = {
|
||||
"security-center": ("static/security-center.js",),
|
||||
"today-timer": (
|
||||
"static/conversation.js", "static/voice-transcript-store.js", "static/voice-conversation-capture.js", "static/mobile-launch.js", "static/mobile-insights.js", "static/mobile-app-shortcuts.js", "static/mobile-plan-today-nav.js", "static/mobile-find-work-nav.js", "static/mobile-pull-refresh.js", "static/live-data-status.js",
|
||||
"static/today-completion.js", "static/card-planning.js", "static/work-detail-position.js", "static/work-route.js", "static/commands.js", "static/saved-searches.js", "static/task-overlay-history.js", "static/search-preview.js", "static/mobile-search-preview-nav.js", "static/search-reply-draft-store.js", "static/conversation-reply-draft-store.js", "static/conversation-photo-drafts.js", "static/search-defer.js", "static/mobile-search-viewport.js", "static/my-work.js", "static/protect-today.js", "static/mobile-task-dock.js", "static/mobile-work-entry.js", "static/mobile-queue-launcher.js", "static/mobile-delivery-recovery.js", "static/mobile-start-day.js", "static/update-triage-session.js", "static/update-review-handoff.js", "static/update-triage-launcher.js", "static/update-triage-gesture.js", "static/notification-undo.js", "static/today-timer.js", "static/today-recap.js", "static/today-wrap-up.js", "static/today-handoff.js",
|
||||
"static/today-completion.js", "static/card-planning.js", "static/work-detail-position.js", "static/work-route.js", "static/commands.js", "static/saved-searches.js", "static/task-overlay-history.js", "static/search-preview.js", "static/mobile-search-preview-nav.js", "static/search-reply-draft-store.js", "static/conversation-reply-draft-store.js", "static/conversation-photo-drafts.js", "static/search-defer.js", "static/mobile-search-viewport.js", "static/agenda-replan.js", "static/my-work.js", "static/protect-today.js", "static/mobile-task-dock.js", "static/mobile-work-entry.js", "static/mobile-queue-launcher.js", "static/mobile-delivery-recovery.js", "static/mobile-start-day.js", "static/update-triage-session.js", "static/update-review-handoff.js", "static/update-triage-launcher.js", "static/update-triage-gesture.js", "static/notification-undo.js", "static/today-timer.js", "static/today-break.js", "static/today-lock-screen.js", "static/today-session-sync.js", "static/today-recap.js", "static/today-wrap-up.js", "static/today-handoff.js",
|
||||
"static/today-rollover.js", "static/later-work.js", "static/later-picker.js", "static/drafts.js", "static/unfiled-captures.js", "static/unfiled-draft-sync.js",
|
||||
"static/assign-and-start.js", "static/filed-claim.js", "static/queue-today.js", "static/create-and-start.js",
|
||||
"static/draft-filing-session.js", "static/draft-capacity-dialog.js", "static/work-selection.js",
|
||||
"static/today-work.js", "static/pick-work.js", "static/batch-find-work.js",
|
||||
"static/today-work.js", "static/today-sync.js", "static/pick-work.js", "static/batch-find-work.js",
|
||||
"static/search-batch-plan.js", "static/mention-composer.js", "static/issue-evidence-review.js", "static/issue-evidence-editor.js",
|
||||
"static/issue-attachment.js", "static/checklist-conflict.js", "static/issue-outbox.js", "static/authored-outbox.js", "static/issue-sheet.js", "static/mobile-issue-detail-nav.js", "static/issue-filing-review.js", "static/issue-filing-receipt.js",
|
||||
),
|
||||
|
||||
+94
-15
@@ -64,7 +64,7 @@ from src.unfiled_draft_store import UnfiledDraftConflict, UnfiledDraftStore
|
||||
from src.security_event_store import SecurityEventStore, SecurityEventStoreError
|
||||
from src.suggestion_engine import compute
|
||||
from src.later_store import LaterStore
|
||||
from src.today_store import TodayPlanFull, TodayStore
|
||||
from src.today_store import TodayPlanFull, TodaySessionConflict, TodayStore
|
||||
from src.views import FRONTEND_BUILD, router as frontend_router
|
||||
|
||||
|
||||
@@ -588,6 +588,21 @@ class TodayRecap(BaseModel):
|
||||
items: list[TodayRecapItem] = Field(min_length=1, max_length=20)
|
||||
|
||||
|
||||
class TodaySessionUpdate(BaseModel):
|
||||
base_revision: int = Field(ge=0)
|
||||
device_id: str = Field(min_length=1, max_length=100)
|
||||
identity: str = Field(max_length=500)
|
||||
elapsed_ms: int = Field(ge=0, le=7 * 24 * 60 * 60 * 1000)
|
||||
running: bool
|
||||
break_deadline_at: int | None = Field(default=None, ge=0, le=10_000_000_000_000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_break_is_paused(self):
|
||||
if self.running and self.break_deadline_at is not None:
|
||||
raise ValueError("break must remain paused")
|
||||
return self
|
||||
|
||||
|
||||
class TodayRecapTimeLog(TodayRecap):
|
||||
log_identities: list[str] = Field(min_length=1, max_length=20)
|
||||
|
||||
@@ -1322,7 +1337,7 @@ async def require_operator_session(request: Request, call_next):
|
||||
async def prevent_live_api_caching(request, call_next):
|
||||
response = await call_next(request)
|
||||
path = dashboard_auth.application_path(request)
|
||||
if path in {"/api/v1/context", "/api/v1/background-identity", "/api/v1/events", "/api/v1/live", "/api/v1/available-issues", "/api/v1/search", "/api/v1/work-route", "/api/v1/today", "/api/v1/later", "/api/v1/saved-searches", "/api/v1/completed-filed-reviews", "/api/v1/security-events", "/api/v1/push-subscription"} or path.startswith("/api/v1/work/") or (
|
||||
if path in {"/api/v1/context", "/api/v1/background-identity", "/api/v1/events", "/api/v1/live", "/api/v1/available-issues", "/api/v1/search", "/api/v1/work-route", "/api/v1/today", "/api/v1/today/session", "/api/v1/later", "/api/v1/saved-searches", "/api/v1/completed-filed-reviews", "/api/v1/security-events", "/api/v1/push-subscription"} or path.startswith("/api/v1/work/") or (
|
||||
path.startswith("/api/v1/repos/")
|
||||
and path.endswith("/review")
|
||||
) or path.startswith("/api/v1/notifications") or (
|
||||
@@ -2456,6 +2471,37 @@ async def update_today_plan(payload: TodayOperation | TodayOperationBatch):
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/today/session")
|
||||
async def get_today_session():
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(_today_store().get_session, login)
|
||||
except (OSError, sqlite3.Error):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Today session synchronization is unavailable",
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
|
||||
@app.patch("/api/v1/today/session")
|
||||
async def update_today_session(payload: TodaySessionUpdate):
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
_today_store().update_session, login, **payload.model_dump()
|
||||
)
|
||||
except TodaySessionConflict as error:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={"code": "session_changed", "session": error.session},
|
||||
)
|
||||
except (OSError, sqlite3.Error):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Today session synchronization is unavailable",
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/today/recaps")
|
||||
async def get_today_recaps(response: Response):
|
||||
login = await _confirmed_login()
|
||||
@@ -5879,31 +5925,60 @@ async def merge_assigned_pull(
|
||||
target=f"{repository}#{number}",
|
||||
)
|
||||
|
||||
async def merge_pull():
|
||||
if not await gitea_proxy.is_assigned_pull(repository, number):
|
||||
raise HTTPException(status_code=404, detail="Assigned pull request not found")
|
||||
return await gitea_proxy.merge_assigned_pull(
|
||||
repository, number, submission.expected_head_sha
|
||||
try:
|
||||
assigned = await asyncio.wait_for(
|
||||
gitea_proxy.is_assigned_pull(repository, number),
|
||||
timeout=ISSUE_ACTION_TIMEOUT_SECONDS,
|
||||
)
|
||||
except Exception:
|
||||
return JSONResponse(
|
||||
{"error": "The pull request assignment could not be verified. Nothing was merged."},
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
if not assigned:
|
||||
raise HTTPException(status_code=404, detail="Assigned pull request not found")
|
||||
|
||||
journal = _security_event_store()
|
||||
try:
|
||||
operation_id = await asyncio.to_thread(
|
||||
journal.reserve,
|
||||
"pull_merged",
|
||||
target=f"{repository}#{number}",
|
||||
)
|
||||
except SecurityEventStoreError:
|
||||
return JSONResponse(
|
||||
{"error": "Security activity is temporarily unavailable. Nothing was merged."},
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
merge_pull(), timeout=ISSUE_ACTION_TIMEOUT_SECONDS
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
_security_event_store().record,
|
||||
"pull_merged",
|
||||
target=f"{repository}#{number}",
|
||||
gitea_proxy.merge_assigned_pull(
|
||||
repository, number, submission.expected_head_sha
|
||||
),
|
||||
timeout=ISSUE_ACTION_TIMEOUT_SECONDS,
|
||||
)
|
||||
try:
|
||||
await asyncio.to_thread(journal.finalize, operation_id)
|
||||
except SecurityEventStoreError:
|
||||
pass
|
||||
return result
|
||||
except HTTPException:
|
||||
raise
|
||||
except gitea_proxy.StalePullError:
|
||||
try:
|
||||
await asyncio.to_thread(journal.discard, operation_id)
|
||||
except SecurityEventStoreError:
|
||||
pass
|
||||
return JSONResponse(
|
||||
{"error": "New commits were pushed. Refresh before merging."},
|
||||
status_code=409,
|
||||
)
|
||||
except gitea_proxy.PullNotMergeableError:
|
||||
try:
|
||||
await asyncio.to_thread(journal.discard, operation_id)
|
||||
except SecurityEventStoreError:
|
||||
pass
|
||||
return JSONResponse(
|
||||
{"error": "This pull request is not currently safe to merge. Refresh its status."},
|
||||
status_code=409,
|
||||
@@ -5919,6 +5994,10 @@ async def merge_assigned_pull(
|
||||
except Exception:
|
||||
merged = False
|
||||
if merged:
|
||||
try:
|
||||
await asyncio.to_thread(journal.finalize, operation_id)
|
||||
except SecurityEventStoreError:
|
||||
pass
|
||||
return {"number": number, "merged": True, "state": "closed"}
|
||||
return JSONResponse(
|
||||
{
|
||||
|
||||
+80
-2
@@ -13,6 +13,14 @@ class TodayPlanFull(ValueError):
|
||||
"""Raised when an add would exceed the bounded Today plan."""
|
||||
|
||||
|
||||
class TodaySessionConflict(ValueError):
|
||||
"""Raised when a device updates an obsolete active-session revision."""
|
||||
|
||||
def __init__(self, session: dict):
|
||||
super().__init__("active Today session changed on another device")
|
||||
self.session = session
|
||||
|
||||
|
||||
class TodayStore:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -36,7 +44,7 @@ class TodayStore:
|
||||
|
||||
def _initialize(self) -> None:
|
||||
connection = connect_private_sqlite(self.path, timeout=self.timeout)
|
||||
if connection.execute("PRAGMA user_version").fetchone()[0] >= 1:
|
||||
if connection.execute("PRAGMA user_version").fetchone()[0] >= 3:
|
||||
connection.close()
|
||||
return
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
@@ -106,7 +114,24 @@ class TodayStore:
|
||||
)
|
||||
"""
|
||||
)
|
||||
connection.execute("PRAGMA user_version = 1")
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS today_sessions (
|
||||
login TEXT PRIMARY KEY,
|
||||
revision INTEGER NOT NULL,
|
||||
device_id TEXT NOT NULL,
|
||||
identity TEXT NOT NULL,
|
||||
elapsed_ms INTEGER NOT NULL,
|
||||
running INTEGER NOT NULL,
|
||||
break_deadline_at INTEGER,
|
||||
updated_at REAL NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
session_columns = {row[1] for row in connection.execute("PRAGMA table_info(today_sessions)")}
|
||||
if "break_deadline_at" not in session_columns:
|
||||
connection.execute("ALTER TABLE today_sessions ADD COLUMN break_deadline_at INTEGER")
|
||||
connection.execute("PRAGMA user_version = 3")
|
||||
connection.commit()
|
||||
connection.close()
|
||||
|
||||
@@ -163,6 +188,59 @@ class TodayStore:
|
||||
).fetchone()
|
||||
return self._snapshot(row)
|
||||
|
||||
@staticmethod
|
||||
def _empty_session() -> dict:
|
||||
return {
|
||||
"revision": 0, "device_id": "", "identity": "",
|
||||
"elapsed_ms": 0, "running": False, "break_deadline_at": None, "updated_at": None,
|
||||
}
|
||||
|
||||
def get_session(self, login: str) -> dict:
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at "
|
||||
"FROM today_sessions WHERE login = ?",
|
||||
(self._normalize_login(login),),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return self._empty_session()
|
||||
return {
|
||||
"revision": int(row[0]), "device_id": row[1], "identity": row[2],
|
||||
"elapsed_ms": int(row[3]), "running": bool(row[4]),
|
||||
"break_deadline_at": row[5], "updated_at": row[6],
|
||||
}
|
||||
|
||||
def update_session(
|
||||
self, login: str, *, base_revision: int, device_id: str,
|
||||
identity: str, elapsed_ms: int, running: bool, break_deadline_at: int | None = None,
|
||||
) -> dict:
|
||||
login = self._normalize_login(login)
|
||||
updated_at = self.clock()
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
current = connection.execute(
|
||||
"SELECT revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at "
|
||||
"FROM today_sessions WHERE login = ?", (login,)
|
||||
).fetchone()
|
||||
current_revision = int(current[0]) if current else 0
|
||||
if base_revision != current_revision:
|
||||
session = self._empty_session() if current is None else {
|
||||
"revision": current_revision, "device_id": current[1], "identity": current[2],
|
||||
"elapsed_ms": int(current[3]), "running": bool(current[4]),
|
||||
"break_deadline_at": current[5], "updated_at": current[6],
|
||||
}
|
||||
raise TodaySessionConflict(session)
|
||||
revision = current_revision + 1
|
||||
connection.execute(
|
||||
"INSERT INTO today_sessions(login, revision, device_id, identity, elapsed_ms, running, break_deadline_at, updated_at) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
|
||||
"ON CONFLICT(login) DO UPDATE SET revision=excluded.revision, device_id=excluded.device_id, "
|
||||
"identity=excluded.identity, elapsed_ms=excluded.elapsed_ms, running=excluded.running, "
|
||||
"break_deadline_at=excluded.break_deadline_at, updated_at=excluded.updated_at",
|
||||
(login, revision, device_id, identity, elapsed_ms, int(running), break_deadline_at, updated_at),
|
||||
)
|
||||
return self.get_session(login)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_recap_items(items: list[dict]) -> list[dict]:
|
||||
if not isinstance(items, list) or not items:
|
||||
|
||||
@@ -80,6 +80,63 @@ def test_release_artifact_plans_hands_off_and_opens_next_mobile_issue(tmp_path:
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
expect(page.locator("#plan-today-sheet")).to_be_hidden()
|
||||
|
||||
page.locator("#close-issue-sheet").click()
|
||||
if page.locator("#plan-today-sheet").is_visible():
|
||||
page.locator("#cancel-plan-today").click()
|
||||
expect(page.locator("[data-mobile-today-hud]")).to_be_visible()
|
||||
take_break = page.locator("[data-today-break-open]")
|
||||
expect(take_break).to_be_visible()
|
||||
take_break.click()
|
||||
expect(page.locator("#today-break-sheet")).to_be_visible()
|
||||
for control in page.locator(".today-break-actions button").all():
|
||||
bounds = control.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
page.go_back()
|
||||
expect(page.locator("#today-break-sheet")).to_be_hidden()
|
||||
|
||||
take_break.click()
|
||||
page.locator('[data-today-break-minutes="5"]').click()
|
||||
expect(page.locator("#today-break-status")).to_have_text("On break · resume in 5:00")
|
||||
expect(page.locator("[data-mobile-today-toggle]")).to_have_text("Resume timer")
|
||||
page.evaluate("""() => {
|
||||
const prefix = 'stackchain.today-sync.v1.timmy.operation.';
|
||||
localStorage.setItem(prefix + 'broken', '{not-json');
|
||||
}""")
|
||||
page.reload(wait_until="networkidle")
|
||||
expect(page.locator("#my-work-status")).to_contain_text("2")
|
||||
expect(page.locator("#today-sync-status")).to_have_text(
|
||||
"Today queue recovered · discarded 1 unreadable device record."
|
||||
)
|
||||
assert page.evaluate("""() => !Object.keys(localStorage).some(
|
||||
key => key.startsWith('stackchain.today-sync.v1.timmy.operation.')
|
||||
)""")
|
||||
expect(page.locator("#today-break-status")).to_contain_text("On break · resume in")
|
||||
if page.locator("#issue-sheet").get_attribute("class") == "issue-sheet open":
|
||||
page.locator("#close-issue-sheet").click()
|
||||
if page.locator("#plan-today-sheet").is_visible():
|
||||
page.locator("#cancel-plan-today").click()
|
||||
expect(page.locator("#resume-today-break")).to_be_visible()
|
||||
page.locator("#resume-today-break").click()
|
||||
expect(page.locator("#today-break-status")).to_be_hidden()
|
||||
expect(page.locator("#issue-sheet")).to_have_class("issue-sheet open")
|
||||
expect(page.locator("#issue-sheet-title")).to_have_text("Ship mobile capture")
|
||||
|
||||
page.locator("#close-issue-sheet").click()
|
||||
if page.locator("#plan-today-sheet").is_visible():
|
||||
page.locator("#cancel-plan-today").click()
|
||||
page.set_viewport_size({"width": 320, "height": 568})
|
||||
page.locator("[data-today-break-open]").click()
|
||||
expect(page.locator("#today-break-sheet")).to_be_visible()
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
custom = page.locator("#today-break-custom-minutes")
|
||||
bounds = custom.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
page.locator("#cancel-today-break").click()
|
||||
expect(page.locator("#today-break-sheet")).to_be_hidden()
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
page.locator("[data-mobile-today-open]").click()
|
||||
expect(page.locator("#issue-sheet")).to_have_class("issue-sheet open")
|
||||
|
||||
page.locator('[data-issue-section="reply"]').click()
|
||||
page.locator("#issue-comment").fill("Handoff complete; continuing with the next Today item.")
|
||||
page.locator("#send-issue-comment-next").click()
|
||||
@@ -89,8 +146,30 @@ def test_release_artifact_plans_hands_off_and_opens_next_mobile_issue(tmp_path:
|
||||
expect(page.locator("[data-mobile-today-hud]")).to_have_attribute("data-overlay-hidden", "true")
|
||||
expect(page.locator("[data-mobile-today-hud]")).to_contain_text("Polish desktop filters")
|
||||
assert fake.comments == [(41, "Handoff complete; continuing with the next Today item.")]
|
||||
|
||||
receipt = page.locator("#today-completion-undo")
|
||||
expect(receipt).to_be_visible()
|
||||
expect(receipt).to_contain_text("Removed from Today. Undo?")
|
||||
undo = page.locator("#undo-today-completion")
|
||||
bounds = undo.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
page.locator("#close-issue-sheet").click()
|
||||
expect(page.locator("[data-mobile-today-hud]")).to_be_visible()
|
||||
expect(page.locator(".mobile-task-dock")).to_be_visible()
|
||||
layout = page.evaluate("""() => {
|
||||
const receipt = document.querySelector('#today-completion-undo').getBoundingClientRect();
|
||||
const hud = document.querySelector('[data-mobile-today-hud]').getBoundingClientRect();
|
||||
const dock = document.querySelector('.mobile-task-dock').getBoundingClientRect();
|
||||
return {receiptBottom:receipt.bottom, hudTop:hud.top, dockTop:dock.top};
|
||||
}""")
|
||||
assert layout["receiptBottom"] <= min(layout["hudTop"], layout["dockTop"])
|
||||
undo.click()
|
||||
expect(receipt).to_be_hidden()
|
||||
expect(page.locator("[data-mobile-today-hud]")).to_contain_text("Polish desktop filters")
|
||||
|
||||
today = page.evaluate("JSON.parse(localStorage.getItem('stackchain.today-work.v1.timmy') || '[]')")
|
||||
assert today == ["issue:acme/mobile:42:"]
|
||||
assert today == ["issue:acme/mobile:41:", "issue:acme/mobile:42:"]
|
||||
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
assert browser_errors == []
|
||||
assert failed_responses == []
|
||||
|
||||
@@ -41,7 +41,10 @@ def test_release_promotion_waits_for_tests_and_bundle():
|
||||
assert "needs: [lint, build-release, browser-journey]" in release
|
||||
assert "github.event_name == 'push'" in release
|
||||
assert "actions/download-artifact@v3" in release
|
||||
assert 'python3 scripts/verify_release.py --input-dir dist --commit "$TARGET"' in release
|
||||
assert (
|
||||
'python3 scripts/verify_release.py --input-dir dist --commit "$TARGET" --repository .'
|
||||
in release
|
||||
)
|
||||
assert release.index("sha256sum -c") < release.index("curl --fail-with-body")
|
||||
|
||||
|
||||
|
||||
@@ -303,4 +303,4 @@ async def test_unread_update_offers_reply_mark_read_and_next_independent_of_toda
|
||||
assert '.update-reply-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr));' in html
|
||||
assert '.update-reply-actions button { min-height:44px;' in html
|
||||
worker = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
assert "stackchain-dashboard-shell-v117" in worker
|
||||
assert "stackchain-dashboard-shell-v120" in worker
|
||||
@@ -435,5 +435,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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/later-sync.js'" in source
|
||||
@@ -256,4 +256,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-v117" in worker
|
||||
assert "stackchain-dashboard-shell-v120" in worker
|
||||
@@ -45,7 +45,7 @@ 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-v117" in worker
|
||||
assert "stackchain-dashboard-shell-v120" in worker
|
||||
|
||||
|
||||
def test_all_conversation_composers_offer_accessible_mobile_mentions():
|
||||
|
||||
@@ -223,7 +223,7 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
|
||||
assert "promptStorage:localStorage" in dashboard
|
||||
assert "pushControllerReady.then(ensureDeviceSetup)" in dashboard
|
||||
assert "BASE + 'static/mobile-device-setup.js'" in worker
|
||||
assert "stackchain-dashboard-shell-v117" in worker
|
||||
assert "stackchain-dashboard-shell-v120" in worker
|
||||
assert ".device-setup-panel" in css
|
||||
assert ".device-readiness-card" in css
|
||||
assert "overflow-x:hidden" in css
|
||||
|
||||
@@ -174,5 +174,5 @@ async def test_mobile_home_progressively_discloses_secondary_panels_as_insights(
|
||||
def test_mobile_insights_rolls_into_the_offline_shell():
|
||||
worker = (CONTROLLER.parent / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in worker
|
||||
assert "stackchain-dashboard-shell-v120" in worker
|
||||
assert "BASE + 'static/mobile-insights.js'" in worker
|
||||
@@ -110,6 +110,42 @@ process.stdout.write(JSON.stringify({{blocked, handed, opened, handoffs}}));
|
||||
assert output["handoffs"] == ["agenda"]
|
||||
|
||||
|
||||
def test_prepare_today_counts_each_work_identity_in_only_its_highest_priority_phase():
|
||||
script = f"""
|
||||
const createStartDay = require({json.dumps(str(START_DAY))});
|
||||
const agendaUpdate = {{kind:'issue', key:'lab#1'}};
|
||||
const attentionUpdate = {{kind:'pull', key:'lab#2'}};
|
||||
const filed = {{kind:'issue', key:'lab#3'}};
|
||||
const delivery = {{outbox_id:'draft-4'}};
|
||||
const controller = createStartDay({{
|
||||
getCounts: () => ({{today:2}}),
|
||||
getPhaseItems: () => ({{
|
||||
delivery:[delivery],
|
||||
agenda:[agendaUpdate],
|
||||
attention:[agendaUpdate, attentionUpdate],
|
||||
update:[agendaUpdate, attentionUpdate],
|
||||
filed:[filed],
|
||||
}}),
|
||||
openQueue: () => {{}},
|
||||
}});
|
||||
process.stdout.write(JSON.stringify(controller.briefing()));
|
||||
"""
|
||||
|
||||
output = run_node(script)
|
||||
assert output == {
|
||||
"total": 4,
|
||||
"next": "delivery",
|
||||
"label": "Review Delivery",
|
||||
"summary": "1 delivery needs action before Today · 3 other items · 2 planned",
|
||||
"phases": [
|
||||
{"name": "delivery", "label": "Delivery recovery", "count": 1},
|
||||
{"name": "agenda", "label": "Agenda", "count": 1},
|
||||
{"name": "attention", "label": "Attention", "count": 1},
|
||||
{"name": "filed", "label": "Filed", "count": 1},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_start_day_view_renders_refreshed_phases_and_launches_primary_action():
|
||||
script = f"""
|
||||
const createStartDay = require({json.dumps(str(START_DAY))});
|
||||
@@ -322,4 +358,24 @@ async def test_dashboard_wires_thumb_safe_start_day_briefing_into_offline_mobile
|
||||
assert ".mobile-start-day-finish { min-height:44px;" in html
|
||||
assert "max-width:100%; overflow-wrap:anywhere;" in html
|
||||
assert "BASE + 'static/mobile-start-day.js'" in service_worker
|
||||
assert "stackchain-dashboard-shell-v117" in service_worker
|
||||
assert "stackchain-dashboard-shell-v120" in service_worker
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_primary_mobile_work_action_opens_a_unique_item_prepare_today_briefing():
|
||||
html = await dashboard()
|
||||
|
||||
assert "getPreparationState: () => mobileStartDay.state()" in html
|
||||
assert "prepareToday: openMobileStartDay" in html
|
||||
assert "function openMobileStartDay()" in html
|
||||
assert "qs('#mobile-queue-heading').textContent = state.active ? 'Resume Prepare Today' : 'Prepare Today';" in html
|
||||
assert "qs('#mobile-queue-sheet').showModal();" in html
|
||||
assert "qs('#mobile-start-day-action').focus();" in html
|
||||
assert "let mobilePreparationItems = {};" in html
|
||||
assert "getPhaseItems: () => mobilePreparationItems" in html
|
||||
assert "mobilePreparationItems = {" in html
|
||||
assert "delivery:draftInbox.partition(lastDrafts).deliveries" in html
|
||||
assert "agenda:agendaMyWork(activeMyWork)" in html
|
||||
assert "attention:activeMyWork.filter(item => item.needs_attention)" in html
|
||||
assert "update:activeMyWork.filter(item => item.has_update)" in html
|
||||
assert "filed:activeMyWork.filter(item => item.is_filed)" in html
|
||||
@@ -85,6 +85,37 @@ process.stdout.write(JSON.stringify({{modes, calls}}));
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_work_entry_opens_prepare_today_before_direct_queue_work():
|
||||
script = f"""
|
||||
const createEntry = require({json.dumps(str(ENTRY))});
|
||||
const calls = [];
|
||||
const state = {{active:true, preparation:{{active:false, next:'attention'}}}};
|
||||
const entry = createEntry({{
|
||||
isTodayActive: () => state.active,
|
||||
isTodayResumable: () => false,
|
||||
getTodayCount: () => 0,
|
||||
getEligibleCount: () => 3,
|
||||
getPreparationState: () => state.preparation,
|
||||
queueLauncher: {{recommend: () => ({{name:'attention'}}), open: name => calls.push('queue:' + name)}},
|
||||
continueToday: () => calls.push('continue'),
|
||||
prepareToday: () => calls.push('prepare'),
|
||||
planToday: () => calls.push('plan'),
|
||||
findWork: () => calls.push('find'),
|
||||
}});
|
||||
const modes = [entry.open()];
|
||||
state.active = false; modes.push(entry.open());
|
||||
state.preparation.active = true; modes.push(entry.open());
|
||||
process.stdout.write(JSON.stringify({{modes, calls}}));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"modes": ["continue", "prepare", "prepare-resume"],
|
||||
"calls": ["continue", "prepare", "prepare"],
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_work_entry_plans_eligible_work_before_find_fallback():
|
||||
script = f"""
|
||||
const createEntry = require({json.dumps(str(ENTRY))});
|
||||
@@ -651,6 +682,28 @@ process.stdout.write(JSON.stringify(labels));
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_task_dock_labels_prepare_today_as_the_primary_action():
|
||||
script = f"""
|
||||
const createDock = require({json.dumps(str(DOCK))});
|
||||
const work = {{attributes: {{}}, setAttribute(name, value) {{ this.attributes[name] = value; }}}};
|
||||
const workLabel = {{textContent:''}};
|
||||
const dock = createDock({{nav:{{}}, buttons:{{work}}, workLabel}});
|
||||
const labels = {{}};
|
||||
for (const mode of ['prepare','prepare-resume']) {{
|
||||
dock.updateWork(mode);
|
||||
labels[mode] = [workLabel.textContent, work.attributes['aria-label']];
|
||||
}}
|
||||
process.stdout.write(JSON.stringify(labels));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"prepare": ["Prepare", "Prepare Today"],
|
||||
"prepare-resume": ["Resume prep", "Resume preparation"],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_renders_accessible_mobile_queue_completion_handoff():
|
||||
html = await dashboard()
|
||||
|
||||
@@ -410,7 +410,7 @@ 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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/plan-today.js'" in source
|
||||
assert "BASE + 'static/plan-today-readiness.js'" in source
|
||||
assert "BASE + 'static/plan-today-preview.js'" in source
|
||||
@@ -4,6 +4,7 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from src import gitea_proxy, main
|
||||
from src.security_event_store import SecurityEventStoreError
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -312,11 +313,98 @@ async def test_assigned_pull_merge_requires_current_eligible_head(monkeypatch):
|
||||
assert calls == [("stackchain/api", 7, "abc123")]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_assigned_pull_merge_fails_before_gitea_when_audit_reservation_fails(
|
||||
monkeypatch,
|
||||
):
|
||||
merge_calls = []
|
||||
|
||||
class UnavailableJournal:
|
||||
def reserve(self, *_args, **_kwargs):
|
||||
raise SecurityEventStoreError("unavailable")
|
||||
|
||||
async def assigned(*_args):
|
||||
return True
|
||||
|
||||
async def merge(*args):
|
||||
merge_calls.append(args)
|
||||
return {"number": 7, "merged": True, "state": "closed"}
|
||||
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: UnavailableJournal())
|
||||
monkeypatch.setattr(main.gitea_proxy, "is_assigned_pull", assigned)
|
||||
monkeypatch.setattr(main.gitea_proxy, "merge_assigned_pull", merge)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls/7/merge",
|
||||
json={"expected_head_sha": "abc123"},
|
||||
)
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json() == {
|
||||
"error": "Security activity is temporarily unavailable. Nothing was merged."
|
||||
}
|
||||
assert merge_calls == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_assigned_pull_merge_reports_success_and_retains_pending_audit_when_finalize_fails(
|
||||
monkeypatch,
|
||||
):
|
||||
lifecycle = []
|
||||
|
||||
class InterruptedJournal:
|
||||
def reserve(self, kind, *, target):
|
||||
lifecycle.append(("reserve", kind, target))
|
||||
return "merge-operation"
|
||||
|
||||
def finalize(self, operation_id):
|
||||
lifecycle.append(("finalize", operation_id))
|
||||
raise SecurityEventStoreError("unavailable")
|
||||
|
||||
def discard(self, operation_id):
|
||||
lifecycle.append(("discard", operation_id))
|
||||
|
||||
async def assigned(*_args):
|
||||
return True
|
||||
|
||||
async def merge(*_args):
|
||||
return {"number": 7, "merged": True, "state": "closed"}
|
||||
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: InterruptedJournal())
|
||||
monkeypatch.setattr(main.gitea_proxy, "is_assigned_pull", assigned)
|
||||
monkeypatch.setattr(main.gitea_proxy, "merge_assigned_pull", merge)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls/7/merge",
|
||||
json={"expected_head_sha": "abc123"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"number": 7, "merged": True, "state": "closed"}
|
||||
assert lifecycle == [
|
||||
("reserve", "pull_merged", "stackchain/api#7"),
|
||||
("finalize", "merge-operation"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_assigned_pull_merge_reconciles_acceptance_before_timeout(monkeypatch):
|
||||
calls = []
|
||||
merged = False
|
||||
|
||||
class LifecycleJournal:
|
||||
def reserve(self, kind, *, target):
|
||||
calls.append(("reserve", kind, target))
|
||||
return "merge-operation"
|
||||
|
||||
def finalize(self, operation_id):
|
||||
calls.append(("finalize", operation_id))
|
||||
|
||||
def discard(self, operation_id):
|
||||
calls.append(("discard", operation_id))
|
||||
|
||||
async def assigned(repository, number):
|
||||
return True
|
||||
|
||||
@@ -332,6 +420,7 @@ async def test_assigned_pull_merge_reconciles_acceptance_before_timeout(monkeypa
|
||||
return merged
|
||||
|
||||
monkeypatch.setattr(main, "ISSUE_ACTION_TIMEOUT_SECONDS", 0.01)
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: LifecycleJournal())
|
||||
monkeypatch.setattr(main.gitea_proxy, "is_assigned_pull", assigned)
|
||||
monkeypatch.setattr(main.gitea_proxy, "merge_assigned_pull", merge)
|
||||
monkeypatch.setattr(main.gitea_proxy, "is_pull_merged_at_head", confirm, raising=False)
|
||||
@@ -345,8 +434,10 @@ async def test_assigned_pull_merge_reconciles_acceptance_before_timeout(monkeypa
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"number": 7, "merged": True, "state": "closed"}
|
||||
assert calls == [
|
||||
("reserve", "pull_merged", "stackchain/api#7"),
|
||||
("merge", "stackchain/api", 7, "abc123"),
|
||||
("confirm", "stackchain/api", 7, "abc123"),
|
||||
("finalize", "merge-operation"),
|
||||
]
|
||||
|
||||
|
||||
@@ -435,6 +526,47 @@ async def test_assigned_pull_merge_returns_conflict_without_mutating_stale_head(
|
||||
assert "New commits" in response.json()["error"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize(
|
||||
"rejection",
|
||||
[gitea_proxy.StalePullError("changed"), gitea_proxy.PullNotMergeableError("unsafe")],
|
||||
)
|
||||
async def test_assigned_pull_merge_discards_audit_reservation_after_definite_rejection(
|
||||
monkeypatch, rejection
|
||||
):
|
||||
lifecycle = []
|
||||
|
||||
class LifecycleJournal:
|
||||
def reserve(self, kind, *, target):
|
||||
lifecycle.append(("reserve", kind, target))
|
||||
return "merge-operation"
|
||||
|
||||
def discard(self, operation_id):
|
||||
lifecycle.append(("discard", operation_id))
|
||||
|
||||
async def assigned(*_args):
|
||||
return True
|
||||
|
||||
async def merge(*_args):
|
||||
raise rejection
|
||||
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: LifecycleJournal())
|
||||
monkeypatch.setattr(main.gitea_proxy, "is_assigned_pull", assigned)
|
||||
monkeypatch.setattr(main.gitea_proxy, "merge_assigned_pull", merge)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls/7/merge",
|
||||
json={"expected_head_sha": "abc123"},
|
||||
)
|
||||
|
||||
assert response.status_code == 409
|
||||
assert lifecycle == [
|
||||
("reserve", "pull_merged", "stackchain/api#7"),
|
||||
("discard", "merge-operation"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_merge_rejects_failed_ci_without_upstream_mutation():
|
||||
requests = []
|
||||
|
||||
@@ -20,7 +20,24 @@ def _fixture(root: Path) -> None:
|
||||
(root / "README.md").write_text("# Stackchain\n")
|
||||
|
||||
|
||||
def _build(source: Path, output: Path) -> subprocess.CompletedProcess[str]:
|
||||
def _commit_fixture(source: Path) -> str:
|
||||
subprocess.run(["git", "init", "-q", str(source)], check=True)
|
||||
subprocess.run(["git", "-C", str(source), "config", "user.name", "Release Test"], check=True)
|
||||
subprocess.run(
|
||||
["git", "-C", str(source), "config", "user.email", "release-test@example.invalid"],
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(["git", "-C", str(source), "add", "."], check=True)
|
||||
subprocess.run(["git", "-C", str(source), "commit", "-qm", "fixture"], check=True)
|
||||
return subprocess.run(
|
||||
["git", "-C", str(source), "rev-parse", "HEAD"],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def _build(source: Path, output: Path, commit: str) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
@@ -30,7 +47,7 @@ def _build(source: Path, output: Path) -> subprocess.CompletedProcess[str]:
|
||||
"--output-dir",
|
||||
str(output),
|
||||
"--commit",
|
||||
"a" * 40,
|
||||
commit,
|
||||
"--source-date-epoch",
|
||||
"1720000000",
|
||||
],
|
||||
@@ -40,14 +57,20 @@ def _build(source: Path, output: Path) -> subprocess.CompletedProcess[str]:
|
||||
)
|
||||
|
||||
|
||||
def test_release_bundle_is_reproducible(tmp_path):
|
||||
def test_release_bundle_is_reproducible_from_declared_commit(tmp_path):
|
||||
source = tmp_path / "source"
|
||||
_fixture(source)
|
||||
commit = _commit_fixture(source)
|
||||
|
||||
first = _build(source, tmp_path / "first")
|
||||
second = _build(source, tmp_path / "second")
|
||||
|
||||
first = _build(source, tmp_path / "first", commit)
|
||||
assert first.returncode == 0, first.stderr
|
||||
|
||||
(source / "src" / "__pycache__").mkdir()
|
||||
(source / "src" / "__pycache__" / "main.cpython-311.pyc").write_bytes(b"bytecode")
|
||||
(source / "src" / "untracked-secret.txt").write_text("must not ship")
|
||||
(source / "src" / "main.py").write_text("print('dirty worktree')\n")
|
||||
second = _build(source, tmp_path / "second", commit)
|
||||
|
||||
assert second.returncode == 0, second.stderr
|
||||
first_archive = next((tmp_path / "first").glob("*.tar.gz"))
|
||||
second_archive = next((tmp_path / "second").glob("*.tar.gz"))
|
||||
@@ -55,7 +78,7 @@ def test_release_bundle_is_reproducible(tmp_path):
|
||||
|
||||
manifest = json.loads(next((tmp_path / "first").glob("*.manifest.json")).read_text())
|
||||
checksum = next((tmp_path / "first").glob("*.sha256")).read_text().split()[0]
|
||||
assert manifest["commit"] == "a" * 40
|
||||
assert manifest["commit"] == commit
|
||||
assert manifest["artifact"]["sha256"] == checksum
|
||||
assert checksum == hashlib.sha256(first_archive.read_bytes()).hexdigest()
|
||||
assert sorted(manifest["files"]) == [
|
||||
@@ -74,19 +97,40 @@ def test_release_bundle_is_reproducible(tmp_path):
|
||||
"requirements.txt",
|
||||
"src/main.py",
|
||||
]
|
||||
assert embedded["commit"] == "a" * 40
|
||||
assert embedded["commit"] == commit
|
||||
assert embedded["files"] == manifest["files"]
|
||||
|
||||
|
||||
def test_release_bundle_rejects_unknown_commit(tmp_path):
|
||||
source = tmp_path / "source"
|
||||
_fixture(source)
|
||||
_commit_fixture(source)
|
||||
|
||||
built = _build(source, tmp_path / "dist", "a" * 40)
|
||||
|
||||
assert built.returncode != 0
|
||||
assert "declared commit is unavailable" in built.stderr
|
||||
|
||||
|
||||
def test_release_bundle_verifier_enforces_integrity(tmp_path):
|
||||
source = tmp_path / "source"
|
||||
output = tmp_path / "dist"
|
||||
_fixture(source)
|
||||
built = _build(source, output)
|
||||
commit = _commit_fixture(source)
|
||||
built = _build(source, output, commit)
|
||||
assert built.returncode == 0, built.stderr
|
||||
|
||||
valid = subprocess.run(
|
||||
[sys.executable, str(VERIFIER), "--input-dir", str(output), "--commit", "a" * 40],
|
||||
[
|
||||
sys.executable,
|
||||
str(VERIFIER),
|
||||
"--input-dir",
|
||||
str(output),
|
||||
"--commit",
|
||||
commit,
|
||||
"--repository",
|
||||
str(source),
|
||||
],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
@@ -96,9 +140,18 @@ def test_release_bundle_verifier_enforces_integrity(tmp_path):
|
||||
archive = next(output.glob("*.tar.gz"))
|
||||
archive.write_bytes(archive.read_bytes() + b"tampered")
|
||||
tampered = subprocess.run(
|
||||
[sys.executable, str(VERIFIER), "--input-dir", str(output), "--commit", "a" * 40],
|
||||
[
|
||||
sys.executable,
|
||||
str(VERIFIER),
|
||||
"--input-dir",
|
||||
str(output),
|
||||
"--commit",
|
||||
commit,
|
||||
"--repository",
|
||||
str(source),
|
||||
],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
assert tampered.returncode != 0
|
||||
assert tampered.returncode != 0
|
||||
+130
-18
@@ -14,7 +14,7 @@ def run_worker_scenario(scenario: str) -> dict:
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const listeners = {{}};
|
||||
const state = {{ added: [], addAttempts: [], individuallyAdded: [], failedAdds: [], deleted: [], deletedDatabases: [], claimed: false, skipped: false, fetches: [], puts: [], migrated: [], activationOrder: [], oldCachedAssets: {{}}, sharedRecords: {{}}, failSharedPut: false, 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 state = {{ added: [], addAttempts: [], individuallyAdded: [], failedAdds: [], deleted: [], deletedDatabases: [], claimed: false, skipped: false, fetches: [], puts: [], migrated: [], activationOrder: [], oldCachedAssets: {{}}, sharedRecords: {{}}, failSharedPut: false, backgroundFlushes: 0, backgroundResumes: 0, outboxPurges: 0, outboxLifecycle: [], notifications: [], closedNotifications: 0, 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',
|
||||
@@ -73,7 +73,10 @@ const context = {{
|
||||
matchAll: async () => state.clientList || [],
|
||||
openWindow: async url => {{ state.opened.push(url); }},
|
||||
}},
|
||||
registration: {{showNotification: async (title, options) => state.notifications.push({{title,options}})}},
|
||||
registration: {{
|
||||
showNotification: async (title, options) => state.notifications.push({{title,options}}),
|
||||
getNotifications: async () => [{{close:()=>{{state.closedNotifications += 1;}}}}],
|
||||
}},
|
||||
__issueSync: {{
|
||||
flush: async () => {{ state.backgroundFlushes += 1; state.outboxLifecycle.push('flush'); return state.flushResult; }},
|
||||
purge: async () => {{ state.outboxPurges += 1; state.outboxLifecycle.push('purge'); }},
|
||||
@@ -135,11 +138,11 @@ async function dispatchMessage(data, ports = []) {{
|
||||
listeners.message({{ data, ports, waitUntil: promise => {{ pending = promise; }} }});
|
||||
if (pending) await pending;
|
||||
}}
|
||||
async function dispatchNotificationClick(route, action = '', notificationId = null, tag = null, url = null) {{
|
||||
async function dispatchNotificationClick(route, action = '', notificationId = null, tag = null, url = null, actionToken = '') {{
|
||||
let pending;
|
||||
listeners.notificationclick({{
|
||||
action,
|
||||
notification: {{tag: tag || ('stackchain-update-' + notificationId), data: {{route, notificationId, ...(url ? {{url}} : {{}})}}, close: () => {{ state.notificationClosed = true; }}}},
|
||||
notification: {{tag: tag || ('stackchain-update-' + notificationId), data: {{route, notificationId, ...(url ? {{url}} : {{}}), ...(actionToken ? {{actionToken}} : {{}})}}, close: () => {{ state.notificationClosed = true; }}}},
|
||||
waitUntil: promise => {{ pending = promise; }},
|
||||
}});
|
||||
if (pending) await pending;
|
||||
@@ -165,13 +168,13 @@ async function dispatchPush(payload) {{
|
||||
def test_offline_activation_migration_rolls_the_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
|
||||
|
||||
def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/my-work.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
@@ -180,7 +183,7 @@ def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/authored-outbox.js'" in source
|
||||
assert "BASE + 'static/background-issue-sync.js'" in source
|
||||
@@ -189,7 +192,7 @@ def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
|
||||
def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/issue-evidence-review.js'" in source
|
||||
assert "BASE + 'static/issue-attachment.js'" in source
|
||||
|
||||
@@ -197,14 +200,14 @@ def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
|
||||
def test_ownership_exit_runtime_rolls_the_offline_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
|
||||
def test_offline_review_next_ships_today_completion_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/today-completion.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -212,7 +215,7 @@ def test_offline_review_next_ships_today_completion_atomically():
|
||||
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/create-issue-sheet.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -220,7 +223,7 @@ def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/issue-sheet.js'" in source
|
||||
assert "BASE + 'static/checklist-conflict.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
@@ -230,14 +233,14 @@ def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" 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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -246,21 +249,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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" 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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" 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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
@@ -501,6 +504,112 @@ def test_authenticated_resume_rearms_a_previously_purged_worker_before_flushing(
|
||||
assert result["state"]["backgroundResumes"] == 1
|
||||
|
||||
|
||||
def test_active_today_message_replaces_one_privacy_safe_lock_screen_notification():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
await dispatchMessage({type:'stackchain-today-lock-screen',active:true,running:true,identity:'secret/repo#42',actionToken:'opaque-token-1234567890'});
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["notifications"] == [
|
||||
{
|
||||
"title": "Today session running",
|
||||
"options": {
|
||||
"body": "Your active Today timer is running.",
|
||||
"tag": "stackchain-today-session",
|
||||
"renotify": False,
|
||||
"silent": True,
|
||||
"actions": [
|
||||
{"action": "pause-today", "title": "Pause"},
|
||||
{"action": "finish-today", "title": "Finish current"},
|
||||
],
|
||||
"data": {"route": "#/my-work/today", "actionToken": "opaque-token-1234567890"},
|
||||
},
|
||||
}
|
||||
]
|
||||
assert "secret" not in json.dumps(result["notifications"])
|
||||
|
||||
|
||||
def test_inactive_today_message_closes_the_lock_screen_notification():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
await dispatchMessage({type:'stackchain-today-lock-screen',active:false,running:false});
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["notifications"] == []
|
||||
assert result["closedNotifications"] == 1
|
||||
|
||||
|
||||
def test_private_data_purge_also_removes_the_today_lock_screen_notification():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
await dispatchMessage({type:'stackchain-purge-outbox'}, [{postMessage:()=>{}}]);
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["outboxPurges"] == 1
|
||||
assert result["closedNotifications"] == 1
|
||||
|
||||
|
||||
def test_today_lock_screen_action_updates_an_open_dashboard_without_navigation():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
state.clientMessages=[];
|
||||
state.clientList=[{
|
||||
url:'https://forge.example/dashboard/#/my-work/today',
|
||||
postMessage:message=>state.clientMessages.push(message),
|
||||
focus:async()=>state.focused.push('today'),
|
||||
}];
|
||||
await dispatchNotificationClick('#/my-work/today','pause-today',null,'stackchain-today-session');
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["clientMessages"] == [
|
||||
{"type": "stackchain-today-timer-action", "action": "pause"}
|
||||
]
|
||||
assert result["focused"] == ["today"]
|
||||
assert result["opened"] == []
|
||||
|
||||
|
||||
def test_today_lock_screen_action_opens_a_validated_one_shot_route_when_closed():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
await dispatchNotificationClick('#/my-work/today','resume-today',null,'stackchain-today-session');
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["opened"] == [
|
||||
"https://forge.example/dashboard/?today_timer_action=resume#/my-work/today"
|
||||
]
|
||||
|
||||
|
||||
def test_finish_today_lock_screen_action_forwards_only_its_opaque_token():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
state.clientMessages=[];
|
||||
state.clientList=[{
|
||||
url:'https://forge.example/dashboard/#/my-work/today',
|
||||
postMessage:message=>state.clientMessages.push(message),
|
||||
focus:async()=>state.focused.push('today'),
|
||||
}];
|
||||
await dispatchNotificationClick('#/my-work/today','finish-today',null,'stackchain-today-session',null,'opaque-token-1234567890');
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["clientMessages"] == [{
|
||||
"type": "stackchain-today-timer-action",
|
||||
"action": "complete",
|
||||
"actionToken": "opaque-token-1234567890",
|
||||
}]
|
||||
|
||||
|
||||
def test_background_mutation_abort_also_cancels_stalled_csrf_lookup():
|
||||
result = run_worker_scenario(
|
||||
"""
|
||||
@@ -930,7 +1039,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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/queue-today.js'" in source
|
||||
|
||||
|
||||
@@ -988,6 +1097,9 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/work-selection.js",
|
||||
"/dashboard/static/today-work.js",
|
||||
"/dashboard/static/today-timer.js",
|
||||
"/dashboard/static/today-break.js",
|
||||
"/dashboard/static/today-lock-screen.js",
|
||||
"/dashboard/static/today-session-sync.js",
|
||||
"/dashboard/static/today-recap.js",
|
||||
"/dashboard/static/today-wrap-up.js",
|
||||
"/dashboard/static/today-handoff.js",
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[1]
|
||||
TIMER = ROOT / "frontend" / "today-timer.js"
|
||||
BREAK = ROOT / "frontend" / "today-break.js"
|
||||
|
||||
|
||||
def run_node(source: str) -> dict:
|
||||
completed = subprocess.run(
|
||||
["node", "-e", source], capture_output=True, text=True
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_timed_break_pauses_immediately_and_restores_absolute_deadline():
|
||||
script = TIMER.read_text() + r"""
|
||||
const values = new Map();
|
||||
const storage = {getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)};
|
||||
let now = 100000;
|
||||
const timer = createTodayTimer({storage,getLogin:()=> 'timmy',now:()=>now});
|
||||
timer.activate('issue:r:42:');
|
||||
now = 112000;
|
||||
const started = timer.startBreak(15);
|
||||
const paused = timer.snapshot();
|
||||
now = 200000;
|
||||
const restored = createTodayTimer({storage,getLogin:()=> 'timmy',now:()=>now}).breakSnapshot();
|
||||
process.stdout.write(JSON.stringify({started,paused,restored}));
|
||||
"""
|
||||
|
||||
assert run_node(script) == {
|
||||
"started": {
|
||||
"identity": "issue:r:42:",
|
||||
"deadline_at": 1012000,
|
||||
"expired": False,
|
||||
},
|
||||
"paused": {
|
||||
"identity": "issue:r:42:", "elapsed_ms": 12000, "running": False,
|
||||
"break_deadline_at": 1012000,
|
||||
},
|
||||
"restored": {
|
||||
"identity": "issue:r:42:",
|
||||
"deadline_at": 1012000,
|
||||
"expired": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_timed_break_snapshot_carries_deadline_for_cross_device_sync():
|
||||
script = TIMER.read_text() + r"""
|
||||
const values = new Map();
|
||||
const storage = {getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)};
|
||||
const timer = createTodayTimer({storage,getLogin:()=> 'timmy',now:()=>100000});
|
||||
timer.activate('issue:r:42:');
|
||||
timer.startBreak(15);
|
||||
process.stdout.write(JSON.stringify(timer.snapshot()));
|
||||
"""
|
||||
|
||||
assert run_node(script) == {
|
||||
"identity": "issue:r:42:", "elapsed_ms": 0, "running": False,
|
||||
"break_deadline_at": 1_000_000,
|
||||
}
|
||||
|
||||
|
||||
def test_break_expiry_never_restarts_time_and_resume_is_explicit_and_idempotent():
|
||||
script = TIMER.read_text() + r"""
|
||||
const values = new Map();
|
||||
const storage = {getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)};
|
||||
let now = 0;
|
||||
const timer = createTodayTimer({storage,getLogin:()=> 'timmy',now:()=>now});
|
||||
timer.activate('issue:r:42:');
|
||||
const invalid = [timer.startBreak(0), timer.startBreak(121), timer.startBreak(1.5)];
|
||||
const started = timer.startBreak(5);
|
||||
now = 300001;
|
||||
const expired = timer.breakSnapshot();
|
||||
const stillPaused = timer.snapshot();
|
||||
const resumed = timer.resumeBreak();
|
||||
now = 305001;
|
||||
const running = timer.snapshot();
|
||||
const replay = timer.resumeBreak();
|
||||
process.stdout.write(JSON.stringify({invalid,started,expired,stillPaused,resumed,running,replay,remaining:timer.breakSnapshot()}));
|
||||
"""
|
||||
|
||||
result = run_node(script)
|
||||
assert result["invalid"] == [False, False, False]
|
||||
assert result["started"]["deadline_at"] == 300000
|
||||
assert result["expired"]["expired"] is True
|
||||
assert result["stillPaused"]["running"] is False
|
||||
assert result["resumed"] is True
|
||||
assert result["running"] == {
|
||||
"identity": "issue:r:42:", "elapsed_ms": 5000, "running": True
|
||||
}
|
||||
assert result["replay"] is False
|
||||
assert result["remaining"] is None
|
||||
|
||||
|
||||
def test_mobile_break_sheet_starts_counts_down_and_requires_explicit_resume():
|
||||
script = f"""
|
||||
const createBreak = require({json.dumps(str(BREAK))});
|
||||
class Element {{
|
||||
constructor() {{ this.listeners={{}}; this.hidden=false; this.textContent=''; this.value=''; this.open=false; this.dataset={{}}; }}
|
||||
addEventListener(name, fn) {{ this.listeners[name]=fn; }}
|
||||
click() {{ return this.listeners.click?.({{preventDefault(){{}}}}); }}
|
||||
showModal() {{ this.open=true; }}
|
||||
close() {{ this.open=false; this.listeners.close?.(); }}
|
||||
focus() {{}}
|
||||
}}
|
||||
let now=100000;
|
||||
let pending=null;
|
||||
const calls=[];
|
||||
const timer={{
|
||||
snapshot:()=>({{identity:'issue:r:42:',elapsed_ms:5000,running:!pending}}),
|
||||
breakSnapshot:()=>pending && {{...pending,expired:now>=pending.deadline_at}},
|
||||
startBreak:minutes=>{{calls.push(['start',minutes]);pending={{identity:'issue:r:42:',deadline_at:now+minutes*60000}};return {{...pending,expired:false}};}},
|
||||
resumeBreak:()=>{{if(!pending)return false;calls.push(['resume']);pending=null;return true;}},
|
||||
}};
|
||||
const sheet=new Element(), opener=new Element(), cancel=new Element(), preset=new Element(), status=new Element(), resume=new Element();
|
||||
preset.dataset.todayBreakMinutes='15';
|
||||
let tick;
|
||||
const controller=createBreak({{timer,sheet,openButtons:[opener],cancelButton:cancel,presetButtons:[preset],status,resumeButton:resume,now:()=>now,setIntervalRef:fn=>(tick=fn,1),clearIntervalRef:()=>{{}},onChange:()=>calls.push(['change']),onResume:identity=>calls.push(['return',identity])}});
|
||||
opener.click();
|
||||
const opened=sheet.open;
|
||||
cancel.click();
|
||||
const cancelled={{open:sheet.open,calls:[...calls]}};
|
||||
opener.click(); preset.click();
|
||||
const started={{open:sheet.open,text:status.textContent,statusHidden:status.hidden,resumeHidden:resume.hidden,openerHidden:opener.hidden}};
|
||||
now=100000+15*60000+1; tick();
|
||||
const expired={{text:status.textContent,resumeHidden:resume.hidden,running:timer.snapshot().running}};
|
||||
resume.click();
|
||||
process.stdout.write(JSON.stringify({{opened,cancelled,started,expired,final:{{calls,statusHidden:status.hidden,openerHidden:opener.hidden,pending}}}}));
|
||||
"""
|
||||
|
||||
assert run_node(script) == {
|
||||
"opened": True,
|
||||
"cancelled": {"open": False, "calls": []},
|
||||
"started": {
|
||||
"open": False,
|
||||
"text": "On break · resume in 15:00",
|
||||
"statusHidden": False,
|
||||
"resumeHidden": False,
|
||||
"openerHidden": True,
|
||||
},
|
||||
"expired": {
|
||||
"text": "Break over · ready to resume",
|
||||
"resumeHidden": False,
|
||||
"running": False,
|
||||
},
|
||||
"final": {
|
||||
"calls": [["start", 15], ["change"], ["resume"], ["return", "issue:r:42:"], ["change"]],
|
||||
"statusHidden": True,
|
||||
"openerHidden": False,
|
||||
"pending": None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_timed_break_is_packaged_as_an_accessible_mobile_flow():
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
css = (ROOT / "frontend" / "dashboard.css").read_text()
|
||||
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
|
||||
bundle = (ROOT / "src" / "frontend_bundle.py").read_text()
|
||||
|
||||
assert 'data-today-break-open' in html
|
||||
assert 'id="today-break-sheet"' in html
|
||||
assert 'data-today-break-minutes="5"' in html
|
||||
assert 'data-today-break-minutes="15"' in html
|
||||
assert 'data-today-break-minutes="30"' in html
|
||||
assert 'id="today-break-custom-minutes"' in html
|
||||
assert 'min="1" max="120" step="1"' in html
|
||||
assert 'id="today-break-status"' in html
|
||||
assert 'id="resume-today-break"' in html
|
||||
assert '<script src="static/today-break.js"></script>' in html
|
||||
assert "createTodayBreak({" in (ROOT / "frontend" / "today-timer.js").read_text()
|
||||
assert '"static/today-break.js"' in bundle
|
||||
assert ".today-break-panel" in css
|
||||
assert "overflow-x:hidden" in css
|
||||
assert ".today-break-actions button" in css
|
||||
assert "min-height:44px" in css
|
||||
|
||||
|
||||
def test_custom_break_validation_is_side_effect_free_until_valid():
|
||||
script = f"""
|
||||
const createBreak = require({json.dumps(str(BREAK))});
|
||||
class Element {{
|
||||
constructor() {{this.listeners={{}};this.open=true;this.hidden=false;this.value='';this.textContent='';}}
|
||||
addEventListener(name,fn){{this.listeners[name]=fn;}}
|
||||
close(){{this.open=false;}}
|
||||
focus(){{this.focused=true;}}
|
||||
}}
|
||||
const form=new Element(), input=new Element(), error=new Element(), status=new Element(), resume=new Element(), sheet=new Element();
|
||||
const calls=[];
|
||||
const timer={{snapshot:()=>({{identity:'issue:r:1:'}}),breakSnapshot:()=>null,startBreak:value=>{{calls.push(value);return value===45;}},resumeBreak:()=>false}};
|
||||
createBreak({{timer,sheet,form,minutesInput:input,error,status,resumeButton:resume,setIntervalRef:()=>1,clearIntervalRef:()=>{{}}}});
|
||||
input.value='2.5'; form.listeners.submit({{preventDefault(){{}}}});
|
||||
const invalid={{open:sheet.open,error:error.textContent,focused:input.focused||false}};
|
||||
input.value='45'; form.listeners.submit({{preventDefault(){{}}}});
|
||||
process.stdout.write(JSON.stringify({{invalid,valid:{{open:sheet.open,error:error.textContent}},calls}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"invalid": {
|
||||
"open": True,
|
||||
"error": "Choose a whole number from 1 to 120 minutes.",
|
||||
"focused": True,
|
||||
},
|
||||
"valid": {"open": False, "error": ""},
|
||||
"calls": [2.5, 45],
|
||||
}
|
||||
|
||||
|
||||
def test_replacing_or_stopping_active_work_clears_an_old_break():
|
||||
script = TIMER.read_text() + r"""
|
||||
const values=new Map();
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)};
|
||||
let now=0;
|
||||
const timer=createTodayTimer({storage,getLogin:()=> 'timmy',now:()=>now});
|
||||
timer.activate('issue:r:1:'); timer.startBreak(5); timer.activate('issue:r:2:');
|
||||
const replaced=timer.breakSnapshot();
|
||||
timer.startBreak(5); timer.stop();
|
||||
const stopped=timer.breakSnapshot();
|
||||
timer.activate('issue:r:3:'); timer.startBreak(5); timer.adopt('issue:r:4:',1000,false);
|
||||
process.stdout.write(JSON.stringify({replaced,stopped,adopted:timer.breakSnapshot()}));
|
||||
"""
|
||||
assert run_node(script) == {"replaced": None, "stopped": None, "adopted": None}
|
||||
|
||||
|
||||
def test_browser_back_closes_break_sheet_without_starting_a_break():
|
||||
script = f"""
|
||||
const createBreak=require({json.dumps(str(BREAK))});
|
||||
class Element{{constructor(){{this.listeners={{}};this.open=false;this.hidden=true;}}addEventListener(n,f){{this.listeners[n]=f;}}showModal(){{this.open=true;}}close(){{this.open=false;}}}}
|
||||
const sheet=new Element(), opener=new Element(), status=new Element(), resume=new Element();
|
||||
const listeners={{}}, pushes=[];
|
||||
const historyRef={{state:{{route:'today'}},pushState:state=>{{historyRef.state=state;pushes.push(state);}},back:()=>listeners.popstate?.()}};
|
||||
const windowRef={{addEventListener:(name,fn)=>listeners[name]=fn}};
|
||||
const timer={{snapshot:()=>({{identity:'issue:r:1:'}}),breakSnapshot:()=>null,resumeBreak:()=>false}};
|
||||
createBreak({{timer,sheet,openButtons:[opener],status,resumeButton:resume,historyRef,windowRef,queryAll:()=>[]}});
|
||||
opener.listeners.click();
|
||||
const opened={{open:sheet.open,state:historyRef.state,pushes}};
|
||||
listeners.popstate();
|
||||
process.stdout.write(JSON.stringify({{opened,closed:!sheet.open}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"opened": {
|
||||
"open": True,
|
||||
"state": {"route": "today", "todayBreak": True},
|
||||
"pushes": [{"route": "today", "todayBreak": True}],
|
||||
},
|
||||
"closed": True,
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "frontend" / "today-lock-screen.js"
|
||||
ROOT = SOURCE.parents[1]
|
||||
|
||||
|
||||
def run_scenario(scenario: str) -> dict:
|
||||
script = SOURCE.read_text() + r"""
|
||||
const values = new Map();
|
||||
const messages = [];
|
||||
const listeners = {};
|
||||
const control = {checked:false, disabled:false, addEventListener:(name, fn)=>listeners[name]=fn};
|
||||
const status = {textContent:''};
|
||||
const serviceWorker = {
|
||||
controller:{postMessage:message=>messages.push(message)},
|
||||
ready:Promise.resolve({active:{postMessage:message=>messages.push(message)}}),
|
||||
addEventListener:(name, fn)=>listeners['sw-' + name]=fn,
|
||||
};
|
||||
const storage = {getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
let permission = 'default';
|
||||
const NotificationRef = {get permission(){return permission;},requestPermission:async()=>{permission='granted';return permission;}};
|
||||
const actions = [];
|
||||
const locationRef = {href:'https://forge.example/dashboard/#/my-work/today'};
|
||||
const historyRef = {replaceState:(_a,_b,url)=>{locationRef.href=new URL(url, locationRef.href).href;}};
|
||||
let tokenCounter = 0;
|
||||
const tokens = ['opaque-token-1234567890', 'new-opaque-token-0987654321'];
|
||||
(async()=>{
|
||||
const lockScreen = createTodayLockScreen({storage,getLogin:()=> 'Timmy',serviceWorker,NotificationRef,control,status,locationRef,historyRef,randomToken:()=> tokens[tokenCounter++],fingerprint:async (_token, identity)=>identity.startsWith('issue:') ? 'opaque-issue-fingerprint' : 'opaque-pull-fingerprint',onAction:(action, identity)=>actions.push([action, identity])});
|
||||
%SCENARIO%
|
||||
})().catch(error=>{console.error(error);process.exit(1)});
|
||||
""".replace("%SCENARIO%", scenario)
|
||||
completed = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_operator_opt_in_syncs_one_privacy_safe_session_notification():
|
||||
result = run_scenario(r"""
|
||||
await lockScreen.enable();
|
||||
await lockScreen.sync({identity:'issue:secret/repo:42:',running:true,elapsed_ms:125000}, true);
|
||||
process.stdout.write(JSON.stringify({checked:control.checked,status:status.textContent,messages,stored:[...values.entries()]}));
|
||||
""")
|
||||
|
||||
assert result["checked"] is True
|
||||
assert result["status"] == "Lock-screen Today controls are on."
|
||||
assert result["stored"] == [
|
||||
["stackchain.today-lock-screen.v1.timmy", "1"],
|
||||
["stackchain.today-lock-screen-action.v1.timmy", '{"token":"opaque-token-1234567890","fingerprint":"opaque-issue-fingerprint"}'],
|
||||
]
|
||||
assert result["messages"][-1] == {
|
||||
"type": "stackchain-today-lock-screen",
|
||||
"active": True,
|
||||
"running": True,
|
||||
"actionToken": "opaque-token-1234567890",
|
||||
}
|
||||
assert "secret" not in json.dumps(result)
|
||||
|
||||
|
||||
def test_disabling_or_ending_session_removes_notification():
|
||||
result = run_scenario(r"""
|
||||
await lockScreen.enable();
|
||||
await lockScreen.sync({identity:'issue:r:42:',running:false,elapsed_ms:0}, false);
|
||||
await lockScreen.disable();
|
||||
process.stdout.write(JSON.stringify({checked:control.checked,messages,stored:[...values.entries()]}));
|
||||
""")
|
||||
|
||||
assert result["checked"] is False
|
||||
assert result["stored"] == []
|
||||
assert result["messages"][-2:] == [
|
||||
{"type": "stackchain-today-lock-screen", "active": False, "running": False},
|
||||
{"type": "stackchain-today-lock-screen", "active": False, "running": False},
|
||||
]
|
||||
|
||||
|
||||
def test_valid_notification_action_is_consumed_once_and_removed_from_url():
|
||||
result = run_scenario(r"""
|
||||
values.set('stackchain.today-lock-screen.v1.timmy','1');
|
||||
locationRef.href='https://forge.example/dashboard/?today_timer_action=pause#/my-work/today';
|
||||
const consumed = await lockScreen.consumeLaunchAction();
|
||||
const second = await lockScreen.consumeLaunchAction();
|
||||
listeners['sw-message']({data:{type:'stackchain-today-timer-action',action:'resume'}});
|
||||
process.stdout.write(JSON.stringify({consumed,second,actions,href:locationRef.href}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"consumed": True,
|
||||
"second": False,
|
||||
"actions": [["pause", None], ["resume", None]],
|
||||
"href": "https://forge.example/dashboard/#/my-work/today",
|
||||
}
|
||||
|
||||
|
||||
def test_finish_action_is_bound_to_the_exact_active_identity_and_consumed_once():
|
||||
result = run_scenario(r"""
|
||||
await lockScreen.enable();
|
||||
await lockScreen.sync({identity:'issue:private/repo:42:',running:true}, true);
|
||||
const first = await lockScreen.consumeAction('complete', 'opaque-token-1234567890');
|
||||
const replay = await lockScreen.consumeAction('complete', 'opaque-token-1234567890');
|
||||
await lockScreen.sync({identity:'pull:private/repo:9:',running:true}, true);
|
||||
const stale = await lockScreen.consumeAction('complete', 'opaque-token-1234567890');
|
||||
process.stdout.write(JSON.stringify({first,replay,stale,actions,messages,stored:[...values.entries()]}));
|
||||
""")
|
||||
|
||||
assert result["first"] is True
|
||||
assert result["replay"] is False
|
||||
assert result["stale"] is False
|
||||
assert result["actions"] == [["complete", "issue:private/repo:42:"]]
|
||||
assert all("private/repo" not in json.dumps(message) for message in result["messages"])
|
||||
|
||||
|
||||
def test_cold_launch_finish_action_is_removed_from_history_before_completion():
|
||||
result = run_scenario(r"""
|
||||
await lockScreen.enable();
|
||||
await lockScreen.sync({identity:'issue:private/repo:42:',running:true}, true);
|
||||
locationRef.href='https://forge.example/dashboard/?today_timer_action=complete&today_action_token=opaque-token-1234567890#/my-work/today';
|
||||
const consumed = await lockScreen.consumeLaunchAction();
|
||||
process.stdout.write(JSON.stringify({consumed,actions,href:locationRef.href}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"consumed": True,
|
||||
"actions": [["complete", "issue:private/repo:42:"]],
|
||||
"href": "https://forge.example/dashboard/#/my-work/today",
|
||||
}
|
||||
|
||||
|
||||
def test_permission_denial_is_truthful_and_does_not_persist_opt_in():
|
||||
result = run_scenario(r"""
|
||||
NotificationRef.requestPermission=async()=>{permission='denied';return permission;};
|
||||
const enabled = await lockScreen.enable();
|
||||
process.stdout.write(JSON.stringify({enabled,checked:control.checked,status:status.textContent,stored:[...values.entries()]}));
|
||||
""")
|
||||
|
||||
assert result == {
|
||||
"enabled": False,
|
||||
"checked": False,
|
||||
"status": "Lock-screen controls are blocked in browser settings.",
|
||||
"stored": [],
|
||||
}
|
||||
|
||||
|
||||
def test_lock_screen_flow_is_wired_into_the_packaged_today_journey():
|
||||
index = (ROOT / "frontend" / "index.html").read_text()
|
||||
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
|
||||
bundle = (ROOT / "src" / "frontend_bundle.py").read_text()
|
||||
|
||||
assert 'id="today-lock-screen"' in index
|
||||
assert 'id="today-lock-screen-status"' in index
|
||||
assert '<script src="static/today-lock-screen.js"></script>' in index
|
||||
assert index.index('static/today-lock-screen.js') < index.index('static/dashboard.js')
|
||||
assert 'createTodayLockScreen({' in dashboard
|
||||
assert "action === 'complete'" in dashboard
|
||||
assert "completeTodayItem(item)" in dashboard
|
||||
assert "todayLockScreen.consumeLaunchAction()" in dashboard
|
||||
assert dashboard.index("const completeTodayItem = createTodayCompletion({") < dashboard.index("todayLockScreen.consumeLaunchAction()")
|
||||
assert "todayLockScreen.sync(snapshot, workSession.checkpointed())" in dashboard
|
||||
assert "todayLockScreen.consumeLaunchAction()" in dashboard
|
||||
assert '"static/today-lock-screen.js"' in bundle
|
||||
@@ -221,7 +221,7 @@ async def test_today_blocker_opens_existing_preview_and_preserves_readiness_gate
|
||||
def test_readiness_runtime_is_available_in_offline_shell():
|
||||
service_worker = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v117';" in service_worker
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v120';" in service_worker
|
||||
assert "BASE + 'static/today-readiness.js'" in service_worker
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
from pathlib import Path
|
||||
|
||||
from src.frontend_bundle import build_frontend
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[1]
|
||||
|
||||
|
||||
def test_dashboard_packages_a_mobile_today_session_handoff():
|
||||
build = build_frontend(ROOT / "frontend")
|
||||
html = build.dashboard_html
|
||||
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
|
||||
css = (ROOT / "frontend" / "dashboard.css").read_text()
|
||||
today_bundle = build.feature_bundles["today-timer"].runtime_bytes.decode()
|
||||
|
||||
assert 'id="today-session-handoff"' in html
|
||||
assert 'id="continue-today-session"' in html
|
||||
assert 'id="today-session-sync-status"' in html
|
||||
assert 'aria-live="polite"' in html
|
||||
assert "createTodaySessionSync" in today_bundle
|
||||
assert "attachTodaySessionHandoff" in today_bundle
|
||||
assert "Session syncing…" in today_bundle
|
||||
assert "Session offline · will retry." in today_bundle
|
||||
assert "Session continued on another device." in today_bundle
|
||||
assert "todaySessionSync = attachTodaySessionHandoff" in dashboard
|
||||
assert "todaySessionSync?.publish(snapshot)" in dashboard
|
||||
assert "min-height:44px" in css
|
||||
@@ -0,0 +1,367 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "frontend" / "today-session-sync.js"
|
||||
|
||||
|
||||
def run_node(script: str) -> dict:
|
||||
completed = subprocess.run(
|
||||
["node", "-e", SOURCE.read_text() + "\n" + script],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_second_device_sees_and_claims_the_running_session():
|
||||
result = run_node(
|
||||
r"""
|
||||
const calls = [];
|
||||
const remote = {revision:3, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:90000, running:true, updated_at:10};
|
||||
let adopted = null;
|
||||
const offers = [];
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=>'phone-b',
|
||||
fetchJson:async (url, options={}) => {
|
||||
calls.push({url, body:options.body ? JSON.parse(options.body) : null});
|
||||
return options.method === 'PATCH' ? {...remote, revision:4, device_id:'phone-b'} : remote;
|
||||
},
|
||||
timer:{adopt:(identity, elapsed, running)=>{adopted={identity, elapsed, running};}},
|
||||
onRemote:session=>{offers.push(session);},
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
const claimed = await sync.claim();
|
||||
process.stdout.write(JSON.stringify({offers, claimed, adopted, calls}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["offers"][0]["device_id"] == "desktop-a"
|
||||
assert result["claimed"]["device_id"] == "phone-b"
|
||||
assert result["adopted"] == {
|
||||
"identity": "issue:r:42:", "elapsed": 90000, "running": True,
|
||||
}
|
||||
assert result["calls"][1] == {
|
||||
"url": "api/v1/today/session",
|
||||
"body": {
|
||||
"base_revision": 3,
|
||||
"device_id": "phone-b",
|
||||
"identity": "issue:r:42:",
|
||||
"elapsed_ms": 90000,
|
||||
"running": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_second_device_sees_and_resumes_a_timed_break():
|
||||
result = run_node(
|
||||
r"""
|
||||
const calls=[];
|
||||
const remote={revision:3,device_id:'phone-a',identity:'issue:r:42:',elapsed_ms:90000,running:false,break_deadline_at:1800000,updated_at:10};
|
||||
let adopted=null;
|
||||
const offers=[];
|
||||
const sync=createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-b',
|
||||
fetchJson:async (url,options={})=>{
|
||||
calls.push(options.body ? JSON.parse(options.body) : null);
|
||||
return options.method === 'PATCH' ? {...remote,revision:4,device_id:'desktop-b',running:true,break_deadline_at:null} : remote;
|
||||
},
|
||||
timer:{adopt:(identity,elapsed,running)=>{adopted={identity,elapsed,running};}},
|
||||
onRemote:session=>offers.push(session),
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
const claimed=await sync.claim();
|
||||
process.stdout.write(JSON.stringify({offers,claimed,adopted,calls}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["offers"][0]["break_deadline_at"] == 1_800_000
|
||||
assert result["calls"][1] == {
|
||||
"base_revision": 3, "device_id": "desktop-b", "identity": "issue:r:42:",
|
||||
"elapsed_ms": 90_000, "running": True, "break_deadline_at": None,
|
||||
}
|
||||
assert result["adopted"] == {
|
||||
"identity": "issue:r:42:", "elapsed": 90_000, "running": True,
|
||||
}
|
||||
assert result["claimed"]["device_id"] == "desktop-b"
|
||||
|
||||
|
||||
def test_break_handoff_summary_is_actionable_and_privacy_safe():
|
||||
result = run_node(
|
||||
r"""
|
||||
const session={identity:'issue:private/repo:42:',elapsed_ms:90000,running:false,break_deadline_at:1800000};
|
||||
process.stdout.write(JSON.stringify({
|
||||
summary:todaySessionHandoffSummary(session,{title:'Secret issue'},0),
|
||||
}));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["summary"].startswith("On break until ")
|
||||
assert "Secret issue" not in result["summary"]
|
||||
assert "private/repo" not in result["summary"]
|
||||
|
||||
|
||||
def test_previous_owner_pauses_after_another_device_claims():
|
||||
result = run_node(
|
||||
r"""
|
||||
let response = {revision:1, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:1000, running:true};
|
||||
let pauses = 0;
|
||||
let transferred = null;
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async()=>response,
|
||||
timer:{pause:()=>{pauses += 1;}},
|
||||
onTransferred:session=>{transferred=session;},
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
response = {...response, revision:2, device_id:'phone-b', elapsed_ms:2500};
|
||||
await sync.refresh();
|
||||
await sync.refresh();
|
||||
process.stdout.write(JSON.stringify({pauses, transferred}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["pauses"] == 1
|
||||
assert result["transferred"]["device_id"] == "phone-b"
|
||||
|
||||
|
||||
def test_owner_poll_publishes_current_elapsed_time():
|
||||
result = run_node(
|
||||
r"""
|
||||
const calls = [];
|
||||
let tick = null;
|
||||
let elapsed = 1000;
|
||||
const owned = {revision:1, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:1000, running:true};
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async (url, options={}) => {
|
||||
calls.push({method:options.method || 'GET', body:options.body ? JSON.parse(options.body) : null});
|
||||
return options.method === 'PATCH' ? {...owned, revision:2, elapsed_ms:elapsed} : owned;
|
||||
},
|
||||
timer:{snapshot:()=>({identity:owned.identity, elapsed_ms:elapsed, running:true})},
|
||||
setInterval:callback=>{tick=callback; return 7;},
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
sync.start();
|
||||
elapsed = 6500;
|
||||
await tick();
|
||||
process.stdout.write(JSON.stringify(calls));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result[-1] == {
|
||||
"method": "PATCH",
|
||||
"body": {
|
||||
"base_revision": 1,
|
||||
"device_id": "desktop-a",
|
||||
"identity": "issue:r:42:",
|
||||
"elapsed_ms": 6500,
|
||||
"running": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_publish_conflict_adopts_remote_owner_and_pauses_once():
|
||||
result = run_node(
|
||||
r"""
|
||||
const calls = [];
|
||||
const owned = {revision:2, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:1000, running:true};
|
||||
const remote = {...owned, revision:3, device_id:'phone-b', elapsed_ms:2500};
|
||||
let pauses = 0;
|
||||
const transfers = [];
|
||||
const statuses = [];
|
||||
let reads = 0;
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async (url, options={}) => {
|
||||
calls.push(options.method || 'GET');
|
||||
if (options.method === 'PATCH') {
|
||||
const error = new Error('session changed');
|
||||
error.status = 409;
|
||||
error.code = 'session_changed';
|
||||
throw error;
|
||||
}
|
||||
reads += 1;
|
||||
return reads === 1 ? owned : remote;
|
||||
},
|
||||
timer:{
|
||||
snapshot:()=>({identity:owned.identity, elapsed_ms:1500, running:true}),
|
||||
pause:()=>{pauses += 1;},
|
||||
},
|
||||
onTransferred:session=>transfers.push(session.device_id),
|
||||
onStatus:status=>statuses.push(status),
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
await sync.publish();
|
||||
await sync.refresh();
|
||||
process.stdout.write(JSON.stringify({calls, pauses, transfers, statuses, session:sync.session()}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["calls"] == ["GET", "PATCH", "GET", "GET"]
|
||||
assert result["session"]["device_id"] == "phone-b"
|
||||
assert result["pauses"] == 1
|
||||
assert result["transfers"] == ["phone-b"]
|
||||
assert "conflict" in result["statuses"]
|
||||
|
||||
|
||||
def test_rapid_publishes_are_single_flight_and_coalesce_latest_snapshot():
|
||||
result = run_node(
|
||||
r"""
|
||||
const owned = {revision:1, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:0, running:true};
|
||||
const bodies = [];
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
let releaseFirst;
|
||||
let patchCount = 0;
|
||||
const firstPatch = new Promise(resolve=>{releaseFirst=resolve;});
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async (url, options={}) => {
|
||||
if (!options.method) return owned;
|
||||
active += 1;
|
||||
peak = Math.max(peak, active);
|
||||
patchCount += 1;
|
||||
const body = JSON.parse(options.body);
|
||||
bodies.push(body);
|
||||
if (patchCount === 1) await firstPatch;
|
||||
active -= 1;
|
||||
return {...owned, revision:1 + patchCount, elapsed_ms:body.elapsed_ms, running:body.running};
|
||||
},
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
const first = sync.publish({identity:owned.identity, elapsed_ms:1000, running:true});
|
||||
await Promise.resolve();
|
||||
const middle = sync.publish({identity:owned.identity, elapsed_ms:2000, running:false});
|
||||
const latest = sync.publish({identity:owned.identity, elapsed_ms:3000, running:true});
|
||||
releaseFirst();
|
||||
await Promise.all([first, middle, latest]);
|
||||
process.stdout.write(JSON.stringify({peak, bodies, session:sync.session()}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["peak"] == 1
|
||||
assert [body["elapsed_ms"] for body in result["bodies"]] == [1000, 3000]
|
||||
assert result["session"]["elapsed_ms"] == 3000
|
||||
|
||||
|
||||
def test_remote_conflict_discards_queued_local_publishes_until_explicit_claim():
|
||||
result = run_node(
|
||||
r"""
|
||||
const owned = {revision:2, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:1000, running:true};
|
||||
const remote = {...owned, revision:3, device_id:'phone-b', elapsed_ms:2500};
|
||||
const calls = [];
|
||||
let reads = 0;
|
||||
let releaseConflict;
|
||||
const conflictReady = new Promise(resolve=>{releaseConflict=resolve;});
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async (url, options={}) => {
|
||||
calls.push(options.method || 'GET');
|
||||
if (options.method === 'PATCH') {
|
||||
await conflictReady;
|
||||
const error = new Error('session changed');
|
||||
error.status = 409;
|
||||
throw error;
|
||||
}
|
||||
reads += 1;
|
||||
return reads === 1 ? owned : remote;
|
||||
},
|
||||
timer:{pause:()=>{}},
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
const stale = sync.publish({identity:owned.identity, elapsed_ms:1500, running:true});
|
||||
await Promise.resolve();
|
||||
const queued = sync.publish({identity:owned.identity, elapsed_ms:2000, running:true});
|
||||
releaseConflict();
|
||||
await Promise.all([stale, queued]);
|
||||
process.stdout.write(JSON.stringify({calls, session:sync.session()}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["calls"] == ["GET", "PATCH", "GET"]
|
||||
assert result["session"]["device_id"] == "phone-b"
|
||||
|
||||
|
||||
def test_transient_failure_retains_latest_intent_for_retry():
|
||||
result = run_node(
|
||||
r"""
|
||||
const owned = {revision:4, device_id:'desktop-a', identity:'issue:r:42:', elapsed_ms:1000, running:true};
|
||||
const bodies = [];
|
||||
const statuses = [];
|
||||
let attempts = 0;
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async (url, options={}) => {
|
||||
if (!options.method) return owned;
|
||||
attempts += 1;
|
||||
bodies.push(JSON.parse(options.body));
|
||||
if (attempts === 1) {
|
||||
const error = new Error('temporarily unavailable');
|
||||
error.status = 503;
|
||||
throw error;
|
||||
}
|
||||
return {...owned, revision:5, elapsed_ms:bodies.at(-1).elapsed_ms};
|
||||
},
|
||||
onStatus:status=>statuses.push(status),
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
const first = await sync.publish({identity:owned.identity, elapsed_ms:4500, running:true});
|
||||
const retried = await sync.publish();
|
||||
process.stdout.write(JSON.stringify({first, retried, bodies, statuses}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["first"] is None
|
||||
assert [body["elapsed_ms"] for body in result["bodies"]] == [4500, 4500]
|
||||
assert result["retried"]["revision"] == 5
|
||||
assert "offline" in result["statuses"]
|
||||
|
||||
|
||||
def test_claim_transport_failure_stays_retryable_without_false_conflict():
|
||||
result = run_node(
|
||||
r"""
|
||||
const remote = {revision:7, device_id:'phone-b', identity:'issue:r:42:', elapsed_ms:9000, running:true};
|
||||
const calls = [];
|
||||
const statuses = [];
|
||||
const sync = createTodaySessionSync({
|
||||
getDeviceId:()=> 'desktop-a',
|
||||
fetchJson:async (url, options={}) => {
|
||||
calls.push(options.method || 'GET');
|
||||
if (!options.method) return remote;
|
||||
const error = new Error('gateway unavailable');
|
||||
error.status = 503;
|
||||
throw error;
|
||||
},
|
||||
onStatus:status=>statuses.push(status),
|
||||
});
|
||||
(async()=>{
|
||||
await sync.refresh();
|
||||
const claimed = await sync.claim();
|
||||
process.stdout.write(JSON.stringify({claimed, calls, statuses}));
|
||||
})().catch(error=>{console.error(error);process.exit(1);});
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["claimed"] is None
|
||||
assert result["calls"] == ["GET", "PATCH"]
|
||||
assert result["statuses"][-1] == "offline"
|
||||
assert "conflict" not in result["statuses"]
|
||||
+136
-1
@@ -4,7 +4,124 @@ import pytest
|
||||
import httpx
|
||||
|
||||
from src import main
|
||||
from src.today_store import TodayPlanFull, TodayStore
|
||||
from src.today_store import TodayPlanFull, TodaySessionConflict, TodayStore
|
||||
|
||||
|
||||
def test_active_session_is_durable_and_account_scoped(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
store = TodayStore(path, clock=lambda: 1234.5)
|
||||
|
||||
saved = store.update_session(
|
||||
"Timmy", base_revision=0, device_id="phone-a",
|
||||
identity="issue:stackchain/dashboard:42:", elapsed_ms=90_000, running=True,
|
||||
)
|
||||
|
||||
assert saved == {
|
||||
"revision": 1,
|
||||
"device_id": "phone-a",
|
||||
"identity": "issue:stackchain/dashboard:42:",
|
||||
"elapsed_ms": 90_000,
|
||||
"running": True,
|
||||
"break_deadline_at": None,
|
||||
"updated_at": 1234.5,
|
||||
}
|
||||
assert TodayStore(path).get_session("timmy") == saved
|
||||
assert store.get_session("alexander") == {
|
||||
"revision": 0,
|
||||
"device_id": "",
|
||||
"identity": "",
|
||||
"elapsed_ms": 0,
|
||||
"running": False,
|
||||
"break_deadline_at": None,
|
||||
"updated_at": None,
|
||||
}
|
||||
|
||||
|
||||
def test_timed_break_deadline_is_durable_in_the_account_session(tmp_path):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
store = TodayStore(path, clock=lambda: 1234.5)
|
||||
|
||||
saved = store.update_session(
|
||||
"timmy", base_revision=0, device_id="phone-a",
|
||||
identity="issue:r:42:", elapsed_ms=90_000, running=False,
|
||||
break_deadline_at=1_800_000,
|
||||
)
|
||||
|
||||
assert saved["break_deadline_at"] == 1_800_000
|
||||
assert saved["running"] is False
|
||||
assert TodayStore(path).get_session("timmy") == saved
|
||||
|
||||
|
||||
def test_active_session_claim_rejects_a_stale_revision(tmp_path):
|
||||
store = TodayStore(tmp_path / "today.sqlite3")
|
||||
first = store.update_session(
|
||||
"timmy", base_revision=0, device_id="phone-a", identity="issue:r:1:",
|
||||
elapsed_ms=1_000, running=True,
|
||||
)
|
||||
claimed = store.update_session(
|
||||
"timmy", base_revision=first["revision"], device_id="phone-b",
|
||||
identity=first["identity"], elapsed_ms=first["elapsed_ms"], running=True,
|
||||
)
|
||||
|
||||
with pytest.raises(TodaySessionConflict) as raised:
|
||||
store.update_session(
|
||||
"timmy", base_revision=first["revision"], device_id="phone-a",
|
||||
identity=first["identity"], elapsed_ms=5_000, running=True,
|
||||
)
|
||||
|
||||
assert raised.value.session == claimed
|
||||
assert store.get_session("timmy") == claimed
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_active_session_api_persists_a_bounded_break_deadline(monkeypatch, tmp_path):
|
||||
async def user():
|
||||
return {"login": "timmy"}
|
||||
|
||||
store = TodayStore(tmp_path / "today.sqlite3")
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "_today_store", lambda: store)
|
||||
payload = main.TodaySessionUpdate(
|
||||
base_revision=0, device_id="phone-a", identity="issue:r:1:",
|
||||
elapsed_ms=5_000, running=False, break_deadline_at=1_800_000,
|
||||
)
|
||||
|
||||
saved = await main.update_today_session(payload)
|
||||
|
||||
assert saved["break_deadline_at"] == 1_800_000
|
||||
assert (await main.get_today_session()) == saved
|
||||
|
||||
|
||||
def test_active_session_api_rejects_a_running_break():
|
||||
with pytest.raises(ValueError, match="break must remain paused"):
|
||||
main.TodaySessionUpdate(
|
||||
base_revision=0, device_id="phone-a", identity="issue:r:1:",
|
||||
elapsed_ms=5_000, running=True, break_deadline_at=1_800_000,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_active_session_api_returns_current_state_on_claim_conflict(monkeypatch, tmp_path):
|
||||
async def user():
|
||||
return {"login": "timmy"}
|
||||
|
||||
store = TodayStore(tmp_path / "today.sqlite3")
|
||||
current = store.update_session(
|
||||
"timmy", base_revision=0, device_id="phone-a", identity="issue:r:1:",
|
||||
elapsed_ms=5_000, running=True,
|
||||
)
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "_today_store", lambda: store)
|
||||
|
||||
payload = main.TodaySessionUpdate(
|
||||
base_revision=0, device_id="phone-b", identity="issue:r:1:",
|
||||
elapsed_ms=5_000, running=True,
|
||||
)
|
||||
with pytest.raises(main.HTTPException) as raised:
|
||||
await main.update_today_session(payload)
|
||||
|
||||
assert raised.value.status_code == 409
|
||||
assert raised.value.detail == {"code": "session_changed", "session": current}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -342,6 +459,21 @@ async def test_authenticated_today_api_uses_confirmed_account_and_csrf(monkeypat
|
||||
},
|
||||
)
|
||||
fetched = await client.get("/api/v1/today")
|
||||
changed_session = await client.patch(
|
||||
"/api/v1/today/session",
|
||||
json={
|
||||
"base_revision": 0,
|
||||
"device_id": "phone-a",
|
||||
"identity": "issue:stackchain/dashboard:357:",
|
||||
"elapsed_ms": 12_000,
|
||||
"running": True,
|
||||
},
|
||||
headers={
|
||||
"Origin": "https://test",
|
||||
"X-CSRF-Token": client.cookies["stackchain_csrf"],
|
||||
},
|
||||
)
|
||||
fetched_session = await client.get("/api/v1/today/session")
|
||||
|
||||
assert forbidden.status_code == 403
|
||||
assert changed.status_code == 200
|
||||
@@ -361,3 +493,6 @@ async def test_authenticated_today_api_uses_confirmed_account_and_csrf(monkeypat
|
||||
"estimates": {},
|
||||
}
|
||||
assert fetched.headers["cache-control"] == "no-store"
|
||||
assert changed_session.status_code == 200
|
||||
assert fetched_session.json() == changed_session.json()
|
||||
assert fetched_session.headers["cache-control"] == "no-store"
|
||||
@@ -5,6 +5,7 @@ from pathlib import Path
|
||||
|
||||
TODAY_SYNC = Path(__file__).parents[1] / "frontend" / "today-sync.js"
|
||||
COORDINATOR = Path(__file__).parents[1] / "frontend" / "outbox-coordinator.js"
|
||||
DASHBOARD = Path(__file__).parents[1] / "frontend" / "dashboard.js"
|
||||
|
||||
|
||||
def test_two_tabs_cannot_erase_each_others_today_edits_or_double_drain():
|
||||
@@ -83,6 +84,69 @@ sync.enqueue('add', 'issue:r:1:');
|
||||
}
|
||||
|
||||
|
||||
def test_operations_queued_in_the_same_millisecond_preserve_enqueue_order():
|
||||
script = f"""
|
||||
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
|
||||
const values = new Map();
|
||||
const storage = {{
|
||||
get length() {{ return values.size; }}, key: index => [...values.keys()][index] || null,
|
||||
getItem: key => values.get(key) || null,
|
||||
setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key),
|
||||
}};
|
||||
const operationIds = ['z-add-first', 'a-move-second'];
|
||||
const sync = createTodaySync({{
|
||||
storage, getLogin: () => 'timmy', now: () => 1000,
|
||||
createOperationId: () => operationIds.shift(),
|
||||
fetchJson: async () => ({{revision: 0, ids: []}}),
|
||||
}});
|
||||
sync.enqueue('add', 'issue:r:1:');
|
||||
sync.enqueue('move', 'issue:r:1:', 'up');
|
||||
process.stdout.write(JSON.stringify(sync.pending().map(operation => operation.operation_id)));
|
||||
"""
|
||||
|
||||
assert json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout) == ["z-add-first", "a-move-second"]
|
||||
|
||||
|
||||
def test_corrupt_queue_record_does_not_hide_or_strand_valid_today_edits():
|
||||
script = f"""
|
||||
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
|
||||
const prefix = 'stackchain.today-sync.v1.timmy.operation.';
|
||||
const values = new Map([
|
||||
[prefix + 'first', JSON.stringify({{queued_at: 1000, operation: {{operation_id:'first', action:'add', item_id:'issue:r:1:'}}}})],
|
||||
[prefix + 'broken', '{{not-json'],
|
||||
[prefix + 'invalid', JSON.stringify({{queued_at: 1000, operation: {{operation_id:'invalid', action:'erase-everything'}}}})],
|
||||
[prefix + 'second', JSON.stringify({{queued_at: 1001, operation: {{operation_id:'second', action:'move', item_id:'issue:r:2:', direction:'up'}}}})],
|
||||
]);
|
||||
const storage = {{get length(){{return values.size}},key:i=>[...values.keys()][i]||null,
|
||||
getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
|
||||
const patches=[]; const statuses=[];
|
||||
const sync=createTodaySync({{storage,getLogin:()=> 'timmy',
|
||||
fetchJson:async(_url,options={{}})=>{{const operations=JSON.parse(options.body).operations;patches.push(...operations);return {{revision:1,ids:['issue:r:1:','issue:r:2:'],accepted_operation_ids:operations.map(x=>x.operation_id)}}}},
|
||||
onRemoteIds:()=>{{}},onStatus:(state,detail={{}})=>statuses.push([state,detail.discarded||0])}});
|
||||
(async()=>{{const result=await sync.flush();process.stdout.write(JSON.stringify({{
|
||||
result,patches,statuses,remaining:[...values.keys()].filter(key=>key.startsWith(prefix)),pending:sync.pending()
|
||||
}}));}})();
|
||||
"""
|
||||
result = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert result["result"] is True
|
||||
assert [item["operation_id"] for item in result["patches"]] == ["first", "second"]
|
||||
assert result["pending"] == []
|
||||
assert result["remaining"] == []
|
||||
assert result["statuses"][-1] == ["recovered", 2]
|
||||
|
||||
|
||||
def test_today_sync_reports_queue_recovery_instead_of_plain_saved_status():
|
||||
source = DASHBOARD.read_text()
|
||||
|
||||
assert "Today queue recovered" in source
|
||||
assert "discarded ${detail.discarded} unreadable device record" in source
|
||||
|
||||
|
||||
def test_today_capacity_configuration_syncs_offline_and_adopts_remote_plan():
|
||||
script = f"""
|
||||
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
|
||||
@@ -127,7 +191,7 @@ sync.enqueueConfiguration(120, {{'issue:r:1:':60}});
|
||||
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-v117" in source
|
||||
assert "stackchain-dashboard-shell-v120" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "frontend" / "today-timer.js"
|
||||
|
||||
|
||||
def test_timer_adopts_claimed_elapsed_time():
|
||||
script = SOURCE.read_text() + r"""
|
||||
const values = new Map();
|
||||
const storage = {
|
||||
getItem:key=>values.get(key)||null,
|
||||
setItem:(key,value)=>values.set(key,value),
|
||||
};
|
||||
let now = 100000;
|
||||
const timer = createTodayTimer({storage, getLogin:()=> 'timmy', now:()=>now});
|
||||
const adopted = timer.adopt('issue:r:42:', 90000, true);
|
||||
now = 105000;
|
||||
process.stdout.write(JSON.stringify({adopted, snapshot:timer.snapshot()}));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
result = json.loads(completed.stdout)
|
||||
|
||||
assert result == {
|
||||
"adopted": True,
|
||||
"snapshot": {"identity": "issue:r:42:", "elapsed_ms": 95000, "running": True},
|
||||
}
|
||||
|
||||
|
||||
def test_timer_reports_durable_changes_for_session_sync():
|
||||
script = SOURCE.read_text() + r"""
|
||||
const values = new Map();
|
||||
const storage = {getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)};
|
||||
let now = 0;
|
||||
const changes = [];
|
||||
const timer = createTodayTimer({
|
||||
storage, getLogin:()=> 'timmy', now:()=>now,
|
||||
onChange:snapshot=>changes.push(snapshot),
|
||||
});
|
||||
timer.activate('issue:r:42:');
|
||||
now = 5000;
|
||||
timer.pause();
|
||||
process.stdout.write(JSON.stringify(changes));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
|
||||
assert json.loads(completed.stdout) == [
|
||||
{"identity": "issue:r:42:", "elapsed_ms": 0, "running": True},
|
||||
{"identity": "issue:r:42:", "elapsed_ms": 5000, "running": False},
|
||||
]
|
||||
@@ -209,6 +209,94 @@ process.stdout.write(JSON.stringify({{completed, calls}}));
|
||||
}
|
||||
|
||||
|
||||
def test_done_for_today_can_restore_original_order_and_estimate_with_inverse_sync():
|
||||
script = f"""
|
||||
const createTodayWork = require({json.dumps(str(TODAY_WORK))});
|
||||
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
|
||||
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 todayWork = createTodayWork({{storage, getLogin:()=> 'timmy'}});
|
||||
const item = number => ({{kind:'issue', repository:'r', number}});
|
||||
todayWork.replace(['issue:r:1:', 'issue:r:2:', 'issue:r:3:']);
|
||||
todayWork.replacePlanning({{capacity_minutes:180, estimates:{{'issue:r:1:':30,'issue:r:2:':60,'issue:r:3:':45}}}});
|
||||
const calls = [];
|
||||
const offers = [];
|
||||
const complete = createTodayCompletion({{
|
||||
todayWork,
|
||||
todaySync: {{enqueue:(action,id,direction)=>{{calls.push([action,id,direction]);return true;}},flush:()=>calls.push(['flush'])}},
|
||||
workSession: {{complete:()=>calls.push(['advance'])}},
|
||||
refresh:()=>calls.push(['refresh']), warm:()=>calls.push(['warm']), announce:message=>calls.push(['announce',message]),
|
||||
now:()=>1000, onOffer:offer=>offers.push(offer),
|
||||
}});
|
||||
const completed = complete(item(2));
|
||||
const restored = complete.undo();
|
||||
process.stdout.write(JSON.stringify({{
|
||||
completed, restored, ids:todayWork.read(), planning:todayWork.planning(), calls,
|
||||
offer:offers[0] && {{identity:offers[0].identity, expires_at:offers[0].expires_at}},
|
||||
}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"completed": True,
|
||||
"restored": "restored",
|
||||
"ids": ["issue:r:1:", "issue:r:2:", "issue:r:3:"],
|
||||
"planning": {
|
||||
"capacity_minutes": 180,
|
||||
"estimates": {
|
||||
"issue:r:1:": 30,
|
||||
"issue:r:2:": 60,
|
||||
"issue:r:3:": 45,
|
||||
},
|
||||
},
|
||||
"calls": [
|
||||
["remove", "issue:r:2:", None], ["flush"], ["refresh"], ["warm"],
|
||||
["advance"], ["announce", "Done for Today. The Gitea item is unchanged."],
|
||||
["add", "issue:r:2:", None], ["move", "issue:r:2:", "up"],
|
||||
["flush"], ["refresh"], ["warm"],
|
||||
["announce", "Restored to Today. Your current work session is unchanged."],
|
||||
],
|
||||
"offer": {"identity": "issue:r:2:", "expires_at": 11000},
|
||||
}
|
||||
|
||||
|
||||
def test_today_completion_undo_expires_and_rejects_a_changed_plan_without_overwrite():
|
||||
script = f"""
|
||||
const createTodayWork = require({json.dumps(str(TODAY_WORK))});
|
||||
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
|
||||
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 todayWork = createTodayWork({{storage, getLogin:()=> 'timmy'}});
|
||||
const item = number => ({{kind:'issue', repository:'r', number}});
|
||||
let clock = 1000;
|
||||
const messages = [];
|
||||
const complete = createTodayCompletion({{
|
||||
todayWork, todaySync:{{enqueue:()=>true,flush:()=>undefined}}, workSession:{{complete:()=>undefined}},
|
||||
refresh:()=>undefined, warm:()=>undefined, announce:message=>messages.push(message), now:()=>clock,
|
||||
}});
|
||||
todayWork.replace(['issue:r:1:', 'issue:r:2:']);
|
||||
complete(item(1));
|
||||
todayWork.replace(['issue:r:2:', 'issue:r:3:']);
|
||||
const changed = complete.undo();
|
||||
todayWork.replace(['issue:r:1:', 'issue:r:2:']);
|
||||
complete(item(1));
|
||||
clock = 11000;
|
||||
const expired = complete.undo();
|
||||
process.stdout.write(JSON.stringify({{changed, expired, ids:todayWork.read(), messages}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"changed": "changed",
|
||||
"expired": "expired",
|
||||
"ids": ["issue:r:2:"],
|
||||
"messages": [
|
||||
"Done for Today. The Gitea item is unchanged.",
|
||||
"Today changed on this device. Add the item back from My Work.",
|
||||
"Done for Today. The Gitea item is unchanged.",
|
||||
"Undo expired. Add the item back to Today from My Work.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_done_for_today_does_not_advance_when_local_plan_persistence_fails():
|
||||
script = f"""
|
||||
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
|
||||
@@ -381,6 +469,18 @@ async def test_today_session_sheets_offer_a_touch_safe_plan_only_completion_acti
|
||||
assert "grid-template-columns:repeat(2,minmax(0,1fr))" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_completion_surfaces_a_touch_safe_accessible_undo_receipt():
|
||||
html = await dashboard()
|
||||
|
||||
assert 'id="today-completion-undo" role="status" aria-live="assertive" hidden' in html
|
||||
assert 'id="undo-today-completion"' in html
|
||||
assert 'Removed from Today. Undo?' in html
|
||||
assert "getElementById('today-completion-undo')" in TODAY_COMPLETION.read_text()
|
||||
assert ".today-completion-undo button { min-height:44px" in html
|
||||
assert "bottom:calc(224px + env(safe-area-inset-bottom))" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_activates_today_lifecycle_convergence():
|
||||
html = await dashboard()
|
||||
|
||||
Reference in new issue
Block a user