Archived
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e8efdb2bb | ||
|
|
e92e476f49 | ||
|
|
4a6a829401 | ||
|
|
c03d0a091f | ||
|
|
2f5df33020 | ||
|
|
5d517861f0 | ||
|
|
59c87f06a2 | ||
|
|
f76b2f8289 | ||
|
|
7c4e798776 | ||
|
|
317fc7371a | ||
|
|
c7d38593dd | ||
|
|
a13a13d90c | ||
|
|
666671ee59 | ||
|
|
d01f502e70 | ||
|
|
3fd5983df6 | ||
|
|
6afdad6fe4 | ||
|
|
449ab78991 | ||
|
|
95887d7493 | ||
|
|
965a73ab49 | ||
|
|
067fb76ebd | ||
|
|
d47205a561 | ||
|
|
1be9da3685 | ||
|
|
a8c1329676 | ||
|
|
d63765a9b1 | ||
|
|
c87d56c939 | ||
|
|
e234d6b6c3 | ||
|
|
edaeba4a4e | ||
|
|
9d8a362583 |
No files matched your search
@@ -57,7 +57,7 @@ jobs:
|
||||
pip install -r requirements-e2e.txt
|
||||
python3 -m playwright install --with-deps chromium
|
||||
- name: Exercise packaged mobile work journeys
|
||||
run: python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py tests/e2e/test_mobile_search_preview_navigation.py tests/e2e/test_mobile_search_week_plan.py tests/e2e/test_mobile_find_work_release.py tests/e2e/test_mobile_home_bootstrap_release.py tests/e2e/test_mobile_sign_out_release.py tests/e2e/test_mobile_today_handoff_release.py tests/e2e/test_mobile_today_wrap_up_release.py tests/e2e/test_mobile_today_summary_release.py tests/e2e/test_mobile_tomorrow_conflict_release.py tests/e2e/test_mobile_week_ahead_release.py tests/e2e/test_mobile_wrap_up_handoff_release.py -q
|
||||
run: python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py tests/e2e/test_mobile_search_preview_navigation.py tests/e2e/test_mobile_search_week_plan.py tests/e2e/test_mobile_find_work_release.py tests/e2e/test_mobile_home_bootstrap_release.py tests/e2e/test_mobile_sign_out_release.py tests/e2e/test_mobile_today_handoff_release.py tests/e2e/test_mobile_today_wrap_up_release.py tests/e2e/test_mobile_today_summary_release.py tests/e2e/test_mobile_tomorrow_conflict_release.py tests/e2e/test_mobile_week_ahead_release.py tests/e2e/test_mobile_today_week_reschedule_release.py tests/e2e/test_mobile_wrap_up_handoff_release.py -q
|
||||
|
||||
release-candidate:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -82,6 +82,11 @@ over-capacity admission requires a second confirmation. The action claims unassi
|
||||
checks, stages the canonical issue through the account-bound Week Ahead outbox, and preserves the Search
|
||||
preview through cancel or browser Back. Offline saves report **sync pending**; if assignment succeeds but
|
||||
local planning fails, the dashboard reports **Assigned, not planned** and leaves the issue recoverable in My Work.
|
||||
The live mobile Week Ahead overview also offers **Remove from week** for active planned work. It removes only the
|
||||
private planning placement—not assignment, issue state, or Gitea content—and immediately recalculates the day's
|
||||
load. A 10-second **Undo** receipt restores the exact day, list position, and estimate. Both transitions use the
|
||||
account-bound Week Ahead outbox, remain **sync pending** after delivery failure, and stay unavailable in a read-only
|
||||
offline snapshot.
|
||||
Search selection mode extends that flow across several open issues with **Plan Week Ahead**. One phone-safe
|
||||
review assigns each issue a future day and estimate, validates five-item limits and daily capacity before any
|
||||
claim, and requires a second confirmation for overload. Confirmed rows are staged into one canonical Week
|
||||
@@ -132,7 +137,10 @@ explicit **Add blocked item anyway** override, while an unavailable dependency l
|
||||
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
|
||||
concurrently changed plan is reported without overwriting newer work. Rescheduling Today work into
|
||||
Week Ahead uses a bounded account-scoped FIFO on the device: multiple offline moves survive reload,
|
||||
deliver oldest-first with stable operation IDs, and rebase each later move on the confirmed plan revisions
|
||||
without concurrent requests. 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 wrap-up, **Share day summary** opens a private review of the exact worked-on and tomorrow selections. Every row is opt-in adjustable, actual time is excluded by default, and an optional bounded note is previewed before the native share sheet or clipboard fallback. Canceling or closing keeps the account-scoped device draft; successful sharing or **Discard draft** removes it.
|
||||
|
||||
@@ -172,7 +180,9 @@ work titles and references, load versus capacity, overloads, and pending sync wi
|
||||
is empty and no work session is active, **Start this day early** confirms the next planned date, item count, minutes,
|
||||
and capacity before atomically moving only that day into Today; offline, pending, stale, or non-empty plans remain
|
||||
unchanged. **Edit day** enters one date and returns to the refreshed overview; **Edit week** starts the continuous
|
||||
planning pass.
|
||||
planning pass. Closing an issue from its Week Ahead detail retires that identity and estimate from every future
|
||||
week day in one durable update while preserving sibling order and daily capacity. The open overview recalculates
|
||||
immediately; an unavailable save remains visibly **sync pending** and retries through the existing lifecycle.
|
||||
**Plan Week Ahead** continues through seven local dates and now finishes on a mobile review step instead of
|
||||
closing after the seventh save. The review shows planned minutes against each day’s capacity, marks overloads,
|
||||
and flags work assigned to more than one date. Operators can move an item to another date without copying it;
|
||||
@@ -326,7 +336,18 @@ export STACKCHAIN_LOGIN_ATTEMPT_DB='/var/lib/stackchain-dashboard/login-attempts
|
||||
# it. Missing, malformed, wrong-key, or modified state fails closed without
|
||||
# returning content. Legacy Today/Later, Saved Search, and Security activity rows
|
||||
# migrate atomically on first use without changing logical revisions or journal IDs.
|
||||
# The single-key setting remains the compatible first deployment and writes v1 envelopes.
|
||||
export STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY='<base64-encoded-32-byte-key>'
|
||||
# After all workers run keyring-capable code, configure at most four named keys and
|
||||
# select the active write key. Keep the old key present during the rolling deployment.
|
||||
# Key IDs use 1-32 letters, digits, underscores, or hyphens.
|
||||
export STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS='{"legacy":"<old-base64-key>","2026-08":"<new-base64-key>"}'
|
||||
export STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID='2026-08'
|
||||
# New writes use authenticated v2 envelopes carrying the active key ID. Rewrap every
|
||||
# shared store with the restart-safe command; output contains store-level counts only.
|
||||
# Run it again until every store reports failed=0, migrated=0, and current=total,
|
||||
# then remove the old key from every worker. Retain all keys and investigate if it exits 1.
|
||||
python3 scripts/rotate_private_state.py
|
||||
# Required for cross-device unfiled Draft sync. The single-key setting remains
|
||||
# supported for the first deployment of keyring-capable code and writes v1 envelopes.
|
||||
# Inject the base64 encoding of exactly 32 random bytes from a secret manager.
|
||||
|
||||
@@ -267,6 +267,19 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.week-plan-dates[hidden] { display:none; }
|
||||
.week-plan-dates button { min-height:44px; min-width:86px; flex:0 0 auto; padding:6px 10px; }
|
||||
.week-plan-dates button[aria-current="date"] { color:#bfdbfe; background:#17365a; border-color:#60a5fa; }
|
||||
.today-week-reschedule { box-sizing:border-box; width:100%; max-width:none; height:100%; max-height:none; margin:0; padding:0; border:0; background:rgba(5,12,21,.82); color:inherit; }
|
||||
.today-week-reschedule::backdrop { background:rgba(5,12,21,.82); }
|
||||
.today-week-reschedule-panel { width:min(100%,560px); box-sizing:border-box; min-height:100%; margin-left:auto; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); background:#0b1526; overflow-x:hidden; }
|
||||
.today-week-reschedule-panel header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
|
||||
.today-week-reschedule-panel h2, .today-week-reschedule-panel header p { margin-top:0; }
|
||||
.today-week-reschedule-panel input { box-sizing:border-box; width:100%; min-height:44px; margin:6px 0 10px; font-size:16px; }
|
||||
.today-week-reschedule-days { display:grid; gap:8px; margin:14px 0; }
|
||||
.today-week-reschedule-days button { min-height:44px; display:grid; grid-template-columns:minmax(0,1fr) auto; gap:8px; text-align:left; overflow-wrap:anywhere; }
|
||||
.today-week-reschedule-days button[aria-checked="true"] { border-color:#60a5fa; background:#17365a; color:#eff6ff; }
|
||||
.today-week-reschedule-days button:disabled { opacity:.58; }
|
||||
#cancel-today-week-reschedule { min-height:44px; }
|
||||
#confirm-today-week-reschedule { position:sticky; bottom:0; width:100%; min-height:48px; }
|
||||
#today-week-reschedule-status { min-height:1.4em; color:#fde68a; }
|
||||
.back-to-week-review { width:100%; min-height:44px; margin:4px 0 12px; }
|
||||
.tomorrow-conflict-review { margin-top:14px; }
|
||||
.tomorrow-conflict-plans { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }
|
||||
@@ -333,6 +346,11 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.week-review-item-open { display:block; width:100%; min-width:0; min-height:44px; padding:8px; border:0; border-radius:8px; background:transparent; color:inherit; text-align:left; }
|
||||
.week-review-item-open:hover { background:#173453; }
|
||||
.week-review-item-open:focus-visible { outline:3px solid #93c5fd; outline-offset:2px; }
|
||||
.week-review-unplan { width:100%; min-height:44px; border-color:#6b87a6; background:transparent; color:#d7e5f5; }
|
||||
.week-review-pull { grid-column:1/-1; width:100%; min-height:44px; border-color:#60a5fa; background:#1d4f7a; color:#eff6ff; font-weight:800; }
|
||||
.week-review-unplan { grid-column:1/-1; }
|
||||
.week-unplan-receipt { margin:12px 0 6px; padding:10px 12px; border:1px solid #60a5fa; border-radius:10px; background:#112d4d; color:#dbeafe; }
|
||||
#undo-week-unplan { width:100%; min-height:44px; margin-bottom:8px; border-color:#60a5fa; background:#1d4f7a; color:#eff6ff; font-weight:800; }
|
||||
.week-start-early { display:block; width:100%; min-height:44px; margin-top:12px; border-color:#60a5fa; background:#1d4f7a; color:#eff6ff; font-weight:800; }
|
||||
.week-start-early:focus-visible { outline:3px solid #bfdbfe; outline-offset:2px; }
|
||||
.week-review-item-copy strong, .week-review-item-copy small { overflow-wrap:anywhere; }
|
||||
|
||||
+13
-11
@@ -391,13 +391,14 @@
|
||||
});
|
||||
const weekPlan = createWeekPlan({
|
||||
fetchJson:fetchReviewJson,localDate:todayRollover.localDate,timeZone:todayRollover.timeZone,
|
||||
storage:localStorage,getLogin:() => planningOwnerLogin,
|
||||
storage:localStorage,getLogin:() => planningOwnerLogin,coordinator:outboxCoordinator,
|
||||
});
|
||||
function openWeekPlanner(trigger) { planningTomorrow=false; return weekFlow.open(trigger); }
|
||||
function renderTomorrowQueueSummary(value) {
|
||||
qs('#mobile-tomorrow-summary').textContent = value ? tomorrowPlan.summary(value) : tomorrowPlan.summary();
|
||||
}
|
||||
function syncPendingTomorrow() {
|
||||
weekFlow.resumePull()&&weekFlow.flushPull();
|
||||
if (!tomorrowPlan.pending()) return Promise.resolve(false);
|
||||
return tomorrowPlan.flush().then(saved => {
|
||||
renderTomorrowQueueSummary(saved);
|
||||
@@ -410,7 +411,7 @@
|
||||
if (conflict) renderTomorrowQueueSummary({ids:[],sync_pending:false,conflict:true});
|
||||
qs('#mobile-tomorrow-summary').textContent = conflict ? 'Conflict · review required' : qs('#mobile-tomorrow-summary').textContent;
|
||||
qs('#my-work-action-status').textContent = conflict ?
|
||||
'Another device changed Tomorrow. Both plans are preserved; open Tomorrow to choose one.' :
|
||||
'Another device changed Tomorrow. Review it.' :
|
||||
`${error.message || 'Tomorrow sync is unavailable.'} Saved on this phone · sync pending.`;
|
||||
return false;
|
||||
});
|
||||
@@ -455,9 +456,10 @@
|
||||
const weekItem=id=>[...todayMyWork,...activeMyWork].find(item=>todayWork.identity(item)===id);
|
||||
const weekFlow=createWeekPlanWorkflow({controller:weekPlan,qs,
|
||||
getItem:weekItem,openItem:openRoutedWork,
|
||||
openPlanner:openPlanToday,setReviewMode:value=>qs('#plan-today-sheet').classList.toggle('week-review-mode',value),
|
||||
openPlanner:openPlanToday,setReviewMode:v=>qs('#plan-today-sheet').classList.toggle('week-review-mode',v),
|
||||
escapeHtml,escapeAttribute:escAttr,todayWork,
|
||||
t:()=>latestTodayPlan,r:refreshMyWorkView,w:warmTodayOffline});
|
||||
t:v=>v?latestTodayPlan=v:latestTodayPlan,r:refreshMyWorkView,w:warmTodayOffline,
|
||||
x:currentTodayProgressTarget});
|
||||
const weekCalendar=StackchainWeekCalendar.mountWeekCalendarHandoff({qs,getItem:weekItem,escapeHtml,escapeAttribute:escAttr,
|
||||
onDone:()=>{weekFlow.finish();taskOverlayHistory.leave();},
|
||||
});
|
||||
@@ -474,9 +476,8 @@
|
||||
onRemotePlan: plan => {
|
||||
if (!planningOwnerLogin) return;
|
||||
latestTodayPlan = plan;
|
||||
const startDayLaunch = window.location.hash === '#/my-work/start-day';
|
||||
weekFlow.promote(plan).finally(() => {
|
||||
if (!startDayLaunch) return;
|
||||
if (window.location.hash !== '#/my-work/start-day') return;
|
||||
window.history.replaceState({}, '', '#/my-work/today');
|
||||
openMobileStartDay();
|
||||
});
|
||||
@@ -484,8 +485,8 @@
|
||||
capacity_minutes: plan.capacity_minutes ?? null,
|
||||
estimates: plan.estimates || {},
|
||||
});
|
||||
const reviewState = todayRollover.reviewState(plan);
|
||||
if (!['stale', 'legacy'].includes(reviewState)) {
|
||||
const s = todayRollover.reviewState(plan);
|
||||
if (!['stale', 'legacy'].includes(s)) {
|
||||
rolloverReviewPlan = null;
|
||||
qs('#plan-today').textContent = 'Plan Today';
|
||||
return;
|
||||
@@ -7115,11 +7116,11 @@
|
||||
closeIssueSheet();
|
||||
refreshMyWorkView({ reconcileSession:false });
|
||||
if (!outcome.advanced) {
|
||||
qs('#my-work-action-status').textContent = 'Issue closure queued, but Today still needs completion.';
|
||||
qs('#my-work-action-status').textContent = 'Issue close queued; Today still needs completion.';
|
||||
} else if (outcome.admission.background) {
|
||||
qs('#my-work-action-status').textContent = 'Issue closure queued for reconnect. Next Today item opened.';
|
||||
qs('#my-work-action-status').textContent = 'Issue close queued. Next Today item opened.';
|
||||
} else {
|
||||
qs('#my-work-action-status').textContent = 'Issue closure saved for next launch. Next Today item opened.';
|
||||
qs('#my-work-action-status').textContent = 'Issue close saved. Next Today item opened.';
|
||||
}
|
||||
} catch (error) {
|
||||
qs('#issue-sheet-status').textContent = error.message + ' The issue remains in Today; retry.';
|
||||
@@ -7733,6 +7734,7 @@
|
||||
planningOwnerLogin = confirmedOwnerLogin;
|
||||
interruptionPrompt.restore();
|
||||
updatePlanningAvailability();
|
||||
syncPendingTomorrow();
|
||||
saved.notifications = notificationReadOutbox.suppress(saved.notifications || []);
|
||||
lastNotifications = saved.notifications;
|
||||
notificationPagination = saved.notification_pagination || { page:1, total:lastNotifications.length, has_more:false };
|
||||
|
||||
@@ -526,6 +526,8 @@
|
||||
</section>
|
||||
<div class="week-review-duplicates" id="week-review-duplicates" role="alert" hidden></div>
|
||||
<div class="week-review-days" id="week-review-days"></div>
|
||||
<div class="week-unplan-receipt" id="week-unplan-receipt" role="status" aria-live="polite" hidden></div>
|
||||
<button id="undo-week-unplan" type="button" hidden>Undo</button>
|
||||
<div class="small week-review-status" id="week-review-status" role="status" aria-live="polite"></div>
|
||||
<button id="edit-week-plan" type="button" hidden>Edit week</button>
|
||||
<button id="confirm-week-plan" type="button">Confirm Week Ahead</button>
|
||||
@@ -1820,10 +1822,25 @@
|
||||
<button class="mobile-today-blocked" data-mobile-today-blocked type="button" hidden>Report blocker</button>
|
||||
<button data-today-break-open type="button">Take break</button>
|
||||
<button data-work-session-adjust-plan type="button" hidden>Adjust remaining plan</button>
|
||||
<button data-work-session-reschedule-week type="button">Reschedule to Week Ahead</button>
|
||||
<button data-mobile-today-end type="button">End session</button>
|
||||
</div>
|
||||
</section>
|
||||
</dialog>
|
||||
<dialog class="today-week-reschedule" id="today-week-reschedule" aria-labelledby="today-week-reschedule-title">
|
||||
<section class="today-week-reschedule-panel">
|
||||
<header>
|
||||
<div><p class="small muted">Active Today item</p><h2 id="today-week-reschedule-title">Reschedule to Week Ahead</h2></div>
|
||||
<button id="cancel-today-week-reschedule" type="button">Cancel</button>
|
||||
</header>
|
||||
<p class="small">Choose a future day after reviewing its current planned load. Today will continue with the next ready item.</p>
|
||||
<div class="today-week-reschedule-days" id="today-week-reschedule-days" role="radiogroup" aria-label="Week Ahead destination"></div>
|
||||
<label for="today-week-reschedule-estimate">Estimate in minutes</label>
|
||||
<input id="today-week-reschedule-estimate" type="number" inputmode="numeric" min="5" max="1440" step="5" required />
|
||||
<p id="today-week-reschedule-status" class="small" role="status" aria-live="assertive"></p>
|
||||
<button id="confirm-today-week-reschedule" type="button" disabled>Move to Week Ahead & continue</button>
|
||||
</section>
|
||||
</dialog>
|
||||
<dialog class="today-progress-sheet" id="today-progress-sheet" aria-labelledby="today-progress-title">
|
||||
<section class="today-progress-panel">
|
||||
<header><div><p class="small muted">Active Today item</p><h2 id="today-progress-title">Add progress update</h2></div><button id="cancel-today-progress" type="button">Cancel</button></header>
|
||||
@@ -2064,6 +2081,7 @@
|
||||
<script src="static/week-calendar.js"></script>
|
||||
<script src="static/week-calendar-import.js"></script>
|
||||
<script src="static/week-plan.js"></script>
|
||||
<script src="static/today-week-reschedule.js"></script>
|
||||
<script src="static/search-week-plan.js"></script>
|
||||
<script src="static/today-sync.js"></script>
|
||||
<script src="static/today-rollover.js"></script>
|
||||
|
||||
@@ -572,6 +572,7 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
|
||||
headers: { Accept: 'application/json' },
|
||||
}).then(result => {
|
||||
if (result?.state !== 'closed') throw new Error('Issue closure was not confirmed.');
|
||||
globalThis.dispatchEvent?.(new CustomEvent('stackchain:issue-closed',{detail:item}));
|
||||
return result;
|
||||
}).finally(() => { closeRequest = null; });
|
||||
return closeRequest;
|
||||
|
||||
@@ -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-v128';
|
||||
const CACHE = 'stackchain-dashboard-shell-v130';
|
||||
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;
|
||||
@@ -127,6 +127,7 @@ const SHELL = [
|
||||
BASE + 'static/week-calendar.js',
|
||||
BASE + 'static/week-calendar-import.js',
|
||||
BASE + 'static/week-plan.js',
|
||||
BASE + 'static/today-week-reschedule.js',
|
||||
BASE + 'static/search-week-plan.js',
|
||||
BASE + 'static/today-sync.js',
|
||||
BASE + 'static/today-rollover.js',
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
function createTodayWeekReschedule({
|
||||
week,
|
||||
api,
|
||||
getToday,
|
||||
adoptToday = () => {},
|
||||
operationId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()),
|
||||
storage = null,
|
||||
getLogin = () => '',
|
||||
now = () => Date.now(),
|
||||
} = {}) {
|
||||
let current = null;
|
||||
let flushing = null;
|
||||
const storagePrefix = 'stackchain.today-week-reschedule.v1.';
|
||||
|
||||
function storageKey() {
|
||||
const login = String(getLogin?.() || '').trim().toLowerCase();
|
||||
return login ? storagePrefix + encodeURIComponent(login) : '';
|
||||
}
|
||||
|
||||
function validRecord(value) {
|
||||
return typeof value?.body?.operation_id === 'string' &&
|
||||
Array.isArray(value?.today?.ids) && Array.isArray(value?.week?.days);
|
||||
}
|
||||
|
||||
function readQueue() {
|
||||
const key = storageKey();
|
||||
if (!key || !storage) return [];
|
||||
try {
|
||||
const value = JSON.parse(storage.getItem(key) || 'null');
|
||||
if (Array.isArray(value?.records)) return value.records.filter(validRecord);
|
||||
return validRecord(value) ? [value] : [];
|
||||
} catch (_error) { return []; }
|
||||
}
|
||||
|
||||
function saveQueue(records) {
|
||||
const key = storageKey();
|
||||
if (!key || !storage) return false;
|
||||
try {
|
||||
if (!records.length) storage.removeItem(key);
|
||||
else storage.setItem(key, JSON.stringify({version:2, records}));
|
||||
return true;
|
||||
}
|
||||
catch (_error) { return false; }
|
||||
}
|
||||
|
||||
function persist(record) { return saveQueue([...readQueue(), record]); }
|
||||
|
||||
function pending() {
|
||||
const key = storageKey();
|
||||
if (!key || !storage) return null;
|
||||
return readQueue()[0] || null;
|
||||
}
|
||||
|
||||
function resume() {
|
||||
const records = readQueue();
|
||||
const record = records[records.length - 1];
|
||||
if (!record) return null;
|
||||
adoptToday(record.today);
|
||||
week.adopt(record.week);
|
||||
return {...record, sync_pending:true, pending_count:records.length};
|
||||
}
|
||||
|
||||
async function restoreConflict(error) {
|
||||
if (error?.status !== 409) throw error;
|
||||
const [today, weekState] = await Promise.all([api('api/v1/today'), api('api/v1/week')]);
|
||||
adoptToday(today);
|
||||
week.adopt(weekState);
|
||||
const conflict = new Error('Plans changed on another device. Review and retry this saved move.');
|
||||
conflict.status = 409;
|
||||
throw conflict;
|
||||
}
|
||||
|
||||
function flush() {
|
||||
if (flushing) return flushing;
|
||||
if (!pending()) return Promise.resolve(false);
|
||||
flushing = (async () => {
|
||||
let result = null;
|
||||
while (true) {
|
||||
const records = readQueue();
|
||||
const record = records[0];
|
||||
if (!record) return result ? {...result, sync_pending:false, pending_count:0} : false;
|
||||
try {
|
||||
result = await api('api/v1/week/reschedule', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(record.body),
|
||||
});
|
||||
} catch (error) { await restoreConflict(error); }
|
||||
adoptToday(result.today);
|
||||
week.adopt(result.week);
|
||||
const latest = readQueue();
|
||||
if (latest[0]?.body?.operation_id !== record.body.operation_id) continue;
|
||||
const remaining = latest.slice(1).map((entry, index) => index ? entry : ({
|
||||
...entry,
|
||||
body:{...entry.body, today_revision:result.today.revision, week_revision:result.week.revision},
|
||||
}));
|
||||
if (!saveQueue(remaining)) throw new Error('Move synced, but its local queue could not be updated.');
|
||||
}
|
||||
})().finally(() => { flushing = null; });
|
||||
return flushing;
|
||||
}
|
||||
|
||||
function optimisticSnapshots(planDate, estimate) {
|
||||
const today = {
|
||||
...current.today,
|
||||
ids: current.today.ids.filter(id => id !== current.identity),
|
||||
estimates: {...(current.today.estimates || {})},
|
||||
};
|
||||
delete today.estimates[current.identity];
|
||||
const days = (current.week.days || []).map(day => {
|
||||
const estimates = {...(day.estimates || {})}; delete estimates[current.identity];
|
||||
return {...day, ids:(day.ids || []).filter(id => id !== current.identity), estimates};
|
||||
});
|
||||
let destination = days.find(day => day.plan_date === planDate);
|
||||
if (!destination) {
|
||||
destination = {plan_date:planDate, ids:[], capacity_minutes:null, estimates:{}};
|
||||
days.push(destination);
|
||||
}
|
||||
destination.ids.push(current.identity);
|
||||
destination.estimates[current.identity] = estimate;
|
||||
return {today, week:{revision:current.week_revision, timezone:current.week.timezone || null, days}};
|
||||
}
|
||||
|
||||
async function open(identity) {
|
||||
let today;
|
||||
const queued = readQueue().length;
|
||||
let offline = Boolean(queued);
|
||||
if (queued) {
|
||||
today = getToday?.();
|
||||
} else {
|
||||
try { today = await api('api/v1/today'); }
|
||||
catch (error) {
|
||||
if (error?.status === 401 || error?.status === 403) throw error;
|
||||
today = getToday?.(); offline = true;
|
||||
}
|
||||
}
|
||||
if (!identity || !today?.ids?.includes(identity)) {
|
||||
throw new Error('The active Today item changed. Reopen rescheduling.');
|
||||
}
|
||||
const loaded = queued ? week.state?.() : await week.load();
|
||||
if (!loaded) throw new Error('Reload Today before rescheduling another saved move.');
|
||||
if (loaded?.sync_pending) {
|
||||
throw new Error('Reconnect before rescheduling Today into Week Ahead.');
|
||||
}
|
||||
offline = offline || Boolean(loaded?.offline_snapshot);
|
||||
const estimate = Number(today.estimates?.[identity]);
|
||||
const estimateMinutes = Number.isFinite(estimate) && estimate > 0 ? estimate : null;
|
||||
const days = week.review().days.map(day => {
|
||||
const ids = (day.ids || []).filter(id => id !== identity);
|
||||
const planned = Number(day.planned_minutes) || 0;
|
||||
const existing = Number(day.estimates?.[identity]) || 0;
|
||||
return {
|
||||
...day,
|
||||
ids,
|
||||
planned_minutes: Math.max(0, planned - existing),
|
||||
load: `${Math.max(0, planned - existing)} / ${Number(day.capacity_minutes) || 0} min`,
|
||||
eligible: ids.length < 5,
|
||||
};
|
||||
});
|
||||
current = {
|
||||
identity,
|
||||
today_revision: today.revision,
|
||||
week_revision: loaded.revision,
|
||||
operation_id: operationId(),
|
||||
estimate_minutes: estimateMinutes,
|
||||
days,
|
||||
today,
|
||||
week: loaded,
|
||||
offline,
|
||||
};
|
||||
return {...current, days:days.map(day => ({...day, ids:[...day.ids]}))};
|
||||
}
|
||||
|
||||
async function confirm(planDate, estimateMinutes, {allowOverload = false} = {}) {
|
||||
if (!current) throw new Error('Open rescheduling before choosing a day.');
|
||||
const day = current.days.find(value => value.plan_date === planDate);
|
||||
if (!day) throw new Error('Choose one of the next seven days.');
|
||||
const estimate = Number(estimateMinutes);
|
||||
if (!Number.isFinite(estimate) || estimate < 5 || estimate > 1440) {
|
||||
throw new Error('Estimate must be between 5 and 1440 minutes.');
|
||||
}
|
||||
if (!day.eligible) throw new Error('That Week Ahead day already has five items.');
|
||||
const capacity = Number(day.capacity_minutes) || 0;
|
||||
if (capacity && day.planned_minutes + estimate > capacity && !allowOverload) {
|
||||
throw new Error("That move exceeds the day's capacity. Confirm overload before rescheduling.");
|
||||
}
|
||||
const body = {
|
||||
operation_id:current.operation_id,
|
||||
identity:current.identity,
|
||||
estimate_minutes:estimate,
|
||||
plan_date:planDate,
|
||||
today_revision:current.today_revision,
|
||||
week_revision:current.week_revision,
|
||||
allow_over_capacity:allowOverload,
|
||||
};
|
||||
const optimistic = optimisticSnapshots(planDate, estimate);
|
||||
const durable = Boolean(storageKey() && storage);
|
||||
const admitted = durable && persist({body, ...optimistic, queued_at:now()});
|
||||
if (durable && !admitted) {
|
||||
throw new Error('Could not save this move on this device. Nothing changed.');
|
||||
}
|
||||
if (admitted) {
|
||||
adoptToday(optimistic.today);
|
||||
week.adopt(optimistic.week);
|
||||
}
|
||||
if (current.offline) {
|
||||
current = null;
|
||||
return {...optimistic, sync_pending:true, pending_count:readQueue().length};
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = admitted ? await flush() : await api('api/v1/week/reschedule', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body),
|
||||
});
|
||||
} catch(error) {
|
||||
if (admitted && error?.status === 409) await restoreConflict(error);
|
||||
if (admitted && error?.status !== 401 && error?.status !== 403) {
|
||||
current = null;
|
||||
return {...optimistic, sync_pending:true};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
adoptToday(result.today);
|
||||
week.adopt(result.week);
|
||||
current = null;
|
||||
return result;
|
||||
}
|
||||
|
||||
function cancel() { current = null; }
|
||||
return {open, confirm, cancel, state:() => current, pending, resume, flush};
|
||||
}
|
||||
|
||||
function mountTodayWeekReschedule({
|
||||
qs, document=globalThis.document, window=globalThis.window, week, api, getToday, adoptToday, currentTarget, closeActions,
|
||||
refresh, warm, continueToday, announce, storage=null, getLogin=()=>'', schedule=callback=>requestAnimationFrame(callback),
|
||||
}={}) {
|
||||
const dialog=qs('#today-week-reschedule'),daysRoot=qs('#today-week-reschedule-days');
|
||||
const estimate=qs('#today-week-reschedule-estimate'),status=qs('#today-week-reschedule-status');
|
||||
const confirm=qs('#confirm-today-week-reschedule'),launcher=qs('[data-work-session-reschedule-week]');
|
||||
let selectedDate=null,allowOverload=false;
|
||||
const controller=createTodayWeekReschedule({week,api,getToday,adoptToday,storage,getLogin});
|
||||
async function flushPending() {
|
||||
if(!controller.pending())return false;
|
||||
try {
|
||||
const result=await controller.flush();
|
||||
announce('Today-to-Week move synced to your account.');
|
||||
await refresh();warm();
|
||||
return result;
|
||||
} catch(error) {
|
||||
announce(`${error.message||'Sync unavailable.'} Move saved on this device · sync pending.`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function resumePending() {
|
||||
const restored=controller.resume();
|
||||
if(!restored)return false;
|
||||
announce('Today-to-Week move saved on this device · sync pending.');
|
||||
flushPending();
|
||||
return restored;
|
||||
}
|
||||
window?.addEventListener('online', flushPending);
|
||||
document?.addEventListener('visibilitychange',()=>document.hidden?false:flushPending());
|
||||
let restoreAttempts=0;
|
||||
function restoreWhenOwned(){
|
||||
if(resumePending()||getLogin()||restoreAttempts++>=20)return;
|
||||
window?.setTimeout(restoreWhenOwned,250);
|
||||
}
|
||||
restoreWhenOwned();
|
||||
function close() {
|
||||
controller.cancel();selectedDate=null;allowOverload=false;
|
||||
if(dialog.open)dialog.close();schedule(()=>{
|
||||
qs('[data-mobile-today-more]').click();launcher.focus();
|
||||
});
|
||||
}
|
||||
function render(opened) {
|
||||
daysRoot.replaceChildren(...opened.days.map(day=>{
|
||||
const button=document.createElement('button');
|
||||
button.type='button';button.dataset.planDate=day.plan_date;button.setAttribute('role','radio');
|
||||
button.setAttribute('aria-checked','false');button.disabled=!day.eligible;
|
||||
const label=document.createElement('strong');label.textContent=day.label;
|
||||
const load=document.createElement('span');load.className='small';
|
||||
load.textContent=day.eligible?day.load:'5 items · full';button.append(label,load);
|
||||
button.addEventListener('click',()=>{
|
||||
selectedDate=day.plan_date;allowOverload=false;
|
||||
daysRoot.querySelectorAll('button').forEach(choice=>choice.setAttribute(
|
||||
'aria-checked',String(choice===button)
|
||||
));
|
||||
status.textContent='';confirm.disabled=false;confirm.textContent='Move to Week Ahead & continue';
|
||||
});
|
||||
return button;
|
||||
}));
|
||||
}
|
||||
launcher.addEventListener('click',async()=>{
|
||||
const target=currentTarget();
|
||||
if(!target){announce('Start or resume a checkpointed Today item before rescheduling.');return;}
|
||||
closeActions();status.textContent='Loading Week Ahead…';confirm.disabled=true;dialog.showModal();
|
||||
try{
|
||||
const opened=await controller.open(target.identity);render(opened);
|
||||
estimate.value=opened.estimate_minutes||'';
|
||||
status.textContent=opened.estimate_minutes?'Choose a future day.':'Add an estimate, then choose a future day.';
|
||||
schedule(()=>daysRoot.querySelector('button:not(:disabled)')?.focus());
|
||||
}catch(error){status.textContent=error.message;}
|
||||
});
|
||||
qs('#cancel-today-week-reschedule').addEventListener('click',close);
|
||||
dialog.addEventListener('cancel',event=>{event.preventDefault();close();});
|
||||
confirm.addEventListener('click',async()=>{
|
||||
if(!selectedDate)return;
|
||||
confirm.disabled=true;status.textContent='Moving Today into Week Ahead…';
|
||||
try{
|
||||
const result=await controller.confirm(selectedDate,Number(estimate.value),{allowOverload});
|
||||
dialog.close();
|
||||
if(result.sync_pending){
|
||||
announce('Moved locally. Saved on this device · sync pending.');warm();
|
||||
}else{
|
||||
await refresh();warm();announce('Moved to Week Ahead. Continuing Today.');
|
||||
}
|
||||
await continueToday();
|
||||
}catch(error){
|
||||
const overload=error.message.includes('Confirm overload');allowOverload=overload;
|
||||
status.textContent=error.message;
|
||||
confirm.textContent=overload?'Confirm overload & continue':'Move to Week Ahead & continue';
|
||||
confirm.disabled=false;
|
||||
}
|
||||
});
|
||||
return {controller,close,flushPending,resumePending};
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = createTodayWeekReschedule;
|
||||
module.exports.mount = mountTodayWeekReschedule;
|
||||
}
|
||||
+277
-7
@@ -1,4 +1,4 @@
|
||||
function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,now=()=>Date.now()}={}) {
|
||||
function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,coordinator,now=()=>Date.now()}={}) {
|
||||
let week={revision:0,timezone:null,days:[]};
|
||||
let flushing=null;
|
||||
let lastConflict=null;
|
||||
@@ -6,8 +6,10 @@ function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,now=()=>D
|
||||
let refreshedAt=null;
|
||||
let confirmedItems={};
|
||||
let pendingItems={};
|
||||
let pulling=null;
|
||||
const storagePrefix='stackchain.week-sync.v1.';
|
||||
const confirmedPrefix='stackchain.week-confirmed.v1.';
|
||||
const pullPrefix='stackchain.week-today-pull.v1.';
|
||||
const cloneDay=day=>({
|
||||
plan_date:day.plan_date,ids:[...(day.ids||[])],capacity_minutes:day.capacity_minutes??null,
|
||||
estimates:{...(day.estimates||{})},
|
||||
@@ -33,6 +35,38 @@ function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,now=()=>D
|
||||
const login=String(getLogin?.()||'').trim().toLowerCase();
|
||||
return login?confirmedPrefix+encodeURIComponent(login):'';
|
||||
}
|
||||
function pullKey() {
|
||||
const login=String(getLogin?.()||'').trim().toLowerCase();
|
||||
return login?pullPrefix+encodeURIComponent(login):'';
|
||||
}
|
||||
function pullQueue() {
|
||||
const key=pullKey();
|
||||
if(!key||!storage)return [];
|
||||
try {
|
||||
const value=JSON.parse(storage.getItem(key)||'null');
|
||||
const entries=Array.isArray(value?.entries)?value.entries:(value?[value]:[]);
|
||||
return entries.filter(entry=>typeof entry?.body?.operation_id==='string'&&Array.isArray(entry?.today?.ids)&&
|
||||
Number.isInteger(entry?.week?.revision)&&Array.isArray(entry?.week?.days));
|
||||
} catch(_error){return [];}
|
||||
}
|
||||
function writePullQueue(entries) {
|
||||
const key=pullKey();if(!key||!storage)return false;
|
||||
try {
|
||||
if(entries.length)storage.setItem(key,JSON.stringify({version:2,entries}));
|
||||
else storage.removeItem(key);
|
||||
return true;
|
||||
} catch(_error){return false;}
|
||||
}
|
||||
function pendingPull() {
|
||||
return pullQueue()[0]||null;
|
||||
}
|
||||
function resumePull() {
|
||||
const queue=pullQueue(),conflicted=queue.find(entry=>entry.conflict&&entry.current?.week);
|
||||
const value=conflicted||queue[queue.length-1];
|
||||
if(!value)return null;
|
||||
adopt(conflicted?conflicted.current.week:value.week);
|
||||
return {...value,...(conflicted?.current||{}),sync_pending:true};
|
||||
}
|
||||
function readConfirmed() {
|
||||
const key=confirmedKey();
|
||||
if(!key||!storage)return null;
|
||||
@@ -238,6 +272,34 @@ function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,now=()=>D
|
||||
if(Number.isFinite(estimate)) destination.estimates[id]=estimate;
|
||||
return Boolean(stageDays(moved));
|
||||
}
|
||||
function retire(id) {
|
||||
const removed=week.days.reduce((total,item)=>total+(item.ids||[]).filter(value=>value===id).length,0);
|
||||
if(!id||!removed||offlineSnapshot)return false;
|
||||
const days=week.days.map(item=>{
|
||||
const estimates={...(item.estimates||{})};delete estimates[id];
|
||||
return {...cloneDay(item),ids:(item.ids||[]).filter(value=>value!==id),estimates};
|
||||
});
|
||||
const staged=stageDays(days);
|
||||
return staged?{...staged,removed}:false;
|
||||
}
|
||||
function unplan(id) {
|
||||
if(!id||offlineSnapshot)return false;
|
||||
const source=week.days.find(item=>(item.ids||[]).includes(id));
|
||||
if(!source)return false;
|
||||
const index=source.ids.indexOf(id),estimate=Number(source.estimates?.[id]);
|
||||
const receipt={id,plan_date:source.plan_date,index,estimate:Number.isFinite(estimate)?estimate:null};
|
||||
const staged=retire(id);
|
||||
return staged?receipt:false;
|
||||
}
|
||||
function restore(receipt) {
|
||||
if(!receipt?.id||!receipt.plan_date||!Number.isInteger(receipt.index)||offlineSnapshot||placement(receipt.id))return false;
|
||||
const days=week.days.map(cloneDay);
|
||||
let destination=days.find(item=>item.plan_date===receipt.plan_date);
|
||||
if(!destination){destination={plan_date:receipt.plan_date,ids:[],capacity_minutes:null,estimates:{}};days.push(destination);}
|
||||
destination.ids.splice(Math.min(receipt.index,destination.ids.length),0,receipt.id);
|
||||
if(Number.isFinite(Number(receipt.estimate)))destination.estimates[receipt.id]=Number(receipt.estimate);
|
||||
return stageDays(days);
|
||||
}
|
||||
function placement(id) {
|
||||
const found=week.days.find(item=>(item.ids||[]).includes(id));
|
||||
if(!found)return null;
|
||||
@@ -436,6 +498,77 @@ function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,now=()=>D
|
||||
plan_date:due.plan_date,today_revision:todayRevision,
|
||||
})});
|
||||
}
|
||||
async function pullItem(identity,today,operationId,allowOverCapacity=false) {
|
||||
if(offlineSnapshot||pending()||conflict()||!identity||!operationId||
|
||||
!Number.isInteger(today?.revision)||!(today.ids||[]).length)return false;
|
||||
const body={operation_id:operationId,identity,today_revision:today.revision,week_revision:week.revision,
|
||||
allow_over_capacity:Boolean(allowOverCapacity)};
|
||||
const key=pullKey();
|
||||
if(key&&storage){
|
||||
const source=week.days.find(day=>(day.ids||[]).includes(identity));
|
||||
if(!source)return false;
|
||||
const estimate=Number(source.estimates?.[identity]);
|
||||
const optimisticToday={...today,ids:[...(today.ids||[]),identity],estimates:{...(today.estimates||{}),
|
||||
...(Number.isFinite(estimate)?{[identity]:estimate}:{})}};
|
||||
const optimisticWeek={revision:week.revision,timezone:week.timezone,days:week.days.map(day=>{
|
||||
const estimates={...(day.estimates||{})};delete estimates[identity];
|
||||
return {...cloneDay(day),ids:(day.ids||[]).filter(id=>id!==identity),estimates};
|
||||
})};
|
||||
const record={body,today:optimisticToday,week:optimisticWeek,queued_at:now()};
|
||||
const queue=pullQueue();
|
||||
if(!writePullQueue([...queue,record]))throw new Error('Could not save this pull on this device. Nothing changed.');
|
||||
adopt(optimisticWeek);
|
||||
try{return await flushPull();}
|
||||
catch(error){
|
||||
if(error?.status===401||error?.status===403)throw error;
|
||||
return {...record,sync_pending:true};
|
||||
}
|
||||
}
|
||||
const result=await fetchJson('api/v1/week/pull-item',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
|
||||
adoptConfirmed(result.week,{...confirmedItems,...pendingItems});return result;
|
||||
}
|
||||
function flushPull() {
|
||||
if(pulling)return pulling;
|
||||
if(!pendingPull()||!pullKey())return Promise.resolve(false);
|
||||
const run=async()=>{
|
||||
let result,lastResult=false;
|
||||
while(pendingPull()){
|
||||
const current=pendingPull();
|
||||
try {
|
||||
result=await fetchJson('api/v1/week/pull-item',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(current.body)});
|
||||
} catch(error) {
|
||||
if(error?.status!==409)throw error;
|
||||
const [today,currentWeek]=await Promise.all([fetchJson('api/v1/today'),fetchJson('api/v1/week')]);
|
||||
const queue=pullQueue(),conflicted={...current,conflict:true,current:{today,week:currentWeek}};
|
||||
if(!writePullQueue([conflicted,...queue.slice(1)]))throw new Error('Could not preserve queued Week Ahead work on this device.');
|
||||
adopt(currentWeek);
|
||||
return {today,week:currentWeek,conflict:true,sync_pending:true};
|
||||
}
|
||||
const queue=pullQueue();
|
||||
if(queue[0]?.body?.operation_id!==current.body.operation_id)continue;
|
||||
const remaining=queue.slice(1).map(entry=>{
|
||||
const identity=entry.body.identity;
|
||||
const source=entry.week.days.find(day=>(day.ids||[]).includes(identity));
|
||||
const estimate=Number(entry.today?.estimates?.[identity]??source?.estimates?.[identity]);
|
||||
const today={...result.today,ids:(result.today.ids||[]).includes(identity)?[...result.today.ids]:[...result.today.ids,identity],
|
||||
estimates:{...(result.today.estimates||{}),...(Number.isFinite(estimate)?{[identity]:estimate}:{})}};
|
||||
const nextWeek={revision:result.week.revision,timezone:result.week.timezone||null,days:result.week.days.map(day=>{
|
||||
const estimates={...(day.estimates||{})};delete estimates[identity];
|
||||
return {...cloneDay(day),ids:(day.ids||[]).filter(id=>id!==identity),estimates};
|
||||
})};
|
||||
result={today,week:nextWeek};
|
||||
return {...entry,body:{...entry.body,today_revision:today.revision,week_revision:nextWeek.revision},today,week:nextWeek};
|
||||
});
|
||||
if(!writePullQueue(remaining))throw new Error('Could not update queued Week Ahead work on this device.');
|
||||
lastResult=result;
|
||||
}
|
||||
adoptConfirmed(lastResult.week,{...confirmedItems,...pendingItems});
|
||||
return {...lastResult,sync_pending:false};
|
||||
};
|
||||
const delivery=coordinator?coordinator.runExclusive('week',run):run();
|
||||
pulling=Promise.resolve(delivery).finally(()=>{pulling=null;});
|
||||
return pulling;
|
||||
}
|
||||
async function startEarly(planDate,todayRevision) {
|
||||
if(offlineSnapshot||pending()||conflict()||!Number.isInteger(todayRevision))return false;
|
||||
const day=week.days.find(item=>item.plan_date===planDate&&item.ids.length);
|
||||
@@ -465,14 +598,15 @@ function createWeekPlan({fetchJson,localDate,timeZone,storage,getLogin,now=()=>D
|
||||
const label=planned.length?`${items} item${items===1?'':'s'} across ${planned.length} day${planned.length===1?'':'s'}`:'Nothing planned';
|
||||
return label+(pending()?' · sync pending':'');
|
||||
}
|
||||
return {adopt,state,dates,day,pass,load,saveDay,stageDay,stageCapacities,review,previewReflow,applyReflow,move,placement,place,pending,flush,conflict,chooseDay,saveMerged,
|
||||
keepLocal,useRemote,promote,startEarly,reconcile:reconcilePromotion,summary,rememberItems,rememberPendingItem,
|
||||
return {adopt,state,dates,day,pass,load,saveDay,stageDay,stageCapacities,review,previewReflow,applyReflow,move,retire,unplan,restore,placement,place,pending,flush,conflict,chooseDay,saveMerged,
|
||||
keepLocal,useRemote,promote,pullItem,pendingPull,resumePull,flushPull,startEarly,reconcile:reconcilePromotion,summary,rememberItems,rememberPendingItem,
|
||||
item:id=>pendingItems[id]||confirmedItems[id]||null,
|
||||
offline:()=>offlineSnapshot};
|
||||
offline:()=>offlineSnapshot,request:fetchJson,reschedule:()=>({storage,getLogin})};
|
||||
}
|
||||
function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPlanner,setReviewMode=()=>{},escapeHtml,escapeAttribute,
|
||||
todayWork,refresh:r=()=>{},warm:w=()=>{},today:t=()=>null,r:refresh=r,w:warm=w,t:getTodayPlan=t,
|
||||
confirmEarly=message=>globalThis.confirm?.(message)??false}={}) {
|
||||
confirmEarly=message=>globalThis.confirm?.(message)??false,setTimer=globalThis.setTimeout,clearTimer=globalThis.clearTimeout,
|
||||
operationId=()=>globalThis.crypto?.randomUUID?.()||('pull-'+Date.now()+'-'+Math.random().toString(16).slice(2)),x=null}={}) {
|
||||
let selectedDate=null;
|
||||
let reviewing=false;
|
||||
let overviewing=false;
|
||||
@@ -480,6 +614,8 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
let blockedReviewOpen=false;
|
||||
let reconciliation=null;
|
||||
let loadState=null;
|
||||
let unplanReceipt=null;
|
||||
let unplanTimer=null;
|
||||
function renderOfflineState(value=loadState) {
|
||||
const notice=qs('#week-offline-snapshot'),retry=qs('#retry-week-live'),capacity=qs('#open-week-capacity-import');
|
||||
const offline=Boolean(value?.offline_snapshot);
|
||||
@@ -606,6 +742,36 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function dismissUnplanReceipt({focus=false}={}) {
|
||||
if(unplanTimer){clearTimer?.(unplanTimer);unplanTimer=null;}
|
||||
unplanReceipt=null;
|
||||
const receipt=qs('#week-unplan-receipt'),undo=qs('#undo-week-unplan');
|
||||
if(receipt)receipt.hidden=true;
|
||||
if(undo)undo.hidden=true;
|
||||
if(focus)qs('#edit-week-plan')?.focus?.();
|
||||
}
|
||||
function showUnplanReceipt(title) {
|
||||
const receipt=qs('#week-unplan-receipt'),undo=qs('#undo-week-unplan');
|
||||
if(receipt){receipt.textContent=title+' removed from Week Ahead.';receipt.hidden=false;}
|
||||
if(undo){undo.hidden=false;undo.focus?.();}
|
||||
if(unplanTimer)clearTimer?.(unplanTimer);
|
||||
unplanTimer=setTimer?.(()=>dismissUnplanReceipt({focus:true}),10000)||null;
|
||||
}
|
||||
async function undoUnplan() {
|
||||
const receipt=unplanReceipt;
|
||||
if(!receipt||!controller.restore?.(receipt))return false;
|
||||
dismissUnplanReceipt();renderReview();renderPass();
|
||||
try{
|
||||
await controller.flush();
|
||||
renderReview();
|
||||
qs('#week-review-status').textContent='Restored to Week Ahead.';
|
||||
}catch(error){
|
||||
qs('#week-review-status').textContent=(error.message||'Week Ahead sync is unavailable.')+' Restore remains saved on this phone.';
|
||||
}
|
||||
qs('#week-review-days').querySelector?.(`[data-week-unplan="${receipt.id}"]`)?.focus?.();
|
||||
return true;
|
||||
}
|
||||
qs('#undo-week-unplan')?.addEventListener('click',undoUnplan);
|
||||
function renderReview() {
|
||||
const value=controller.review(),root=qs('#week-review-days'),duplicates=qs('#week-review-duplicates');
|
||||
const readOnly=Boolean(controller.offline?.());
|
||||
@@ -628,7 +794,17 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
const load=day.planned_minutes+(capacity?' of '+capacity:'')+' min'+(day.overloaded?' · over capacity':'');
|
||||
const move=id=>overviewing?'':'<div class="week-review-move"><label>Move to <select data-week-move-destination="'+escapeAttribute(id)+'">'+destinations+
|
||||
'</select></label><button type="button" data-week-move="'+escapeAttribute(id)+'">Move</button></div>';
|
||||
const items=day.ids.length?'<ul>'+day.ids.map(id=>'<li>'+itemMarkup(id,day)+move(id)+'</li>').join('')+'</ul>':
|
||||
const unplan=id=>overviewing&&!readOnly?'<button type="button" class="week-review-unplan" data-week-unplan="'+escapeAttribute(id)+'">Remove from week</button>':'';
|
||||
const pull=id=>{
|
||||
const inToday=(today?.ids||[]).includes(id),full=(today?.ids||[]).length>=5;
|
||||
if(!overviewing||readOnly||pending||!Number.isInteger(today?.revision)||!(today?.ids||[]).length||inToday)return '';
|
||||
const todayMinutes=(today.ids||[]).reduce((total,itemId)=>total+(Number(today.estimates?.[itemId])||0),0);
|
||||
const projected=todayMinutes+(Number(day.estimates?.[id])||0),capacity=Number(today.capacity_minutes)||0;
|
||||
const overload=capacity&&projected>capacity;
|
||||
return '<button type="button" class="week-review-pull" data-week-pull-item="'+escapeAttribute(id)+'"'+(full?' disabled':'')+'>'+
|
||||
(full?'Today is full':(overload?'Review Today · '+projected+' of '+capacity+' min':'Add to Today'))+'</button>';
|
||||
};
|
||||
const items=day.ids.length?'<ul>'+day.ids.map(id=>'<li>'+itemMarkup(id,day)+move(id)+pull(id)+unplan(id)+'</li>').join('')+'</ul>':
|
||||
'<p class="small muted">Nothing planned.</p>';
|
||||
const edit=readOnly?'':'<button type="button" data-week-edit-day="'+escapeAttribute(day.plan_date)+'" aria-label="Edit '+escapeAttribute(day.label)+'">Edit day</button>';
|
||||
const start=day===nextUp&&canStartEarly?'<button type="button" class="week-start-early" data-week-start-early="'+escapeAttribute(day.plan_date)+'">Start this day early</button>':'';
|
||||
@@ -657,6 +833,44 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
controller.flush().then(()=>{renderReview();qs('#mobile-week-summary').textContent=controller.summary();})
|
||||
.catch(error=>{qs('#week-review-status').textContent=(error.message||'Week Ahead sync is unavailable.')+' Changes remain on this phone.';});
|
||||
}));
|
||||
root.querySelectorAll('[data-week-unplan]').forEach(button=>button.addEventListener('click',async event=>{
|
||||
const id=event.currentTarget.dataset.weekUnplan,item=getItem(id)||controller.item?.(id);
|
||||
const receipt=controller.unplan?.(id);
|
||||
if(!receipt)return;
|
||||
unplanReceipt=receipt;
|
||||
renderReview();renderPass();showUnplanReceipt(String(item?.title||'Work'));
|
||||
try{
|
||||
await controller.flush();
|
||||
renderReview();
|
||||
qs('#mobile-week-summary').textContent=controller.summary();
|
||||
}catch(error){
|
||||
qs('#week-review-status').textContent=(error.message||'Week Ahead sync is unavailable.')+' Removal remains saved on this phone.';
|
||||
}
|
||||
}));
|
||||
root.querySelectorAll('[data-week-pull-item]').forEach(button=>button.addEventListener('click',async event=>{
|
||||
const id=event.currentTarget.dataset.weekPullItem,current=getTodayPlan?.();
|
||||
if(!id||!Number.isInteger(current?.revision)||!(current.ids||[]).length||current.ids.length>=5)return;
|
||||
const source=value.days.find(day=>day.ids.includes(id)),estimate=Number(source?.estimates?.[id])||0;
|
||||
const todayMinutes=current.ids.reduce((total,itemId)=>total+(Number(current.estimates?.[itemId])||0),0);
|
||||
const projected=todayMinutes+estimate,capacity=Number(current.capacity_minutes)||0;
|
||||
const overCapacity=Boolean(capacity&&projected>capacity),item=getItem(id)||controller.item?.(id);
|
||||
if(overCapacity&&!confirmEarly('Add '+String(item?.title||'work')+' to Today?\n\nToday will be '+projected+' of '+capacity+' min · '+(projected-capacity)+' min over capacity.'))return;
|
||||
event.currentTarget.disabled=true;
|
||||
try{
|
||||
const result=await controller.pullItem?.(id,current,operationId(),overCapacity);
|
||||
if(!result)return;
|
||||
getTodayPlan?.(result.today);todayWork.replace(result.today.ids);
|
||||
todayWork.replacePlanning({capacity_minutes:result.today.capacity_minutes??null,estimates:result.today.estimates||{}});
|
||||
refresh();warm();renderReview();
|
||||
qs('#mobile-week-summary').textContent=controller.summary();
|
||||
qs('#week-review-status').textContent=result.sync_pending?String(item?.title||'Work')+' added to Today · sync pending.':
|
||||
String(item?.title||'Work')+' added to Today.';
|
||||
}catch(error){
|
||||
renderReview();
|
||||
qs('#week-review-status').textContent=error?.code==='today_full'?'Today is full. Finish or move work before adding more.':
|
||||
((error.message||'Today or Week Ahead changed.')+' Reopen Week Ahead and retry.');
|
||||
}
|
||||
}));
|
||||
root.querySelectorAll('[data-week-open-item]').forEach(button=>button.addEventListener('click',event=>{
|
||||
const id=button.dataset.weekOpenItem,item=getItem(id)||controller.item?.(id);
|
||||
if(item)openItem?.(item,event.currentTarget);
|
||||
@@ -772,6 +986,51 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
if(!reviewing||!value.can_confirm||controller.pending()) return false;
|
||||
return true;
|
||||
}
|
||||
async function retire(item) {
|
||||
const staged=controller.retire?.(todayWork.identity({...item,kind:'issue'}));
|
||||
if(!staged)return false;
|
||||
const title=String(item?.title||'Completed work');
|
||||
const refreshOverview=message=>{
|
||||
if(overviewing||reviewing)renderReview();
|
||||
qs('#week-review-status').textContent=message;
|
||||
qs('#edit-week-plan')?.focus?.();
|
||||
};
|
||||
try {
|
||||
await controller.flush();
|
||||
refreshOverview(title+' removed and Week Ahead saved.');
|
||||
return 'saved';
|
||||
} catch(_error) {
|
||||
refreshOverview(title+' removed · sync pending.');
|
||||
return 'pending';
|
||||
}
|
||||
}
|
||||
function adoptPull(value,message) {
|
||||
if(!value?.today)return false;
|
||||
t(value.today);todayWork.replace(value.today.ids);
|
||||
todayWork.replacePlanning({capacity_minutes:value.today.capacity_minutes??null,estimates:value.today.estimates||{}});
|
||||
refresh();warm();
|
||||
qs('#mobile-week-summary').textContent=controller.summary();
|
||||
qs('#my-work-action-status').textContent=message;
|
||||
return value;
|
||||
}
|
||||
function resumePull() {
|
||||
const restored=controller.resumePull?.();
|
||||
return restored?adoptPull(restored,'Week-to-Today pull saved on this phone · sync pending.'):false;
|
||||
}
|
||||
async function flushPull() {
|
||||
const pendingPull=controller.pendingPull?.();
|
||||
if(!pendingPull)return false;
|
||||
if(pendingPull.conflict)return adoptPull(pendingPull.current,
|
||||
'Today or Week Ahead changed on another device. Saved pull needs review.');
|
||||
try {
|
||||
const result=await controller.flushPull();
|
||||
return adoptPull(result,result.conflict?'Today or Week Ahead changed on another device. Saved pull needs review.':
|
||||
'Week Ahead work added to Today.');
|
||||
} catch(error) {
|
||||
qs('#my-work-action-status').textContent=(error.message||'Week-to-Today sync is unavailable.')+' Saved on this phone · sync pending.';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function finish(){reviewing=false;overviewing=false;setReviewMode(false);closeReflow();qs('#week-review').hidden=true;return true;}
|
||||
qs('#back-to-week-review')?.addEventListener('click',returnToReview);
|
||||
qs('#edit-week-plan')?.addEventListener('click',editWeek);
|
||||
@@ -792,7 +1051,7 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
qs('#my-work-action-status').textContent=(error.message||'Week Ahead needs review before promotion.')+' Open Week Ahead to review.';return false;
|
||||
}
|
||||
}
|
||||
const workflow={open,save,advance,confirm,finish,promote,editWeek,renderDates,renderReview,renderConflict,active:()=>Boolean(selectedDate)||reviewing||Boolean(reconciliation),
|
||||
const workflow={open,save,advance,confirm,finish,promote,retire,resumePull,flushPull,editWeek,renderDates,renderReview,renderConflict,active:()=>Boolean(selectedDate)||reviewing||Boolean(reconciliation),
|
||||
reviewing:()=>reviewing,overviewing:()=>overviewing,selectedDate:()=>selectedDate,
|
||||
day:()=>reconciliationDay()||(selectedDate?controller.day(selectedDate):(overviewing?{ids:[]}:null)),
|
||||
copy:()=>reconciliation?{title:"Start today's plan",heading:'Unfinished Today + due Week Ahead',available:'Available today',build:'Build combined Today'}:
|
||||
@@ -800,7 +1059,18 @@ function createWeekPlanWorkflow({controller,qs,getItem=()=>null,openItem,openPla
|
||||
(selectedDate?{title:'Plan Week Ahead',heading:selectedDate+', in order',available:'Available this day',build:'Build this day'}:null)),
|
||||
clear(){selectedDate=null;reviewing=false;overviewing=false;editingFromReview=false;reconciliation=null;setReviewMode(false);qs('#week-review').hidden=true;
|
||||
const back=qs('#back-to-week-review');if(back)back.hidden=true;renderDates();}};
|
||||
globalThis.addEventListener?.('stackchain:issue-closed',event=>retire(event.detail));
|
||||
if(typeof weekCalendarImport!=='undefined')weekCalendarImport.mount(controller,workflow,qs);
|
||||
if(x)mountTodayWeekReschedule({
|
||||
qs,week:controller,getToday:t,refresh:r,warm:w,api:controller.request,currentTarget:x,...controller.reschedule(),
|
||||
closeActions:()=>qs('#mobile-today-actions').close(),
|
||||
continueToday:()=>qs('[data-work-session-next]').click(),
|
||||
announce:message=>{qs('#my-work-action-status').textContent=message;},
|
||||
adoptToday:value=>{
|
||||
t(value);todayWork.replace(value.ids);
|
||||
todayWork.replacePlanning({capacity_minutes:value.capacity_minutes??null,estimates:value.estimates||{}});
|
||||
},
|
||||
});
|
||||
return workflow;
|
||||
}
|
||||
if(typeof module!=='undefined'&&module.exports){
|
||||
|
||||
@@ -19,6 +19,7 @@ RUNTIME_DIRECTORIES = ("docs", "frontend", "src")
|
||||
RUNTIME_FILES = (
|
||||
"README.md",
|
||||
"requirements.txt",
|
||||
"scripts/rotate_private_state.py",
|
||||
"scripts/rotate_unfiled_drafts.py",
|
||||
)
|
||||
EXCLUDED_PARTS = {"__pycache__", ".pytest_cache"}
|
||||
|
||||
Executable
+176
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rewrap shared private-state envelopes under the configured active key."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from src.private_state import connect_private_sqlite # noqa: E402
|
||||
from src.state_encryption import ( # noqa: E402
|
||||
PrivateStateCipher,
|
||||
PrivateStateEncryptionError,
|
||||
private_state_encryption_config,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Field:
|
||||
column: str
|
||||
binding: str
|
||||
alias: str | None = None
|
||||
plaintext_string: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Table:
|
||||
name: str
|
||||
context_columns: tuple[str, ...]
|
||||
fields: tuple[Field, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Store:
|
||||
name: str
|
||||
identity: str
|
||||
env: str
|
||||
filename: str
|
||||
tables: tuple[Table, ...]
|
||||
|
||||
|
||||
STORES = (
|
||||
Store("today", "today", "STACKCHAIN_TODAY_DB", "today.sqlite3", (
|
||||
Table("today_plans", ("login",), (Field("ids", "plan:{login}"),)),
|
||||
Table("tomorrow_plans", ("login",), (Field("payload", "tomorrow:{login}"),)),
|
||||
Table("tomorrow_promotions", ("login", "promotion_id"), (Field("result", "tomorrow-promotion:{login}:{promotion_id}"),)),
|
||||
Table("week_plans", ("login",), (Field("payload", "week:{login}"),)),
|
||||
Table("week_promotions", ("login", "promotion_id"), (Field("result", "week-promotion:{login}:{promotion_id}"),)),
|
||||
Table("week_reschedules", ("login", "operation_id"), (Field("result", "week-reschedule:{login}:{operation_id}"),)),
|
||||
Table("today_sessions", ("login",), (Field("device_id", "session:{login}"),)),
|
||||
Table("today_recaps", ("login",), (
|
||||
Field("session_id", "recap-id:{login}", "session_id", True),
|
||||
Field("items", "recap-items:{login}:{session_id}"),
|
||||
)),
|
||||
Table("today_time_logs", ("login",), (
|
||||
Field("session_id", "time-log-session:{login}", "session_id", True),
|
||||
Field("identity", "time-log-identity:{login}:{session_id}", "identity", True),
|
||||
Field("actual_minutes", "time-log-payload:{login}:{session_id}:{identity}"),
|
||||
)),
|
||||
)),
|
||||
Store("later", "later", "STACKCHAIN_LATER_DB", "later.sqlite3", (
|
||||
Table("later_plans", ("login",), (Field("records", "plan:{login}"),)),
|
||||
Table("later_item_revisions", ("login",), (Field("item_id", "item-revision:{login}", plaintext_string=True),)),
|
||||
)),
|
||||
Store("live-snapshot", "live-snapshot", "STACKCHAIN_LIVE_SNAPSHOT_DB", "live-snapshot.sqlite3", (
|
||||
Table("live_snapshot", ("generation",), (Field("value_json", "{generation}"),)),
|
||||
)),
|
||||
Store("available-issue-snapshot", "available-issue-snapshot", "STACKCHAIN_AVAILABLE_ISSUE_SNAPSHOT_DB", "available-issue-snapshot.sqlite3", (
|
||||
Table("available_issue_snapshot", (), (Field("items_json", "singleton"),)),
|
||||
)),
|
||||
Store("saved-searches", "saved-searches", "STACKCHAIN_SAVED_SEARCH_DB", "saved-searches.sqlite3", (
|
||||
Table("saved_searches", ("login",), (Field("views", "views:{login}"),)),
|
||||
)),
|
||||
Store("security-events", "security-events", "STACKCHAIN_SECURITY_EVENT_DB", "security-events.sqlite3", (
|
||||
Table("security_events", ("id",), (Field("payload", "event:{id}"),)),
|
||||
)),
|
||||
Store("idempotency-ledger", "idempotency-ledger", "STACKCHAIN_IDEMPOTENCY_DB", "idempotency.sqlite3", (
|
||||
Table("idempotency_operations", ("key",), (
|
||||
Field("fingerprint", "{key}:fingerprint"),
|
||||
Field("response_json", "{key}:response"),
|
||||
)),
|
||||
)),
|
||||
)
|
||||
|
||||
|
||||
def _tables(connection: sqlite3.Connection) -> set[str]:
|
||||
return {
|
||||
row[0]
|
||||
for row in connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table'"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def rotate_store(path: Path, spec: Store, config) -> dict[str, int]:
|
||||
counts = {"current": 0, "failed": 0, "migrated": 0, "total": 0}
|
||||
if not path.exists():
|
||||
return counts
|
||||
cipher = PrivateStateCipher(config, store=spec.identity)
|
||||
with connect_private_sqlite(path, timeout=1.0) as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
available = _tables(connection)
|
||||
for table in spec.tables:
|
||||
if table.name not in available:
|
||||
continue
|
||||
columns = (*table.context_columns, *(field.column for field in table.fields))
|
||||
query = f"SELECT rowid AS _rotation_rowid, {', '.join(columns)} FROM {table.name}"
|
||||
for row in connection.execute(query).fetchall():
|
||||
context = {name: row[name] for name in table.context_columns}
|
||||
updates: dict[str, str] = {}
|
||||
row_failed = False
|
||||
row_counts = {"current": 0, "migrated": 0, "total": 0}
|
||||
for field in table.fields:
|
||||
payload = row[field.column]
|
||||
if payload is None:
|
||||
continue
|
||||
row_counts["total"] += 1
|
||||
try:
|
||||
binding = field.binding.format(**context)
|
||||
if isinstance(payload, str) and not payload.startswith(("v1:", "v2:")) and field.plaintext_string:
|
||||
value, stale = payload, True
|
||||
else:
|
||||
value, stale = cipher.open(str(payload), binding=binding)
|
||||
if field.alias:
|
||||
context[field.alias] = value
|
||||
if stale:
|
||||
updates[field.column] = cipher.seal(value, binding=binding)
|
||||
row_counts["migrated"] += 1
|
||||
else:
|
||||
row_counts["current"] += 1
|
||||
except (KeyError, PrivateStateEncryptionError, ValueError):
|
||||
row_failed = True
|
||||
break
|
||||
counts["total"] += row_counts["total"]
|
||||
if row_failed:
|
||||
counts["failed"] += 1
|
||||
continue
|
||||
if updates:
|
||||
assignments = ", ".join(f"{name} = ?" for name in updates)
|
||||
connection.execute(
|
||||
f"UPDATE {table.name} SET {assignments} WHERE rowid = ?",
|
||||
(*updates.values(), row["_rotation_rowid"]),
|
||||
)
|
||||
counts["migrated"] += row_counts["migrated"]
|
||||
counts["current"] += row_counts["current"]
|
||||
return counts
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
config = private_state_encryption_config()
|
||||
if isinstance(config, bytes):
|
||||
raise PrivateStateEncryptionError("rotation requires a keyring")
|
||||
state = Path(os.getenv("STACKCHAIN_STATE_DIR", ".stackchain-state"))
|
||||
report = {
|
||||
spec.name: rotate_store(
|
||||
Path(os.getenv(spec.env, str(state / spec.filename))), spec, config
|
||||
)
|
||||
for spec in STORES
|
||||
}
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
print(json.dumps({"error": "Private-state rotation configuration is unavailable"}, sort_keys=True))
|
||||
return 2
|
||||
print(json.dumps(report, sort_keys=True))
|
||||
return 1 if any(item["failed"] for item in report.values()) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -12,7 +12,7 @@ from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import (
|
||||
PrivateStateCipher,
|
||||
PrivateStateEncryptionError,
|
||||
private_state_encryption_key,
|
||||
private_state_encryption_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ class AvailableIssueSnapshotStore:
|
||||
self.path = Path(path)
|
||||
self.clock = clock or time.time
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="available-issue-snapshot",
|
||||
)
|
||||
with self._connect() as connection:
|
||||
|
||||
@@ -36,7 +36,7 @@ FEATURE_SOURCES = {
|
||||
"planning": (
|
||||
"static/plan-today.js", "static/plan-today-readiness.js",
|
||||
"static/plan-today-preview.js", "static/today-rollover.js", "static/today-readiness.js",
|
||||
"static/tomorrow-plan.js", "static/week-calendar.js", "static/week-calendar-import.js", "static/week-plan.js", "static/search-week-plan.js", "static/search-batch-plan.js", "static/agenda-session-launcher.js", "static/mobile-plan-today-nav.js",
|
||||
"static/tomorrow-plan.js", "static/week-calendar.js", "static/week-calendar-import.js", "static/week-plan.js", "static/today-week-reschedule.js", "static/search-week-plan.js", "static/search-batch-plan.js", "static/agenda-session-launcher.js", "static/mobile-plan-today-nav.js",
|
||||
),
|
||||
"today-timer": (
|
||||
"static/conversation.js", "static/widgets.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-find-work-nav.js", "static/mobile-pull-refresh.js", "static/live-data-status.js",
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@ from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import PrivateStateCipher, private_state_encryption_key
|
||||
from src.state_encryption import PrivateStateCipher, private_state_encryption_config
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -38,7 +38,7 @@ class IdempotencyLedger:
|
||||
self.lock_timeout_seconds = lock_timeout_seconds
|
||||
self.clock = clock
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="idempotency-ledger",
|
||||
)
|
||||
self._initialize()
|
||||
|
||||
+4
-4
@@ -6,7 +6,7 @@ from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_config
|
||||
|
||||
|
||||
class LaterStore:
|
||||
@@ -26,7 +26,7 @@ class LaterStore:
|
||||
self.operation_retention_seconds = operation_retention_seconds
|
||||
self.clock = clock
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="later",
|
||||
)
|
||||
self._initialize()
|
||||
@@ -124,7 +124,7 @@ class LaterStore:
|
||||
"SELECT item_id, revision FROM later_item_revisions WHERE login = ?",
|
||||
(login,),
|
||||
):
|
||||
if stored_item_id.startswith("v1:"):
|
||||
if stored_item_id.startswith(("v1:", "v2:")):
|
||||
item_id, _legacy = self._cipher.open(
|
||||
stored_item_id, binding=f"item-revision:{login}"
|
||||
)
|
||||
@@ -141,7 +141,7 @@ class LaterStore:
|
||||
) -> dict[str, str]:
|
||||
migrated = dict(stored_ids)
|
||||
for item_id, stored_item_id in stored_ids.items():
|
||||
if stored_item_id.startswith("v1:"):
|
||||
if stored_item_id.startswith(("v1:", "v2:")):
|
||||
continue
|
||||
sealed_item_id = self._cipher.seal(
|
||||
item_id, binding=f"item-revision:{login}"
|
||||
|
||||
@@ -15,7 +15,7 @@ from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import (
|
||||
PrivateStateCipher,
|
||||
PrivateStateEncryptionError,
|
||||
private_state_encryption_key,
|
||||
private_state_encryption_config,
|
||||
)
|
||||
|
||||
SECTIONS = ("context", "events", "notifications")
|
||||
@@ -63,7 +63,7 @@ class LiveSnapshotStore:
|
||||
self.path = Path(path)
|
||||
self.clock = clock or time.time
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="live-snapshot",
|
||||
)
|
||||
self._initialize()
|
||||
|
||||
+71
-1
@@ -747,6 +747,24 @@ class WeekPromotion(BaseModel):
|
||||
today_revision: int = Field(ge=0)
|
||||
|
||||
|
||||
class WeekReschedule(BaseModel):
|
||||
operation_id: str = Field(min_length=1, max_length=100)
|
||||
identity: str = Field(min_length=1, max_length=500)
|
||||
estimate_minutes: int = Field(ge=5, le=1440)
|
||||
plan_date: str = Field(min_length=10, max_length=10)
|
||||
today_revision: int = Field(ge=0)
|
||||
week_revision: int = Field(ge=0)
|
||||
allow_over_capacity: bool = False
|
||||
|
||||
|
||||
class WeekItemPull(BaseModel):
|
||||
operation_id: str = Field(min_length=1, max_length=100)
|
||||
identity: str = Field(min_length=1, max_length=500)
|
||||
today_revision: int = Field(ge=0)
|
||||
week_revision: int = Field(ge=0)
|
||||
allow_over_capacity: bool = False
|
||||
|
||||
|
||||
class WeekReconciliation(WeekPromotion):
|
||||
ids: list[str] = Field(max_length=5)
|
||||
capacity_minutes: int | None = Field(default=None, ge=15, le=1440)
|
||||
@@ -1468,7 +1486,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/tomorrow", "/api/v1/tomorrow/promote", "/api/v1/week", "/api/v1/week/promote", "/api/v1/week/start-early", "/api/v1/week/reconcile", "/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 (
|
||||
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/tomorrow", "/api/v1/tomorrow/promote", "/api/v1/week", "/api/v1/week/promote", "/api/v1/week/start-early", "/api/v1/week/reconcile", "/api/v1/week/reschedule", "/api/v1/week/pull-item", "/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 (
|
||||
@@ -2857,6 +2875,58 @@ async def promote_week_plan(payload: WeekPromotion):
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/week/reschedule")
|
||||
async def reschedule_today_to_week(payload: WeekReschedule):
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
_today_store().reschedule_today_to_week, login, **payload.model_dump()
|
||||
)
|
||||
except WeekPlanConflict as error:
|
||||
raise HTTPException(
|
||||
status_code=409, detail={"code": "week_changed", "week": error.snapshot}
|
||||
)
|
||||
except TodayPromotionConflict as error:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={"code": "today_changed", "today": error.today, "week": error.week},
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error))
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Week Ahead rescheduling is unavailable",
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/week/pull-item")
|
||||
async def pull_week_item_into_today(payload: WeekItemPull):
|
||||
login = await _confirmed_login()
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
_today_store().pull_week_item, login, **payload.model_dump()
|
||||
)
|
||||
except WeekPlanConflict as error:
|
||||
raise HTTPException(
|
||||
status_code=409, detail={"code": "week_changed", "week": error.snapshot}
|
||||
)
|
||||
except TodayPromotionConflict as error:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={"code": "today_changed", "today": error.today, "week": error.week},
|
||||
)
|
||||
except TodayPlanFull:
|
||||
raise HTTPException(status_code=409, detail={"code": "today_full"})
|
||||
except ValueError as error:
|
||||
raise HTTPException(status_code=422, detail=str(error))
|
||||
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Adding Week Ahead work to Today is unavailable",
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/week/start-early")
|
||||
async def start_week_day_early(payload: WeekPromotion):
|
||||
login = await _confirmed_login()
|
||||
|
||||
@@ -5,7 +5,7 @@ import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_config
|
||||
|
||||
|
||||
_REPOSITORY = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
|
||||
@@ -33,7 +33,7 @@ class SavedSearchStore:
|
||||
self.limit = limit
|
||||
self.timeout = timeout
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="saved-searches",
|
||||
)
|
||||
self._initialize()
|
||||
|
||||
@@ -10,7 +10,7 @@ from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import (
|
||||
PrivateStateCipher,
|
||||
PrivateStateEncryptionError,
|
||||
private_state_encryption_key,
|
||||
private_state_encryption_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ class SecurityEventStore:
|
||||
self.lock_timeout_seconds = lock_timeout_seconds
|
||||
try:
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="security-events",
|
||||
)
|
||||
except PrivateStateEncryptionError as exc:
|
||||
|
||||
+136
-18
@@ -6,6 +6,8 @@ import base64
|
||||
import binascii
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
@@ -16,7 +18,7 @@ class PrivateStateEncryptionError(RuntimeError):
|
||||
|
||||
|
||||
def decode_private_state_encryption_key(encoded: str) -> bytes:
|
||||
"""Decode the independently injected 256-bit private-state key."""
|
||||
"""Decode an independently injected 256-bit private-state key."""
|
||||
try:
|
||||
key = base64.b64decode(encoded, validate=True)
|
||||
except (binascii.Error, ValueError) as error:
|
||||
@@ -31,38 +33,130 @@ def decode_private_state_encryption_key(encoded: str) -> bytes:
|
||||
|
||||
|
||||
def private_state_encryption_key() -> bytes:
|
||||
"""Load the legacy single key setting."""
|
||||
return decode_private_state_encryption_key(
|
||||
os.getenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY", "")
|
||||
)
|
||||
|
||||
|
||||
_KEY_ID = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
|
||||
_MAX_KEYS = 4
|
||||
|
||||
|
||||
def decode_private_state_encryption_keyring(
|
||||
encoded: str, active_key_id: str
|
||||
) -> tuple[dict[str, bytes], str]:
|
||||
"""Decode a bounded key-ID-to-key JSON object and validate its active key."""
|
||||
try:
|
||||
raw = json.loads(encoded)
|
||||
except (TypeError, json.JSONDecodeError) as error:
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state encryption keyring is invalid"
|
||||
) from error
|
||||
if not isinstance(raw, dict) or not raw:
|
||||
raise PrivateStateEncryptionError("private state encryption keyring is invalid")
|
||||
if len(raw) > _MAX_KEYS:
|
||||
raise PrivateStateEncryptionError(
|
||||
f"private state encryption keyring supports at most {_MAX_KEYS} keys"
|
||||
)
|
||||
keys: dict[str, bytes] = {}
|
||||
for key_id, value in raw.items():
|
||||
if not isinstance(key_id, str) or not _KEY_ID.fullmatch(key_id):
|
||||
raise PrivateStateEncryptionError("private state encryption key ID is invalid")
|
||||
if not isinstance(value, str):
|
||||
raise PrivateStateEncryptionError("private state encryption keyring is invalid")
|
||||
keys[key_id] = decode_private_state_encryption_key(value)
|
||||
if active_key_id not in keys:
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state active key is missing from the keyring"
|
||||
)
|
||||
return keys, active_key_id
|
||||
|
||||
|
||||
def private_state_encryption_config() -> bytes | tuple[dict[str, bytes], str]:
|
||||
"""Load a rotation keyring when configured, otherwise the legacy single key."""
|
||||
encoded = os.getenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS", "")
|
||||
active = os.getenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", "")
|
||||
if encoded or active:
|
||||
return decode_private_state_encryption_keyring(encoded, active)
|
||||
return private_state_encryption_key()
|
||||
|
||||
|
||||
class PrivateStateCipher:
|
||||
"""Seal JSON values with store-specific authenticated context."""
|
||||
|
||||
def __init__(self, key: bytes, *, store: str):
|
||||
if not isinstance(key, bytes) or len(key) != 32:
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state encryption requires exactly 32 key bytes"
|
||||
)
|
||||
def __init__(
|
||||
self,
|
||||
key: bytes | Mapping[str, bytes] | tuple[dict[str, bytes], str],
|
||||
*,
|
||||
store: str,
|
||||
active_key_id: str | None = None,
|
||||
):
|
||||
if isinstance(key, tuple):
|
||||
key, active_key_id = key
|
||||
if isinstance(key, Mapping):
|
||||
if not key or len(key) > _MAX_KEYS or active_key_id not in key:
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state encryption keyring configuration is invalid"
|
||||
)
|
||||
ciphers: dict[str, AESGCM] = {}
|
||||
for key_id, raw_key in key.items():
|
||||
if not isinstance(key_id, str) or not _KEY_ID.fullmatch(key_id):
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state encryption key ID is invalid"
|
||||
)
|
||||
if not isinstance(raw_key, bytes) or len(raw_key) != 32:
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state encryption requires exactly 32 key bytes"
|
||||
)
|
||||
ciphers[key_id] = AESGCM(raw_key)
|
||||
self._ciphers = ciphers
|
||||
self._active_key_id = active_key_id
|
||||
self._legacy_cipher = None
|
||||
else:
|
||||
if not isinstance(key, bytes) or len(key) != 32:
|
||||
raise PrivateStateEncryptionError(
|
||||
"private state encryption requires exactly 32 key bytes"
|
||||
)
|
||||
self._ciphers = {}
|
||||
self._active_key_id = None
|
||||
self._legacy_cipher = AESGCM(key)
|
||||
if not store or "\0" in store:
|
||||
raise ValueError("private state store identity is invalid")
|
||||
self._cipher = AESGCM(key)
|
||||
self._store = store
|
||||
|
||||
def _aad(self, binding: str) -> bytes:
|
||||
return f"stackchain:private-state:v1\0{self._store}\0{binding}".encode()
|
||||
def _aad(self, binding: str, *, version: str = "v1", key_id: str = "") -> bytes:
|
||||
prefix = f"stackchain:private-state:{version}\0{self._store}\0{binding}"
|
||||
if version == "v2":
|
||||
prefix += f"\0{key_id}"
|
||||
return prefix.encode()
|
||||
|
||||
def seal(self, value: object, *, binding: str = "singleton") -> str:
|
||||
plaintext = json.dumps(value, separators=(",", ":")).encode()
|
||||
nonce = os.urandom(12)
|
||||
sealed = nonce + self._cipher.encrypt(nonce, plaintext, self._aad(binding))
|
||||
if self._active_key_id is not None:
|
||||
key_id = self._active_key_id
|
||||
sealed = nonce + self._ciphers[key_id].encrypt(
|
||||
nonce, plaintext, self._aad(binding, version="v2", key_id=key_id)
|
||||
)
|
||||
return f"v2:{key_id}:" + base64.urlsafe_b64encode(sealed).decode()
|
||||
sealed = nonce + self._legacy_cipher.encrypt(
|
||||
nonce, plaintext, self._aad(binding)
|
||||
)
|
||||
return "v1:" + base64.urlsafe_b64encode(sealed).decode()
|
||||
|
||||
@staticmethod
|
||||
def _decode_sealed(payload: str) -> bytes:
|
||||
sealed = base64.b64decode(payload, altchars=b"-_", validate=True)
|
||||
if len(sealed) < 28:
|
||||
raise ValueError("encrypted payload is too short")
|
||||
return sealed
|
||||
|
||||
def open(self, payload: str, *, binding: str = "singleton") -> tuple[object, bool]:
|
||||
"""Return the decoded value and whether plaintext migration is required."""
|
||||
"""Return the decoded value and whether active-key rewrapping is required."""
|
||||
if not isinstance(payload, str):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
if not payload.startswith("v1:"):
|
||||
if not payload.startswith(("v1:", "v2:")):
|
||||
try:
|
||||
return json.loads(payload), True
|
||||
except (TypeError, json.JSONDecodeError) as error:
|
||||
@@ -70,13 +164,37 @@ class PrivateStateCipher:
|
||||
"private state could not be decrypted"
|
||||
) from error
|
||||
try:
|
||||
sealed = base64.b64decode(payload[3:], altchars=b"-_", validate=True)
|
||||
if len(sealed) < 28:
|
||||
raise ValueError("encrypted payload is too short")
|
||||
plaintext = self._cipher.decrypt(
|
||||
sealed[:12], sealed[12:], self._aad(binding)
|
||||
if payload.startswith("v2:"):
|
||||
_, key_id, encoded = payload.split(":", 2)
|
||||
cipher = self._ciphers.get(key_id)
|
||||
if cipher is None:
|
||||
raise ValueError("encrypted payload uses an unavailable key")
|
||||
sealed = self._decode_sealed(encoded)
|
||||
plaintext = cipher.decrypt(
|
||||
sealed[:12],
|
||||
sealed[12:],
|
||||
self._aad(binding, version="v2", key_id=key_id),
|
||||
)
|
||||
return json.loads(plaintext), key_id != self._active_key_id
|
||||
|
||||
sealed = self._decode_sealed(payload[3:])
|
||||
candidates = (
|
||||
[self._legacy_cipher]
|
||||
if self._legacy_cipher is not None
|
||||
else list(self._ciphers.values())
|
||||
)
|
||||
return json.loads(plaintext), False
|
||||
plaintext = None
|
||||
for cipher in candidates:
|
||||
try:
|
||||
plaintext = cipher.decrypt(
|
||||
sealed[:12], sealed[12:], self._aad(binding)
|
||||
)
|
||||
break
|
||||
except InvalidTag:
|
||||
continue
|
||||
if plaintext is None:
|
||||
raise InvalidTag
|
||||
return json.loads(plaintext), self._active_key_id is not None
|
||||
except (
|
||||
binascii.Error,
|
||||
InvalidTag,
|
||||
|
||||
+211
-8
@@ -8,7 +8,7 @@ from pathlib import Path
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from src.private_state import connect_private_sqlite
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
|
||||
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_config
|
||||
|
||||
|
||||
class TodayPlanFull(ValueError):
|
||||
@@ -77,14 +77,14 @@ class TodayStore:
|
||||
self.recap_limit = recap_limit
|
||||
self.clock = clock
|
||||
self._cipher = PrivateStateCipher(
|
||||
encryption_key if encryption_key is not None else private_state_encryption_key(),
|
||||
encryption_key if encryption_key is not None else private_state_encryption_config(),
|
||||
store="today",
|
||||
)
|
||||
self._initialize()
|
||||
|
||||
def _initialize(self) -> None:
|
||||
connection = connect_private_sqlite(self.path, timeout=self.timeout)
|
||||
if connection.execute("PRAGMA user_version").fetchone()[0] >= 5:
|
||||
if connection.execute("PRAGMA user_version").fetchone()[0] >= 7:
|
||||
connection.close()
|
||||
return
|
||||
connection.execute("PRAGMA journal_mode=WAL")
|
||||
@@ -189,7 +189,17 @@ class TodayStore:
|
||||
"login TEXT NOT NULL, promotion_id TEXT NOT NULL, result TEXT NOT NULL, "
|
||||
"created_at REAL NOT NULL, PRIMARY KEY (login, promotion_id))"
|
||||
)
|
||||
connection.execute("PRAGMA user_version = 5")
|
||||
connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS week_reschedules ("
|
||||
"login TEXT NOT NULL, operation_id TEXT NOT NULL, result TEXT NOT NULL, "
|
||||
"created_at REAL NOT NULL, PRIMARY KEY (login, operation_id))"
|
||||
)
|
||||
connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS week_item_pulls ("
|
||||
"login TEXT NOT NULL, operation_id TEXT NOT NULL, result TEXT NOT NULL, "
|
||||
"created_at REAL NOT NULL, PRIMARY KEY (login, operation_id))"
|
||||
)
|
||||
connection.execute("PRAGMA user_version = 7")
|
||||
connection.commit()
|
||||
connection.close()
|
||||
|
||||
@@ -223,7 +233,7 @@ class TodayStore:
|
||||
def _snapshot(self, row, login: str) -> tuple[dict, bool]:
|
||||
if row is None:
|
||||
return {"revision": 0, "ids": [], "capacity_minutes": None, "estimates": {}}, False
|
||||
if row[1].startswith("v1:"):
|
||||
if row[1].startswith(("v1:", "v2:")):
|
||||
payload, legacy = self._cipher.open(row[1], binding=f"plan:{login}")
|
||||
if not isinstance(payload, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
@@ -568,6 +578,199 @@ class TodayStore:
|
||||
)
|
||||
return snapshot
|
||||
|
||||
def reschedule_today_to_week(
|
||||
self, login: str, *, operation_id: str, identity: str, estimate_minutes: int,
|
||||
plan_date: str, today_revision: int, week_revision: int,
|
||||
allow_over_capacity: bool = False,
|
||||
) -> dict:
|
||||
"""Atomically move one current Today item to one Week Ahead date."""
|
||||
login = self._normalize_login(login)
|
||||
if not isinstance(operation_id, str) or not operation_id.strip() or len(operation_id) > 100:
|
||||
raise ValueError("operation_id is required and bounded")
|
||||
operation_id = operation_id.strip()
|
||||
if not isinstance(identity, str) or not identity or len(identity) > 500:
|
||||
raise ValueError("identity is required and bounded")
|
||||
if (
|
||||
not isinstance(estimate_minutes, int) or isinstance(estimate_minutes, bool)
|
||||
or estimate_minutes < 5 or estimate_minutes > 1440
|
||||
):
|
||||
raise ValueError("estimate_minutes must be between 5 and 1440")
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
receipt = connection.execute(
|
||||
"SELECT result FROM week_reschedules WHERE login = ? AND operation_id = ?",
|
||||
(login, operation_id),
|
||||
).fetchone()
|
||||
if receipt:
|
||||
result, _legacy = self._cipher.open(
|
||||
receipt[0], binding=f"week-reschedule:{login}:{operation_id}"
|
||||
)
|
||||
if not isinstance(result, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
return result
|
||||
today_row = connection.execute(
|
||||
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
|
||||
"FROM today_plans WHERE login = ?", (login,),
|
||||
).fetchone()
|
||||
today, _legacy = self._snapshot(today_row, login)
|
||||
week_row = connection.execute(
|
||||
"SELECT revision, payload FROM week_plans WHERE login = ?", (login,)
|
||||
).fetchone()
|
||||
week = self._week_snapshot(week_row, login)
|
||||
if today["revision"] != today_revision or identity not in today["ids"]:
|
||||
raise TodayPromotionConflict(today, week)
|
||||
if week["revision"] != week_revision:
|
||||
raise WeekPlanConflict(week)
|
||||
|
||||
days = []
|
||||
for source in week["days"]:
|
||||
estimates = dict(source.get("estimates", {}))
|
||||
estimates.pop(identity, None)
|
||||
days.append({
|
||||
**source,
|
||||
"ids": [item_id for item_id in source.get("ids", []) if item_id != identity],
|
||||
"estimates": estimates,
|
||||
})
|
||||
destination = next((day for day in days if day["plan_date"] == plan_date), None)
|
||||
if destination is None:
|
||||
destination = {
|
||||
"plan_date": plan_date, "ids": [],
|
||||
"capacity_minutes": None, "estimates": {},
|
||||
}
|
||||
days.append(destination)
|
||||
destination["ids"].append(identity)
|
||||
destination["estimates"][identity] = estimate_minutes
|
||||
planned_minutes = sum(
|
||||
int(destination["estimates"].get(item_id, 0)) for item_id in destination["ids"]
|
||||
)
|
||||
if (
|
||||
destination.get("capacity_minutes") is not None
|
||||
and planned_minutes > destination["capacity_minutes"]
|
||||
and not allow_over_capacity
|
||||
):
|
||||
raise ValueError("explicit overload confirmation is required")
|
||||
normalized_week = self._normalize_week(days=days, timezone=week["timezone"])
|
||||
|
||||
today_ids = [item_id for item_id in today["ids"] if item_id != identity]
|
||||
today_estimates = {
|
||||
item_id: minutes for item_id, minutes in today["estimates"].items()
|
||||
if item_id != identity
|
||||
}
|
||||
today_result = {
|
||||
**today, "revision": today_revision + 1,
|
||||
"ids": today_ids, "estimates": today_estimates,
|
||||
}
|
||||
week_result = {"revision": week_revision + 1, **normalized_week}
|
||||
connection.execute(
|
||||
"UPDATE today_plans SET revision = ?, ids = ?, capacity_minutes = NULL, "
|
||||
"estimates = '{}', plan_date = NULL, timezone = NULL WHERE login = ?",
|
||||
(today_result["revision"], self._sealed_plan(login, today_result), login),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE week_plans SET revision = ?, payload = ? WHERE login = ?",
|
||||
(week_result["revision"], self._cipher.seal(
|
||||
normalized_week, binding=f"week:{login}"
|
||||
), login),
|
||||
)
|
||||
result = {"today": today_result, "week": week_result}
|
||||
connection.execute(
|
||||
"INSERT INTO week_reschedules(login, operation_id, result, created_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
(login, operation_id, self._cipher.seal(
|
||||
result, binding=f"week-reschedule:{login}:{operation_id}"
|
||||
), self.clock()),
|
||||
)
|
||||
return result
|
||||
|
||||
def pull_week_item(
|
||||
self, login: str, *, operation_id: str, identity: str,
|
||||
today_revision: int, week_revision: int, allow_over_capacity: bool = False,
|
||||
) -> dict:
|
||||
"""Atomically append one Week Ahead item to Today and remove it from Week."""
|
||||
login = self._normalize_login(login)
|
||||
if not isinstance(operation_id, str) or not operation_id.strip() or len(operation_id) > 100:
|
||||
raise ValueError("operation_id is required and bounded")
|
||||
if not isinstance(identity, str) or not identity or len(identity) > 500:
|
||||
raise ValueError("identity is required and bounded")
|
||||
operation_id = operation_id.strip()
|
||||
with self._connect() as connection:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
receipt = connection.execute(
|
||||
"SELECT result FROM week_item_pulls WHERE login = ? AND operation_id = ?",
|
||||
(login, operation_id),
|
||||
).fetchone()
|
||||
if receipt:
|
||||
result, _legacy = self._cipher.open(
|
||||
receipt[0], binding=f"week-item-pull:{login}:{operation_id}"
|
||||
)
|
||||
if not isinstance(result, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
return result
|
||||
today_row = connection.execute(
|
||||
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
|
||||
"FROM today_plans WHERE login = ?", (login,),
|
||||
).fetchone()
|
||||
today, _legacy = self._snapshot(today_row, login)
|
||||
week_row = connection.execute(
|
||||
"SELECT revision, payload FROM week_plans WHERE login = ?", (login,),
|
||||
).fetchone()
|
||||
week = self._week_snapshot(week_row, login)
|
||||
if today["revision"] != today_revision:
|
||||
raise TodayPromotionConflict(today, week)
|
||||
if week["revision"] != week_revision:
|
||||
raise WeekPlanConflict(week)
|
||||
if identity in today["ids"]:
|
||||
raise ValueError("work is already in Today")
|
||||
if len(today["ids"]) >= self.limit:
|
||||
raise TodayPlanFull("Today plan is full")
|
||||
source = next((day for day in week["days"] if identity in day["ids"]), None)
|
||||
if source is None:
|
||||
raise WeekPlanConflict(week)
|
||||
estimate = source.get("estimates", {}).get(identity)
|
||||
planned_minutes = sum(
|
||||
int(today["estimates"].get(item_id, 0)) for item_id in today["ids"]
|
||||
) + (int(estimate) if estimate else 0)
|
||||
if (
|
||||
today.get("capacity_minutes") is not None
|
||||
and planned_minutes > today["capacity_minutes"]
|
||||
and not allow_over_capacity
|
||||
):
|
||||
raise ValueError("moving work over Today capacity requires explicit overload confirmation")
|
||||
today_result = {
|
||||
**today, "revision": today_revision + 1,
|
||||
"ids": [*today["ids"], identity],
|
||||
"estimates": {**today["estimates"], **({identity: estimate} if estimate else {})},
|
||||
}
|
||||
remaining_days = []
|
||||
for day in week["days"]:
|
||||
estimates = dict(day.get("estimates", {}))
|
||||
estimates.pop(identity, None)
|
||||
remaining_days.append({
|
||||
**day, "ids": [item_id for item_id in day["ids"] if item_id != identity],
|
||||
"estimates": estimates,
|
||||
})
|
||||
week_payload = {"timezone": week["timezone"], "days": remaining_days}
|
||||
week_result = {"revision": week_revision + 1, **week_payload}
|
||||
connection.execute(
|
||||
"INSERT INTO today_plans(login, revision, ids, capacity_minutes, estimates, plan_date, timezone) "
|
||||
"VALUES (?, ?, ?, NULL, '{}', NULL, NULL) ON CONFLICT(login) DO UPDATE SET "
|
||||
"revision=excluded.revision, ids=excluded.ids, capacity_minutes=NULL, estimates='{}', "
|
||||
"plan_date=NULL, timezone=NULL",
|
||||
(login, today_result["revision"], self._sealed_plan(login, today_result)),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE week_plans SET revision = ?, payload = ? WHERE login = ?",
|
||||
(week_result["revision"], self._cipher.seal(week_payload, binding=f"week:{login}"), login),
|
||||
)
|
||||
result = {"today": today_result, "week": week_result}
|
||||
connection.execute(
|
||||
"INSERT INTO week_item_pulls(login, operation_id, result, created_at) VALUES (?, ?, ?, ?)",
|
||||
(login, operation_id, self._cipher.seal(
|
||||
result, binding=f"week-item-pull:{login}:{operation_id}"
|
||||
), self.clock()),
|
||||
)
|
||||
return result
|
||||
|
||||
def promote_week(
|
||||
self, login: str, *, promotion_id: str, week_revision: int,
|
||||
plan_date: str, today_revision: int, allow_future: bool = False,
|
||||
@@ -719,7 +922,7 @@ class TodayStore:
|
||||
def _session_snapshot(self, row, login: str) -> tuple[dict, bool]:
|
||||
if row is None:
|
||||
return self._empty_session(), False
|
||||
if row[1].startswith("v1:"):
|
||||
if row[1].startswith(("v1:", "v2:")):
|
||||
payload, legacy = self._cipher.open(row[1], binding=f"session:{login}")
|
||||
if not isinstance(payload, dict):
|
||||
raise PrivateStateEncryptionError("private state could not be decrypted")
|
||||
@@ -820,7 +1023,7 @@ class TodayStore:
|
||||
def _recap_snapshot(
|
||||
self, login: str, encrypted_session_id: str, created_at: float, serialized: str
|
||||
) -> tuple[dict, bool]:
|
||||
if encrypted_session_id.startswith("v1:"):
|
||||
if encrypted_session_id.startswith(("v1:", "v2:")):
|
||||
session_id, legacy_session = self._cipher.open(
|
||||
encrypted_session_id, binding=f"recap-id:{login}"
|
||||
)
|
||||
@@ -912,7 +1115,7 @@ class TodayStore:
|
||||
|
||||
def _time_log_snapshot(self, login: str, row) -> tuple[dict, bool]:
|
||||
encrypted_session, encrypted_identity, payload_value, status_value = row
|
||||
if encrypted_session.startswith("v1:"):
|
||||
if encrypted_session.startswith(("v1:", "v2:")):
|
||||
session_id = self._cipher.open(
|
||||
encrypted_session, binding=f"time-log-session:{login}"
|
||||
)[0]
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
|
||||
pytest.skip("packaged Today to Week Ahead journey runs only in its gated CI job", allow_module_level=True)
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
from fake_gitea import FakeGiteaServer
|
||||
from test_mobile_offline_issue_release import ACCESS_TOKEN, ROOT, release_server
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)])
|
||||
def test_release_artifact_reschedules_active_today_into_week_ahead(
|
||||
tmp_path: Path, width: int, height: int
|
||||
):
|
||||
archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz"))
|
||||
assert len(archives) == 1, "browser job must download exactly one assembled release archive"
|
||||
fake = FakeGiteaServer(("127.0.0.1", 0))
|
||||
thread = threading.Thread(target=fake.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
with release_server(
|
||||
archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}"
|
||||
) as origin, sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
|
||||
page = browser.new_page(
|
||||
viewport={"width": width, "height": height}, timezone_id="UTC"
|
||||
)
|
||||
page_errors: list[str] = []
|
||||
page.on("pageerror", lambda error: page_errors.append(str(error)))
|
||||
page.goto(origin + "/", wait_until="networkidle")
|
||||
page.locator('input[name="device_label"]').fill("Reschedule release phone")
|
||||
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
|
||||
page.locator("#submit-sign-in").click()
|
||||
page.wait_for_url(origin + "/", wait_until="networkidle")
|
||||
|
||||
plan_date = (date.today() + timedelta(days=2)).isoformat()
|
||||
saved_week = page.evaluate(
|
||||
"""async ({planDate}) => {
|
||||
const response=await fetch('api/v1/week',{method:'PUT',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({base_revision:0,timezone:'UTC',days:[{
|
||||
plan_date:planDate,ids:[],capacity_minutes:90,estimates:{}
|
||||
}]})});
|
||||
return {status:response.status,body:await response.json()};
|
||||
}""",
|
||||
{"planDate": plan_date},
|
||||
)
|
||||
assert saved_week["status"] == 200
|
||||
|
||||
page.locator('[data-mobile-task="work"]').click()
|
||||
page.locator("#plan-today-available").fill("90")
|
||||
page.locator("#plan-today-available").press("Tab")
|
||||
page.locator("#build-today-plan").click()
|
||||
missing = page.locator("[data-plan-missing-estimate]")
|
||||
for _ in range(2):
|
||||
missing.nth(0).fill("30")
|
||||
missing.nth(0).press("Tab")
|
||||
save_and_start = page.locator("#save-and-start-today")
|
||||
expect(save_and_start).to_be_enabled()
|
||||
save_and_start.click()
|
||||
expect(page.locator("#plan-today-sheet")).to_be_hidden(timeout=10_000)
|
||||
expect(page.locator("#issue-sheet-title")).to_have_text("Ship mobile capture")
|
||||
if page.locator("#plan-today-sheet").is_visible():
|
||||
page.locator("#cancel-plan-today").click()
|
||||
page.locator("#close-issue-sheet").click()
|
||||
if page.locator("#plan-today-sheet").is_visible():
|
||||
page.locator("#cancel-plan-today").click()
|
||||
|
||||
launcher = page.locator("[data-work-session-reschedule-week]")
|
||||
page.locator("[data-mobile-today-more]").click()
|
||||
expect(launcher).to_be_visible()
|
||||
launcher_bounds = launcher.bounding_box()
|
||||
assert launcher_bounds and launcher_bounds["height"] >= 44
|
||||
launcher.click()
|
||||
dialog = page.locator("#today-week-reschedule")
|
||||
expect(dialog).to_be_visible()
|
||||
days = page.locator("#today-week-reschedule-days button")
|
||||
try:
|
||||
expect(days).to_have_count(7)
|
||||
except AssertionError as error:
|
||||
raise AssertionError({
|
||||
"status": page.locator("#today-week-reschedule-status").text_content(),
|
||||
"page_errors": page_errors,
|
||||
"today": page.evaluate("async()=>await (await fetch('api/v1/today')).json()"),
|
||||
"week": page.evaluate("async()=>await (await fetch('api/v1/week')).json()"),
|
||||
}) from error
|
||||
for control in [*days.all(), page.locator("#cancel-today-week-reschedule"), page.locator("#confirm-today-week-reschedule")]:
|
||||
bounds = control.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
|
||||
page.locator("#cancel-today-week-reschedule").click()
|
||||
expect(dialog).to_be_hidden()
|
||||
expect(launcher).to_be_focused()
|
||||
|
||||
launcher.click()
|
||||
destination = page.locator(
|
||||
f'#today-week-reschedule-days button[data-plan-date="{plan_date}"]'
|
||||
)
|
||||
destination.click()
|
||||
page.locator("#confirm-today-week-reschedule").click()
|
||||
expect(dialog).to_be_hidden()
|
||||
expect(page.locator("#issue-sheet-title")).to_have_text("Polish desktop filters")
|
||||
week = page.evaluate("async()=>await (await fetch('api/v1/week')).json()")
|
||||
today = page.evaluate("async()=>await (await fetch('api/v1/today')).json()")
|
||||
assert week["days"][0]["plan_date"] == plan_date
|
||||
assert len(week["days"][0]["ids"]) == 1
|
||||
assert len(today["ids"]) == 1
|
||||
assert not page_errors
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
browser.close()
|
||||
finally:
|
||||
fake.shutdown()
|
||||
fake.server_close()
|
||||
thread.join(timeout=2)
|
||||
@@ -34,6 +34,29 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
|
||||
page = browser.new_page(viewport={"width": width, "height": height}, timezone_id="UTC")
|
||||
page_errors: list[str] = []
|
||||
page.on("pageerror", lambda error: page_errors.append(str(error)))
|
||||
pulled: list[dict] = []
|
||||
|
||||
page.route("**/api/v1/today", lambda route: route.fulfill(
|
||||
status=200, content_type="application/json", body=json.dumps({
|
||||
"revision": 3, "ids": ["issue:acme/mobile:99:"],
|
||||
"capacity_minutes": 60, "estimates": {"issue:acme/mobile:99:": 30},
|
||||
}),
|
||||
))
|
||||
|
||||
def pull_item_route(route):
|
||||
body = json.loads(route.request.post_data or "{}")
|
||||
pulled.append(body)
|
||||
route.fulfill(status=200, content_type="application/json", body=json.dumps({
|
||||
"today": {"revision": 4, "ids": ["issue:acme/mobile:99:", body["identity"]],
|
||||
"capacity_minutes": 60,
|
||||
"estimates": {"issue:acme/mobile:99:": 30, body["identity"]: 45}},
|
||||
"week": {"revision": 99, "timezone": "UTC", "days": [{
|
||||
"plan_date": (date.today() + timedelta(days=1)).isoformat(),
|
||||
"ids": [], "capacity_minutes": 60, "estimates": {},
|
||||
}]},
|
||||
}))
|
||||
|
||||
page.route("**/api/v1/week/pull-item", pull_item_route)
|
||||
|
||||
def week_route(route):
|
||||
if route.request.method == "PUT":
|
||||
@@ -53,11 +76,21 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
|
||||
}))
|
||||
|
||||
page.route("**/api/v1/week", week_route)
|
||||
page.route(
|
||||
"**/api/v1/repos/acme/mobile/issues/41/close",
|
||||
lambda route: route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body='{"number":41,"state":"closed","updated_at":"2026-08-21T12:00:00Z"}',
|
||||
),
|
||||
)
|
||||
page.goto(origin + "/", wait_until="networkidle")
|
||||
page.locator('input[name="device_label"]').fill("Week Ahead release phone")
|
||||
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
|
||||
page.locator("#submit-sign-in").click()
|
||||
page.wait_for_url(origin + "/", wait_until="networkidle")
|
||||
if page.locator("#plan-today-sheet").is_visible():
|
||||
page.locator("#cancel-plan-today").click()
|
||||
page.locator('[data-mobile-task="queues"]').click()
|
||||
page.locator('[data-mobile-queue="week"]').click()
|
||||
page.wait_for_timeout(100)
|
||||
@@ -76,6 +109,27 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
|
||||
expect(page.locator("#confirm-week-plan")).to_be_hidden()
|
||||
edit_week = page.locator("#edit-week-plan")
|
||||
expect(edit_week).to_be_visible()
|
||||
remove_actions = cards.first.locator("[data-week-unplan]")
|
||||
expect(remove_actions).to_have_count(2)
|
||||
remove_bounds = remove_actions.nth(1).bounding_box()
|
||||
assert remove_bounds and remove_bounds["height"] >= 44
|
||||
remove_actions.nth(1).click()
|
||||
expect(cards.first).not_to_contain_text("Polish desktop filters")
|
||||
expect(page.locator("#week-unplan-receipt")).to_have_text(
|
||||
"Polish desktop filters removed from Week Ahead."
|
||||
)
|
||||
undo = page.locator("#undo-week-unplan")
|
||||
expect(undo).to_be_visible()
|
||||
undo_bounds = undo.bounding_box()
|
||||
assert undo_bounds and undo_bounds["height"] >= 44
|
||||
undo.click()
|
||||
expect(cards.first).to_contain_text("Polish desktop filters")
|
||||
expect(page.locator("#week-unplan-receipt")).to_be_hidden()
|
||||
assert saved[-2]["days"][0]["ids"] == ["issue:acme/mobile:41:"]
|
||||
assert saved[-1]["days"][0]["ids"] == [
|
||||
"issue:acme/mobile:41:", "issue:acme/mobile:42:"
|
||||
]
|
||||
writes_before_reflow = len(saved)
|
||||
reflow = page.locator("#open-week-reflow")
|
||||
expect(reflow).to_be_visible()
|
||||
bounds = reflow.bounding_box()
|
||||
@@ -93,12 +147,12 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
page.locator("#cancel-week-reflow").click()
|
||||
expect(preview).to_be_hidden()
|
||||
assert saved == [], "cancelling reflow must not write"
|
||||
assert len(saved) == writes_before_reflow, "cancelling reflow must not write"
|
||||
reflow.click()
|
||||
page.locator("#apply-week-reflow").click()
|
||||
expect(page.locator("#week-review-status")).to_have_text("Week Ahead reflowed and saved.")
|
||||
expect(preview).to_be_hidden()
|
||||
assert len(saved) == 1
|
||||
assert len(saved) == writes_before_reflow + 1
|
||||
assert [day["ids"] for day in saved[-1]["days"]][:2] == [["issue:acme/mobile:41:"], []]
|
||||
planned_item = cards.first.locator("[data-week-open-item]")
|
||||
expect(planned_item).to_have_count(1)
|
||||
@@ -112,7 +166,7 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
|
||||
expect(page.locator("#issue-sheet")).not_to_have_class(re.compile(r"\bopen\b"))
|
||||
expect(overview).to_be_visible()
|
||||
expect(planned_item).to_be_focused()
|
||||
assert len(saved) == 1, "opening and inspecting Week Ahead must not add a write"
|
||||
assert len(saved) == writes_before_reflow + 1, "opening and inspecting Week Ahead must not add a write"
|
||||
for control in (cards.first.locator("[data-week-edit-day]"), edit_week):
|
||||
bounds = control.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
@@ -242,6 +296,47 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
|
||||
assert [day["plan_date"] for day in saved[-1]["days"]] == sorted(
|
||||
day["plan_date"] for day in saved[-1]["days"]
|
||||
)
|
||||
|
||||
before_retirement = len(saved)
|
||||
page.locator('[data-mobile-task="queues"]').click()
|
||||
page.locator('[data-mobile-queue="week"]').click()
|
||||
expect(overview).to_be_visible()
|
||||
planned_item = cards.first.locator(
|
||||
'[data-week-open-item="issue:acme/mobile:41:"]'
|
||||
)
|
||||
planned_item.click()
|
||||
expect(page.locator("#issue-sheet-title")).to_have_text("Ship mobile capture")
|
||||
page.once("dialog", lambda dialog: dialog.accept())
|
||||
page.locator("#close-issue").click()
|
||||
expect(page.locator("#issue-sheet")).not_to_have_class(re.compile(r"\bopen\b"))
|
||||
expect(cards.first).not_to_contain_text("Ship mobile capture")
|
||||
expect(cards.first).to_contain_text("Polish desktop filters")
|
||||
expect(cards.first).to_contain_text("45 of 60 min")
|
||||
expect(page.locator("#week-review-status")).to_have_text(
|
||||
"Ship mobile capture removed and Week Ahead saved."
|
||||
)
|
||||
expect(edit_week).to_be_focused()
|
||||
assert len(saved) == before_retirement + 1
|
||||
assert saved[-1]["days"][0]["ids"] == ["issue:acme/mobile:42:"]
|
||||
assert saved[-1]["days"][0]["capacity_minutes"] == 60
|
||||
pull = cards.first.locator('[data-week-pull-item="issue:acme/mobile:42:"]')
|
||||
expect(pull).to_have_text("Review Today · 75 of 60 min")
|
||||
pull_bounds = pull.bounding_box()
|
||||
assert pull_bounds and pull_bounds["height"] >= 44
|
||||
page.once("dialog", lambda dialog: dialog.dismiss())
|
||||
pull.click()
|
||||
expect(cards.first).to_contain_text("Polish desktop filters")
|
||||
assert pulled == [], "cancelling the overload review must not submit"
|
||||
expect(pull).to_have_text("Review Today · 75 of 60 min")
|
||||
page.once("dialog", lambda dialog: dialog.accept())
|
||||
pull.click()
|
||||
expect(cards.first).not_to_contain_text("Polish desktop filters")
|
||||
expect(page.locator("#week-review-status")).to_have_text(
|
||||
"Polish desktop filters added to Today."
|
||||
)
|
||||
assert pulled and pulled[-1]["identity"] == "issue:acme/mobile:42:"
|
||||
assert pulled[-1]["today_revision"] == 3
|
||||
assert pulled[-1]["allow_over_capacity"] is True
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
browser.close()
|
||||
finally:
|
||||
|
||||
@@ -70,6 +70,14 @@ def test_release_promotion_waits_for_packaged_mobile_journeys():
|
||||
"tests/e2e/test_mobile_today_summary_release.py "
|
||||
"tests/e2e/test_mobile_tomorrow_conflict_release.py "
|
||||
"tests/e2e/test_mobile_week_ahead_release.py "
|
||||
"tests/e2e/test_mobile_today_week_reschedule_release.py "
|
||||
"tests/e2e/test_mobile_wrap_up_handoff_release.py -q"
|
||||
) in browser
|
||||
assert "needs: [lint, build-release, browser-journey]" in release
|
||||
|
||||
|
||||
def test_browser_job_runs_packaged_today_week_reschedule_journey():
|
||||
text = WORKFLOW.read_text()
|
||||
browser = text[text.index(" browser-journey:") : text.index(" release-candidate:")]
|
||||
|
||||
assert "tests/e2e/test_mobile_today_week_reschedule_release.py" in browser
|
||||
@@ -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-v128" in worker
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in worker
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in worker
|
||||
assert "stackchain-dashboard-shell-v130" in worker
|
||||
|
||||
|
||||
def test_all_conversation_composers_offer_accessible_mobile_mentions():
|
||||
|
||||
@@ -383,7 +383,7 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
|
||||
assert "controller.recoverPermission('deadline')" in dashboard
|
||||
assert "pushControllerReady.then(ensureDeviceSetup)" in dashboard
|
||||
assert "BASE + 'static/mobile-device-setup.js'" in worker
|
||||
assert "stackchain-dashboard-shell-v128" in worker
|
||||
assert "stackchain-dashboard-shell-v130" in worker
|
||||
assert ".device-setup-panel" in css
|
||||
assert ".device-readiness-card" in css
|
||||
assert "overflow-x:hidden" in css
|
||||
|
||||
@@ -243,5 +243,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-v128" in worker
|
||||
assert "stackchain-dashboard-shell-v130" in worker
|
||||
assert "BASE + 'static/mobile-insights.js'" in worker
|
||||
@@ -358,7 +358,7 @@ 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-v128" in service_worker
|
||||
assert "stackchain-dashboard-shell-v130" in service_worker
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -549,5 +549,5 @@ async def test_offline_today_issue_queues_closure_before_completing_and_advancin
|
||||
admission = handler.index("await closeOfflineIssue(closing)")
|
||||
sheet_close = handler.index("closeIssueSheet()")
|
||||
assert admission < sheet_close
|
||||
assert "Issue closure queued for reconnect." in handler
|
||||
assert "Issue close queued." in handler
|
||||
assert "The issue remains in Today; retry." in handler
|
||||
@@ -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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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
|
||||
@@ -20,6 +20,7 @@ def _fixture(root: Path) -> None:
|
||||
(root / "requirements.txt").write_text("fastapi==1.0\n")
|
||||
(root / "README.md").write_text("# Stackchain\n")
|
||||
(root / "scripts" / "rotate_unfiled_drafts.py").write_text("print('rotate')\n")
|
||||
(root / "scripts" / "rotate_private_state.py").write_text("print('rotate private')\n")
|
||||
|
||||
|
||||
def _commit_fixture(source: Path) -> str:
|
||||
@@ -87,6 +88,7 @@ def test_release_bundle_is_reproducible_from_declared_commit(tmp_path):
|
||||
"README.md",
|
||||
"frontend/index.html",
|
||||
"requirements.txt",
|
||||
"scripts/rotate_private_state.py",
|
||||
"scripts/rotate_unfiled_drafts.py",
|
||||
"src/main.py",
|
||||
]
|
||||
@@ -98,6 +100,7 @@ def test_release_bundle_is_reproducible_from_declared_commit(tmp_path):
|
||||
"frontend/index.html",
|
||||
"release-manifest.json",
|
||||
"requirements.txt",
|
||||
"scripts/rotate_private_state.py",
|
||||
"scripts/rotate_unfiled_drafts.py",
|
||||
"src/main.py",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from src.saved_search_store import SavedSearchStore
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPT = ROOT / "scripts" / "rotate_private_state.py"
|
||||
|
||||
|
||||
def encoded(value: bytes) -> str:
|
||||
return base64.b64encode(value * 32).decode()
|
||||
|
||||
|
||||
def run_rotation(state: Path, *, tamper: bool = False):
|
||||
env = {
|
||||
**os.environ,
|
||||
"STACKCHAIN_STATE_DIR": str(state),
|
||||
"STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS": json.dumps(
|
||||
{"old": encoded(b"o"), "next": encoded(b"n")}
|
||||
),
|
||||
"STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID": "next",
|
||||
}
|
||||
if tamper:
|
||||
with sqlite3.connect(state / "saved-searches.sqlite3") as connection:
|
||||
connection.execute(
|
||||
"UPDATE saved_searches SET views = 'v1:tampered' WHERE login = 'timmy'"
|
||||
)
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SCRIPT)], env=env, text=True, capture_output=True
|
||||
)
|
||||
|
||||
|
||||
def test_rotation_command_rewraps_shared_store_rows_without_changing_metadata(tmp_path):
|
||||
state = tmp_path / "state"
|
||||
path = state / "saved-searches.sqlite3"
|
||||
store = SavedSearchStore(path, encryption_key=b"o" * 32)
|
||||
expected = store.replace(
|
||||
"timmy",
|
||||
0,
|
||||
[{"id": "mine", "name": "My private work", "query": "assignee:timmy"}],
|
||||
)
|
||||
|
||||
completed = run_rotation(state)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
report = json.loads(completed.stdout)
|
||||
assert report["saved-searches"] == {
|
||||
"current": 0,
|
||||
"failed": 0,
|
||||
"migrated": 1,
|
||||
"total": 1,
|
||||
}
|
||||
with sqlite3.connect(path) as connection:
|
||||
revision, payload = connection.execute(
|
||||
"SELECT revision, views FROM saved_searches WHERE login = 'timmy'"
|
||||
).fetchone()
|
||||
assert revision == expected["revision"]
|
||||
assert payload.startswith("v2:next:")
|
||||
assert SavedSearchStore(
|
||||
path, encryption_key=({"next": b"n" * 32}, "next")
|
||||
).get("timmy") == expected
|
||||
|
||||
|
||||
def test_rotation_command_fails_closed_and_never_prints_private_content(tmp_path):
|
||||
state = tmp_path / "state"
|
||||
secret = "private launch roadmap"
|
||||
store = SavedSearchStore(state / "saved-searches.sqlite3", encryption_key=b"o" * 32)
|
||||
store.replace("timmy", 0, [{"id": "secret", "name": secret, "query": "is:open"}])
|
||||
|
||||
completed = run_rotation(state, tamper=True)
|
||||
|
||||
assert completed.returncode == 1
|
||||
report = json.loads(completed.stdout)
|
||||
assert report["saved-searches"]["failed"] == 1
|
||||
assert secret not in completed.stdout
|
||||
assert "timmy" not in completed.stdout
|
||||
assert completed.stderr == ""
|
||||
@@ -177,23 +177,31 @@ async function dispatchPush(payload) {{
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_week_unplan_undo_rolls_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/week-plan.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
|
||||
|
||||
def test_private_today_action_mailbox_rolls_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
|
||||
|
||||
def test_per_day_week_conflict_ui_rolls_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/week-plan.js'" in source
|
||||
|
||||
|
||||
def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/my-work.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
@@ -202,7 +210,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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
|
||||
@@ -211,7 +219,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/issue-evidence-review.js'" in source
|
||||
assert "BASE + 'static/issue-attachment.js'" in source
|
||||
|
||||
@@ -219,14 +227,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/today-completion.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -234,7 +242,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/create-issue-sheet.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -242,7 +250,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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
|
||||
@@ -252,14 +260,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -268,21 +276,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" 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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
@@ -1252,7 +1260,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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/queue-today.js'" in source
|
||||
|
||||
|
||||
@@ -1331,6 +1339,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/week-calendar.js",
|
||||
"/dashboard/static/week-calendar-import.js",
|
||||
"/dashboard/static/week-plan.js",
|
||||
"/dashboard/static/today-week-reschedule.js",
|
||||
"/dashboard/static/search-week-plan.js",
|
||||
"/dashboard/static/today-sync.js",
|
||||
"/dashboard/static/today-rollover.js",
|
||||
|
||||
@@ -311,7 +311,7 @@ def test_mobile_settings_and_launch_route_wire_start_day_into_existing_promotion
|
||||
assert 'id="device-setup-start-day"' in html
|
||||
assert "startDayControl:qs('#push-start-day')" in dashboard
|
||||
assert "startDayHour:qs('#push-start-day-hour')" in dashboard
|
||||
assert "window.location.hash === '#/my-work/start-day'" in dashboard
|
||||
assert "window.location.hash !== '#/my-work/start-day'" in dashboard
|
||||
assert "weekFlow.promote(plan).finally(() =>" in dashboard
|
||||
assert "onRemotePlan: async plan =>" not in dashboard
|
||||
assert "openMobileStartDay()" in dashboard
|
||||
@@ -0,0 +1,119 @@
|
||||
import base64
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
from src.today_store import TodayStore
|
||||
from src.state_encryption import (
|
||||
PrivateStateCipher,
|
||||
PrivateStateEncryptionError,
|
||||
decode_private_state_encryption_keyring,
|
||||
private_state_encryption_config,
|
||||
)
|
||||
|
||||
|
||||
def encoded(byte: bytes) -> str:
|
||||
return base64.b64encode(byte * 32).decode()
|
||||
|
||||
|
||||
def test_keyring_writes_active_versioned_envelope_and_reads_it_current():
|
||||
keys, active = decode_private_state_encryption_keyring(
|
||||
json.dumps({"old": encoded(b"o"), "next": encoded(b"n")}), "next"
|
||||
)
|
||||
|
||||
cipher = PrivateStateCipher(keys, active_key_id=active, store="today")
|
||||
payload = cipher.seal({"ids": [7]}, binding="timmy")
|
||||
|
||||
assert payload.startswith("v2:next:")
|
||||
assert cipher.open(payload, binding="timmy") == ({"ids": [7]}, False)
|
||||
|
||||
|
||||
def test_keyring_reads_legacy_v1_and_marks_it_for_rewrap():
|
||||
legacy = PrivateStateCipher(b"o" * 32, store="today")
|
||||
payload = legacy.seal({"ids": [7]}, binding="timmy")
|
||||
rotating = PrivateStateCipher(
|
||||
{"old": b"o" * 32, "next": b"n" * 32},
|
||||
active_key_id="next",
|
||||
store="today",
|
||||
)
|
||||
|
||||
assert rotating.open(payload, binding="timmy") == ({"ids": [7]}, True)
|
||||
|
||||
|
||||
def test_keyring_reads_inactive_v2_and_marks_it_for_rewrap():
|
||||
old = PrivateStateCipher(
|
||||
{"old": b"o" * 32, "next": b"n" * 32},
|
||||
active_key_id="old",
|
||||
store="today",
|
||||
)
|
||||
payload = old.seal({"ids": [7]}, binding="timmy")
|
||||
rotating = PrivateStateCipher(
|
||||
{"old": b"o" * 32, "next": b"n" * 32},
|
||||
active_key_id="next",
|
||||
store="today",
|
||||
)
|
||||
|
||||
assert rotating.open(payload, binding="timmy") == ({"ids": [7]}, True)
|
||||
|
||||
|
||||
def test_keyring_fails_closed_for_unknown_key_id():
|
||||
cipher = PrivateStateCipher(
|
||||
{"next": b"n" * 32}, active_key_id="next", store="today"
|
||||
)
|
||||
|
||||
with pytest.raises(PrivateStateEncryptionError, match="could not be decrypted"):
|
||||
cipher.open("v2:retired:AAAA", binding="timmy")
|
||||
|
||||
|
||||
def test_keyring_configuration_is_bounded_and_requires_active_key():
|
||||
with pytest.raises(PrivateStateEncryptionError, match="active key"):
|
||||
decode_private_state_encryption_keyring(
|
||||
json.dumps({"old": encoded(b"o")}), "missing"
|
||||
)
|
||||
with pytest.raises(PrivateStateEncryptionError, match="at most 4"):
|
||||
decode_private_state_encryption_keyring(
|
||||
json.dumps({str(i): encoded(bytes([65 + i])) for i in range(5)}), "0"
|
||||
)
|
||||
|
||||
|
||||
def test_environment_prefers_keyring_and_keeps_single_key_rollout(monkeypatch):
|
||||
monkeypatch.setenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY", encoded(b"l"))
|
||||
monkeypatch.delenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS", raising=False)
|
||||
monkeypatch.delenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", raising=False)
|
||||
assert private_state_encryption_config() == b"l" * 32
|
||||
|
||||
monkeypatch.setenv(
|
||||
"STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS",
|
||||
json.dumps({"legacy": encoded(b"l"), "next": encoded(b"n")}),
|
||||
)
|
||||
monkeypatch.setenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", "next")
|
||||
keys, active = private_state_encryption_config()
|
||||
assert keys == {"legacy": b"l" * 32, "next": b"n" * 32}
|
||||
assert active == "next"
|
||||
|
||||
|
||||
def test_today_store_reads_and_lazily_rewraps_v2_state_during_rotation(tmp_path, monkeypatch):
|
||||
path = tmp_path / "today.sqlite3"
|
||||
legacy = TodayStore(path, encryption_key=b"l" * 32)
|
||||
legacy.apply("timmy", "seed", "add", "issue:stackchain/dashboard#1237")
|
||||
|
||||
monkeypatch.setenv(
|
||||
"STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS",
|
||||
json.dumps({"legacy": encoded(b"l"), "next": encoded(b"n")}),
|
||||
)
|
||||
monkeypatch.setenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", "next")
|
||||
rotating = TodayStore(path)
|
||||
|
||||
assert rotating.get("timmy")["ids"] == ["issue:stackchain/dashboard#1237"]
|
||||
assert rotating.apply(
|
||||
"timmy", "add-next", "add", "issue:stackchain/dashboard#1238"
|
||||
)["ids"] == [
|
||||
"issue:stackchain/dashboard#1237",
|
||||
"issue:stackchain/dashboard#1238",
|
||||
]
|
||||
with sqlite3.connect(path) as connection:
|
||||
payload = connection.execute(
|
||||
"SELECT ids FROM today_plans WHERE login = 'timmy'"
|
||||
).fetchone()[0]
|
||||
assert payload.startswith("v2:next:")
|
||||
@@ -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-v128';" in service_worker
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v130';" in service_worker
|
||||
assert "BASE + 'static/today-readiness.js'" in service_worker
|
||||
|
||||
|
||||
|
||||
@@ -343,7 +343,7 @@ listeners['stackchain:first-task-complete']();
|
||||
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-v128" in source
|
||||
assert "stackchain-dashboard-shell-v130" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
CONTROLLER = Path(__file__).parents[1] / "frontend" / "today-week-reschedule.js"
|
||||
INDEX = CONTROLLER.parent / "index.html"
|
||||
CSS = CONTROLLER.parent / "dashboard.css"
|
||||
DASHBOARD = CONTROLLER.parent / "dashboard.js"
|
||||
BUNDLE = CONTROLLER.parents[1] / "src" / "frontend_bundle.py"
|
||||
|
||||
|
||||
def run_controller(scenario: str) -> dict:
|
||||
harness = f"""
|
||||
const createReschedule = require({json.dumps(str(CONTROLLER))});
|
||||
(async()=>{{ {scenario} }})().catch(error=>{{console.error(error);process.exit(1);}});
|
||||
"""
|
||||
completed = subprocess.run(
|
||||
["node", "-e", harness], check=True, capture_output=True, text=True
|
||||
)
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_reschedule_controller_reviews_load_and_atomically_confirms_selected_day():
|
||||
result = run_controller("""
|
||||
const requests=[];
|
||||
const weekState={revision:7,offline_snapshot:false,days:[]};
|
||||
const review={days:[
|
||||
{plan_date:'2026-08-24',label:'Mon, Aug 24',ids:['one'],planned_minutes:30,capacity_minutes:60,overloaded:false},
|
||||
{plan_date:'2026-08-25',label:'Tue, Aug 25',ids:[],planned_minutes:0,capacity_minutes:90,overloaded:false}
|
||||
]};
|
||||
const week={load:async()=>weekState,review:()=>review,adopt:value=>{weekState.revision=value.revision;weekState.days=value.days;}};
|
||||
const api=async(url,options)=>{
|
||||
if(url==='api/v1/today')return {revision:4,ids:['active','other'],estimates:{active:45}};
|
||||
requests.push({url,body:JSON.parse(options.body)});return {
|
||||
today:{revision:5,ids:['other'],capacity_minutes:120,estimates:{other:20}},
|
||||
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:['active'],capacity_minutes:90,estimates:{active:45}}]}
|
||||
};};
|
||||
let adoptedToday=null;
|
||||
const controller=createReschedule({week,api,getToday:()=>({revision:4,ids:['active','other'],estimates:{active:45}}),
|
||||
adoptToday:value=>{adoptedToday=value;},operationId:()=> 'move-active'});
|
||||
const opened=await controller.open('active');
|
||||
const confirmed=await controller.confirm('2026-08-25',45);
|
||||
console.log(JSON.stringify({opened,confirmed,requests,adoptedToday,weekState}));
|
||||
""")
|
||||
|
||||
assert result["opened"]["estimate_minutes"] == 45
|
||||
assert result["opened"]["days"][0]["load"] == "30 / 60 min"
|
||||
assert result["opened"]["days"][1]["eligible"] is True
|
||||
assert result["requests"] == [{
|
||||
"url": "api/v1/week/reschedule",
|
||||
"body": {
|
||||
"operation_id": "move-active",
|
||||
"identity": "active",
|
||||
"estimate_minutes": 45,
|
||||
"plan_date": "2026-08-25",
|
||||
"today_revision": 4,
|
||||
"week_revision": 7,
|
||||
"allow_over_capacity": False,
|
||||
},
|
||||
}]
|
||||
assert result["adoptedToday"]["ids"] == ["other"]
|
||||
assert result["weekState"]["revision"] == 8
|
||||
assert result["confirmed"]["today"]["revision"] == 5
|
||||
|
||||
|
||||
def test_reschedule_controller_blocks_offline_full_and_overloaded_days_without_mutation():
|
||||
result = run_controller("""
|
||||
let calls=0;
|
||||
const days=[
|
||||
{plan_date:'2026-08-24',label:'Mon',ids:['1','2','3','4','5'],planned_minutes:50,capacity_minutes:60},
|
||||
{plan_date:'2026-08-25',label:'Tue',ids:['1'],planned_minutes:50,capacity_minutes:60}
|
||||
];
|
||||
const week={load:async()=>({revision:2,offline_snapshot:false}),review:()=>({days}),adopt:()=>{}};
|
||||
const api=async url=>{if(url==='api/v1/today')return {revision:3,ids:['active'],estimates:{active:30}};calls++;};
|
||||
const controller=createReschedule({week,api,getToday:()=>({revision:3,ids:['active'],estimates:{active:30}})});
|
||||
const opened=await controller.open('active');
|
||||
let fullError='',overError='';
|
||||
try{await controller.confirm('2026-08-24',30);}catch(error){fullError=error.message;}
|
||||
try{await controller.confirm('2026-08-25',30);}catch(error){overError=error.message;}
|
||||
const offline=createReschedule({week:{load:async()=>({revision:2,offline_snapshot:true,days:[]}),review:()=>({days})},api,getToday:()=>({revision:3,ids:['active'],estimates:{active:30}})});
|
||||
let offlineOpened=null;try{offlineOpened=await offline.open('active');}catch(_error){}
|
||||
console.log(JSON.stringify({opened,fullError,overError,offlineOpened,calls}));
|
||||
""")
|
||||
|
||||
assert result["opened"]["days"][0]["eligible"] is False
|
||||
assert result["fullError"] == "That Week Ahead day already has five items."
|
||||
assert result["overError"] == "That move exceeds the day's capacity. Confirm overload before rescheduling."
|
||||
assert result["offlineOpened"]["offline"] is True
|
||||
assert result["calls"] == 0
|
||||
|
||||
|
||||
def test_reschedule_controller_persists_offline_move_before_optimistic_adoption():
|
||||
result = run_controller("""
|
||||
const values=new Map();
|
||||
const events=[];
|
||||
const storage={
|
||||
getItem:key=>values.get(key)||null,
|
||||
setItem:(key,value)=>{events.push('persist');values.set(key,value);},
|
||||
removeItem:key=>values.delete(key),
|
||||
};
|
||||
const today={revision:4,ids:['active','other'],capacity_minutes:120,estimates:{active:45,other:20}};
|
||||
const weekState={revision:7,timezone:'UTC',offline_snapshot:true,days:[
|
||||
{plan_date:'2026-08-25',ids:[],capacity_minutes:90,estimates:{}}
|
||||
]};
|
||||
const week={load:async()=>weekState,review:()=>({days:[
|
||||
{plan_date:'2026-08-25',label:'Tue',ids:[],planned_minutes:0,capacity_minutes:90,estimates:{}}
|
||||
]}),adopt:value=>events.push(['week',value])};
|
||||
const api=async()=>{const error=new Error('offline');error.status=0;throw error;};
|
||||
const controller=createReschedule({week,api,getToday:()=>today,adoptToday:value=>events.push(['today',value]),
|
||||
storage,getLogin:()=> 'Timmy',operationId:()=> 'move-active',now:()=>123});
|
||||
const opened=await controller.open('active');
|
||||
const confirmed=await controller.confirm('2026-08-25',45);
|
||||
console.log(JSON.stringify({opened,confirmed,events,keys:[...values.keys()],record:JSON.parse([...values.values()][0])}));
|
||||
""")
|
||||
|
||||
assert result["opened"]["offline"] is True
|
||||
assert result["confirmed"]["sync_pending"] is True
|
||||
assert result["events"][0] == "persist"
|
||||
assert result["events"][1][0] == "today"
|
||||
assert result["events"][1][1]["ids"] == ["other"]
|
||||
assert result["events"][2][0] == "week"
|
||||
assert result["events"][2][1]["days"][0]["ids"] == ["active"]
|
||||
assert result["keys"] == ["stackchain.today-week-reschedule.v1.timmy"]
|
||||
assert result["record"]["version"] == 2
|
||||
assert result["record"]["records"][0]["body"]["operation_id"] == "move-active"
|
||||
assert result["record"]["records"][0]["queued_at"] == 123
|
||||
|
||||
|
||||
def test_reschedule_controller_restores_and_delivers_same_operation_after_reload():
|
||||
result = run_controller("""
|
||||
const key='stackchain.today-week-reschedule.v1.timmy';
|
||||
const record={queued_at:123,body:{operation_id:'move-active',identity:'active',estimate_minutes:45,
|
||||
plan_date:'2026-08-25',today_revision:4,week_revision:7,allow_over_capacity:false},
|
||||
today:{revision:4,ids:['other'],estimates:{other:20}},
|
||||
week:{revision:7,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:['active'],capacity_minutes:90,estimates:{active:45}}]}};
|
||||
const values=new Map([[key,JSON.stringify(record)]]);const adopted=[];const requests=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const api=async(url,options)=>{requests.push({url,body:JSON.parse(options.body)});return {
|
||||
today:{revision:5,ids:['other'],estimates:{other:20}},
|
||||
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:['active'],capacity_minutes:90,estimates:{active:45}}]}};};
|
||||
const controller=createReschedule({week:{adopt:value=>adopted.push(['week',value])},api,
|
||||
getToday:()=>null,adoptToday:value=>adopted.push(['today',value]),storage,getLogin:()=> 'timmy'});
|
||||
const restored=controller.resume();
|
||||
const delivered=await controller.flush();
|
||||
console.log(JSON.stringify({restored,delivered,adopted,requests,remaining:values.size}));
|
||||
""")
|
||||
|
||||
assert result["restored"]["sync_pending"] is True
|
||||
assert result["adopted"][0][0] == "today"
|
||||
assert result["adopted"][1][0] == "week"
|
||||
assert result["requests"][0]["body"]["operation_id"] == "move-active"
|
||||
assert result["delivered"]["sync_pending"] is False
|
||||
assert result["remaining"] == 0
|
||||
|
||||
|
||||
def test_reschedule_controller_keeps_admitted_operation_when_connection_drops_on_confirm():
|
||||
result = run_controller("""
|
||||
const values=new Map();const events=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>{events.push('persist');values.set(key,value);},removeItem:key=>values.delete(key)};
|
||||
const weekState={revision:7,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:[],capacity_minutes:90,estimates:{}}]};
|
||||
const week={load:async()=>weekState,review:()=>({days:[{...weekState.days[0],label:'Tue',planned_minutes:0}]}),
|
||||
adopt:value=>events.push(['week',value])};
|
||||
let calls=0;const api=async url=>{if(url==='api/v1/today')return {revision:4,ids:['active'],estimates:{active:45}};
|
||||
calls++;const error=new Error('connection dropped');error.status=0;throw error;};
|
||||
const controller=createReschedule({week,api,getToday:()=>null,adoptToday:value=>events.push(['today',value]),
|
||||
storage,getLogin:()=> 'timmy',operationId:()=> 'stable-operation'});
|
||||
await controller.open('active');
|
||||
const result=await controller.confirm('2026-08-25',45);
|
||||
console.log(JSON.stringify({result,events,calls,pending:controller.pending()}));
|
||||
""")
|
||||
|
||||
assert result["result"]["sync_pending"] is True
|
||||
assert result["events"][0] == "persist"
|
||||
assert result["calls"] == 1
|
||||
assert result["pending"]["body"]["operation_id"] == "stable-operation"
|
||||
|
||||
|
||||
def test_reschedule_controller_queues_two_offline_moves_without_replacing_the_first():
|
||||
result = run_controller("""
|
||||
const values=new Map();
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
let today={revision:4,ids:['active','other'],capacity_minutes:120,estimates:{active:45,other:20}};
|
||||
let weekState={revision:7,timezone:'UTC',offline_snapshot:true,days:[
|
||||
{plan_date:'2026-08-25',ids:[],capacity_minutes:90,estimates:{}}
|
||||
]};
|
||||
const confirmedWeek=JSON.parse(JSON.stringify(weekState));let loads=0;
|
||||
const week={load:async()=>{loads++;weekState=JSON.parse(JSON.stringify(confirmedWeek));return weekState;},state:()=>weekState,review:()=>({days:[
|
||||
{...weekState.days[0],label:'Tue',planned_minutes:Object.values(weekState.days[0].estimates).reduce((a,b)=>a+b,0)}
|
||||
]}),adopt:value=>{weekState={...value,offline_snapshot:true};}};
|
||||
const api=async()=>{const error=new Error('offline');error.status=0;throw error;};
|
||||
let n=0;
|
||||
const controller=createReschedule({week,api,getToday:()=>today,adoptToday:value=>{today=value;},
|
||||
storage,getLogin:()=> 'timmy',operationId:()=> `move-${++n}`,now:()=>100+n});
|
||||
await controller.open('active');
|
||||
await controller.confirm('2026-08-25',45);
|
||||
await controller.open('other');
|
||||
const confirmed=await controller.confirm('2026-08-25',20);
|
||||
const stored=JSON.parse([...values.values()][0]);
|
||||
console.log(JSON.stringify({confirmed,stored,today,weekState,loads}));
|
||||
""")
|
||||
|
||||
assert [entry["body"]["operation_id"] for entry in result["stored"]["records"]] == [
|
||||
"move-1",
|
||||
"move-2",
|
||||
]
|
||||
assert result["confirmed"]["pending_count"] == 2
|
||||
assert result["today"]["ids"] == []
|
||||
assert result["weekState"]["days"][0]["ids"] == ["active", "other"]
|
||||
assert result["loads"] == 1
|
||||
|
||||
|
||||
def test_reschedule_controller_drains_fifo_and_rebases_each_next_move():
|
||||
result = run_controller("""
|
||||
const key='stackchain.today-week-reschedule.v1.timmy';
|
||||
const make=(id,identity,today,week)=>({queued_at:1,body:{operation_id:id,identity,estimate_minutes:20,
|
||||
plan_date:'2026-08-25',today_revision:today,week_revision:week,allow_over_capacity:false},
|
||||
today:{revision:today,ids:[]},week:{revision:week,days:[]}});
|
||||
const values=new Map([[key,JSON.stringify({version:2,records:[make('move-1','one',4,7),make('move-2','two',4,7)]})]]);
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const requests=[];let active=0,maxActive=0;
|
||||
const api=async(_url,options)=>{active++;maxActive=Math.max(maxActive,active);
|
||||
const body=JSON.parse(options.body);requests.push(body);await new Promise(resolve=>setTimeout(resolve,1));active--;
|
||||
const step=requests.length;return {today:{revision:4+step,ids:[]},week:{revision:7+step,days:[]}};};
|
||||
const controller=createReschedule({week:{adopt:()=>{}},api,adoptToday:()=>{},storage,getLogin:()=> 'timmy'});
|
||||
const delivered=await controller.flush();
|
||||
console.log(JSON.stringify({requests,maxActive,delivered,remaining:values.size}));
|
||||
""")
|
||||
|
||||
assert [request["operation_id"] for request in result["requests"]] == ["move-1", "move-2"]
|
||||
assert result["requests"][1]["today_revision"] == 5
|
||||
assert result["requests"][1]["week_revision"] == 8
|
||||
assert result["maxActive"] == 1
|
||||
assert result["delivered"]["pending_count"] == 0
|
||||
assert result["remaining"] == 0
|
||||
|
||||
|
||||
def test_reschedule_controller_restores_server_truth_and_keeps_intent_on_conflict():
|
||||
result = run_controller("""
|
||||
const key='stackchain.today-week-reschedule.v1.timmy';
|
||||
const record={queued_at:123,body:{operation_id:'move-active'},today:{revision:4,ids:[]},week:{revision:7,days:[]}};
|
||||
const values=new Map([[key,JSON.stringify(record)]]);const adopted=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const api=async url=>{
|
||||
if(url==='api/v1/week/reschedule'){const error=new Error('conflict');error.status=409;throw error;}
|
||||
if(url==='api/v1/today')return {revision:9,ids:['active'],estimates:{active:45}};
|
||||
return {revision:12,timezone:'UTC',days:[]};
|
||||
};
|
||||
const controller=createReschedule({week:{adopt:value=>adopted.push(['week',value])},api,
|
||||
adoptToday:value=>adopted.push(['today',value]),storage,getLogin:()=> 'timmy'});
|
||||
let message='';try{await controller.flush();}catch(error){message=error.message;}
|
||||
console.log(JSON.stringify({message,adopted,pending:controller.pending(),remaining:values.size}));
|
||||
""")
|
||||
|
||||
assert result["message"] == "Plans changed on another device. Review and retry this saved move."
|
||||
assert result["adopted"][0][1]["revision"] == 9
|
||||
assert result["adopted"][1][1]["revision"] == 12
|
||||
assert result["pending"]["body"]["operation_id"] == "move-active"
|
||||
assert result["remaining"] == 1
|
||||
|
||||
|
||||
def test_mobile_active_today_reschedule_dialog_is_touch_safe_and_wired_into_release_bundle():
|
||||
index = INDEX.read_text()
|
||||
css = CSS.read_text()
|
||||
dashboard = DASHBOARD.read_text()
|
||||
bundle = BUNDLE.read_text()
|
||||
|
||||
assert 'data-work-session-reschedule-week' in index
|
||||
assert 'id="today-week-reschedule"' in index
|
||||
assert 'id="today-week-reschedule-days"' in index
|
||||
assert 'id="today-week-reschedule-estimate"' in index
|
||||
assert 'id="confirm-today-week-reschedule"' in index
|
||||
assert 'id="cancel-today-week-reschedule"' in index
|
||||
assert '.today-week-reschedule-days button { min-height:44px;' in css
|
||||
assert '.today-week-reschedule-panel { width:min(100%,560px);' in css
|
||||
assert 'x:currentTodayProgressTarget' in dashboard
|
||||
assert 'restoreWhenOwned()' in CONTROLLER.read_text()
|
||||
assert "runTodayTransition('next')" in dashboard
|
||||
assert 'reschedule:()=>({storage,getLogin})' in (CONTROLLER.parent / "week-plan.js").read_text()
|
||||
assert "addEventListener('online', flushPending)" in CONTROLLER.read_text()
|
||||
assert '"static/today-week-reschedule.js"' in bundle
|
||||
@@ -189,6 +189,95 @@ def test_week_early_start_moves_a_future_day_to_empty_today_exactly_once(tmp_pat
|
||||
assert store.get_week("timmy")["days"] == [sample_days()[1]]
|
||||
|
||||
|
||||
def test_pull_week_item_atomically_appends_to_active_today_and_replays_exactly_once(tmp_path):
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"i" * 32)
|
||||
active_id = "issue:stackchain/dashboard:1:"
|
||||
pulled_id = "issue:secret/repo:3:"
|
||||
today = store.apply("timmy", "seed-active", "add", active_id)
|
||||
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
|
||||
|
||||
result = store.pull_week_item(
|
||||
"timmy", operation_id="pull-secret-3", identity=pulled_id,
|
||||
today_revision=today["revision"], week_revision=week["revision"],
|
||||
)
|
||||
replay = store.pull_week_item(
|
||||
"timmy", operation_id="pull-secret-3", identity=pulled_id,
|
||||
today_revision=today["revision"], week_revision=week["revision"],
|
||||
)
|
||||
|
||||
assert replay == result
|
||||
assert result["today"]["ids"] == [active_id, pulled_id]
|
||||
assert result["today"]["estimates"] == {pulled_id: 60}
|
||||
assert result["week"]["days"][0]["ids"] == ["issue:secret/repo:2:"]
|
||||
assert result["week"]["days"][0]["estimates"] == {"issue:secret/repo:2:": 45}
|
||||
assert result["week"]["days"][1] == sample_days()[1]
|
||||
assert store.get("timmy") == result["today"]
|
||||
assert store.get_week("timmy") == result["week"]
|
||||
|
||||
|
||||
def test_pull_week_item_rejects_full_or_changed_today_without_partial_write(tmp_path):
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"f" * 32)
|
||||
today = store.get("timmy")
|
||||
for index in range(5):
|
||||
today = store.apply("timmy", f"seed-{index}", "add", f"issue:r:{index + 1}:")
|
||||
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
|
||||
|
||||
with pytest.raises(main.TodayPlanFull):
|
||||
store.pull_week_item(
|
||||
"timmy", operation_id="full", identity="issue:secret/repo:3:",
|
||||
today_revision=today["revision"], week_revision=week["revision"],
|
||||
)
|
||||
with pytest.raises(TodayPromotionConflict):
|
||||
store.pull_week_item(
|
||||
"timmy", operation_id="stale", identity="issue:secret/repo:3:",
|
||||
today_revision=today["revision"] - 1, week_revision=week["revision"],
|
||||
)
|
||||
|
||||
assert store.get("timmy") == today
|
||||
assert store.get_week("timmy") == week
|
||||
|
||||
|
||||
def test_pull_week_item_requires_explicit_today_capacity_overload_confirmation(tmp_path):
|
||||
store = TodayStore(
|
||||
tmp_path / "today.sqlite3", encryption_key=b"c" * 32,
|
||||
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
|
||||
)
|
||||
active_id = "issue:stackchain/dashboard:1:"
|
||||
pulled_id = "issue:stackchain/dashboard:2:"
|
||||
seed = store.replace_week(
|
||||
"timmy", base_revision=0, timezone="UTC", days=[{
|
||||
"plan_date": "2026-08-22", "ids": [active_id],
|
||||
"capacity_minutes": 60, "estimates": {active_id: 45},
|
||||
}],
|
||||
)
|
||||
today = store.promote_week(
|
||||
"timmy", promotion_id="seed-today", week_revision=seed["revision"],
|
||||
plan_date="2026-08-22", today_revision=0,
|
||||
)
|
||||
week = store.replace_week(
|
||||
"timmy", base_revision=2, timezone="UTC", days=[{
|
||||
"plan_date": "2026-08-23", "ids": [pulled_id],
|
||||
"capacity_minutes": 60, "estimates": {pulled_id: 30},
|
||||
}],
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="explicit overload confirmation"):
|
||||
store.pull_week_item(
|
||||
"timmy", operation_id="unconfirmed", identity=pulled_id,
|
||||
today_revision=today["revision"], week_revision=week["revision"],
|
||||
)
|
||||
assert store.get("timmy") == today
|
||||
assert store.get_week("timmy") == week
|
||||
|
||||
moved = store.pull_week_item(
|
||||
"timmy", operation_id="confirmed", identity=pulled_id,
|
||||
today_revision=today["revision"], week_revision=week["revision"],
|
||||
allow_over_capacity=True,
|
||||
)
|
||||
assert moved["today"]["capacity_minutes"] == 60
|
||||
assert moved["today"]["estimates"] == {active_id: 45, pulled_id: 30}
|
||||
|
||||
|
||||
def test_normal_week_promotion_still_rejects_a_future_day_without_writes(tmp_path):
|
||||
store = TodayStore(
|
||||
tmp_path / "today.sqlite3",
|
||||
@@ -327,6 +416,26 @@ async def test_week_early_start_api_promotes_a_future_day(monkeypatch, tmp_path)
|
||||
assert store.get_week("timmy")["days"] == [sample_days()[1]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pull_week_item_api_returns_both_atomic_plans(monkeypatch, tmp_path):
|
||||
async def user():
|
||||
return {"login": "timmy"}
|
||||
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"u" * 32)
|
||||
today = store.apply("timmy", "seed", "add", "issue:r:active:")
|
||||
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "_today_store", lambda: store)
|
||||
|
||||
result = await main.pull_week_item_into_today(main.WeekItemPull(
|
||||
operation_id="pull-api", identity="issue:secret/repo:3:",
|
||||
week_revision=week["revision"], today_revision=today["revision"],
|
||||
))
|
||||
|
||||
assert result["today"]["ids"] == ["issue:r:active:", "issue:secret/repo:3:"]
|
||||
assert result["week"]["days"][0]["ids"] == ["issue:secret/repo:2:"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_week_reconciliation_api_returns_atomic_today_and_remaining_week(monkeypatch, tmp_path):
|
||||
async def user():
|
||||
@@ -386,3 +495,144 @@ async def test_week_api_round_trip_and_conflict_contract(monkeypatch, tmp_path):
|
||||
await main.replace_week_plan(payload)
|
||||
assert raised.value.status_code == 409
|
||||
assert raised.value.detail == {"code": "week_changed", "snapshot": saved}
|
||||
|
||||
|
||||
def test_reschedule_today_item_atomically_moves_it_into_selected_week_day(tmp_path):
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"s" * 32)
|
||||
active_id = "issue:stackchain/dashboard:1228:"
|
||||
other_id = "issue:stackchain/dashboard:1229:"
|
||||
today = store.apply("timmy", "add-active", "add", active_id)
|
||||
today = store.apply("timmy", "add-other", "add", other_id)
|
||||
week = store.replace_week(
|
||||
"timmy",
|
||||
base_revision=0,
|
||||
timezone="UTC",
|
||||
days=[{
|
||||
"plan_date": "2026-08-24",
|
||||
"ids": [active_id],
|
||||
"capacity_minutes": 120,
|
||||
"estimates": {active_id: 30},
|
||||
}, {
|
||||
"plan_date": "2026-08-25",
|
||||
"ids": [],
|
||||
"capacity_minutes": 90,
|
||||
"estimates": {},
|
||||
}],
|
||||
)
|
||||
|
||||
result = store.reschedule_today_to_week(
|
||||
"timmy",
|
||||
operation_id="reschedule-active-2026-08-25",
|
||||
identity=active_id,
|
||||
estimate_minutes=45,
|
||||
plan_date="2026-08-25",
|
||||
today_revision=today["revision"],
|
||||
week_revision=week["revision"],
|
||||
)
|
||||
|
||||
assert result["today"]["ids"] == [other_id]
|
||||
assert result["week"]["days"] == [{
|
||||
"plan_date": "2026-08-24", "ids": [], "capacity_minutes": 120, "estimates": {},
|
||||
}, {
|
||||
"plan_date": "2026-08-25", "ids": [active_id], "capacity_minutes": 90,
|
||||
"estimates": {active_id: 45},
|
||||
}]
|
||||
assert store.get("timmy") == result["today"]
|
||||
assert store.get_week("timmy") == result["week"]
|
||||
|
||||
|
||||
def test_reschedule_today_item_is_idempotent_and_rejects_stale_plans_without_partial_write(tmp_path):
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"i" * 32)
|
||||
identity = "issue:stackchain/dashboard:1228:"
|
||||
today = store.apply("timmy", "add-active", "add", identity)
|
||||
week = store.replace_week(
|
||||
"timmy", base_revision=0, timezone="UTC",
|
||||
days=[{
|
||||
"plan_date": "2026-08-25", "ids": [],
|
||||
"capacity_minutes": 60, "estimates": {},
|
||||
}],
|
||||
)
|
||||
arguments = {
|
||||
"operation_id": "same-operation", "identity": identity,
|
||||
"estimate_minutes": 30, "plan_date": "2026-08-25",
|
||||
"today_revision": today["revision"], "week_revision": week["revision"],
|
||||
}
|
||||
|
||||
moved = store.reschedule_today_to_week("timmy", **arguments)
|
||||
assert store.reschedule_today_to_week("timmy", **arguments) == moved
|
||||
|
||||
another = store.apply("timmy", "add-another", "add", "issue:stackchain/dashboard:1230:")
|
||||
with pytest.raises(TodayPromotionConflict) as conflict:
|
||||
store.reschedule_today_to_week(
|
||||
"timmy", **{**arguments, "operation_id": "stale-operation", "identity": another["ids"][-1]}
|
||||
)
|
||||
assert conflict.value.today == another
|
||||
assert store.get_week("timmy") == moved["week"]
|
||||
|
||||
|
||||
def test_reschedule_today_item_requires_explicit_capacity_overload_confirmation(tmp_path):
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"o" * 32)
|
||||
identity = "issue:stackchain/dashboard:1228:"
|
||||
today = store.apply("timmy", "add-active", "add", identity)
|
||||
week = store.replace_week(
|
||||
"timmy", base_revision=0, timezone="UTC",
|
||||
days=[{
|
||||
"plan_date": "2026-08-25", "ids": ["issue:stackchain/dashboard:1:"],
|
||||
"capacity_minutes": 60, "estimates": {"issue:stackchain/dashboard:1:": 45},
|
||||
}],
|
||||
)
|
||||
arguments = {
|
||||
"identity": identity, "estimate_minutes": 30, "plan_date": "2026-08-25",
|
||||
"today_revision": today["revision"], "week_revision": week["revision"],
|
||||
}
|
||||
|
||||
with pytest.raises(ValueError, match="explicit overload confirmation"):
|
||||
store.reschedule_today_to_week(
|
||||
"timmy", operation_id="unconfirmed", allow_over_capacity=False, **arguments
|
||||
)
|
||||
assert store.get("timmy") == today
|
||||
assert store.get_week("timmy") == week
|
||||
|
||||
moved = store.reschedule_today_to_week(
|
||||
"timmy", operation_id="confirmed", allow_over_capacity=True, **arguments
|
||||
)
|
||||
assert moved["week"]["days"][0]["ids"][-1] == identity
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_week_reschedule_api_returns_atomic_snapshots_and_conflict_recovery(monkeypatch, tmp_path):
|
||||
async def user():
|
||||
return {"login": "timmy"}
|
||||
|
||||
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"a" * 32)
|
||||
identity = "issue:stackchain/dashboard:1228:"
|
||||
today = store.apply("timmy", "add-active", "add", identity)
|
||||
week = store.replace_week(
|
||||
"timmy", base_revision=0, timezone="UTC",
|
||||
days=[{
|
||||
"plan_date": "2026-08-25", "ids": [],
|
||||
"capacity_minutes": 60, "estimates": {},
|
||||
}],
|
||||
)
|
||||
monkeypatch.setattr(main, "current_user", user)
|
||||
monkeypatch.setattr(main, "_today_store", lambda: store)
|
||||
payload = main.WeekReschedule(
|
||||
operation_id="move-active", identity=identity, estimate_minutes=30,
|
||||
plan_date="2026-08-25", today_revision=today["revision"],
|
||||
week_revision=week["revision"],
|
||||
)
|
||||
|
||||
moved = await main.reschedule_today_to_week(payload)
|
||||
assert moved["today"]["ids"] == []
|
||||
assert moved["week"]["days"][0]["ids"] == [identity]
|
||||
|
||||
stale = main.WeekReschedule(
|
||||
operation_id="stale", identity="issue:stackchain/dashboard:1229:", estimate_minutes=30,
|
||||
plan_date="2026-08-25", today_revision=today["revision"], week_revision=week["revision"],
|
||||
)
|
||||
with pytest.raises(main.HTTPException) as raised:
|
||||
await main.reschedule_today_to_week(stale)
|
||||
assert raised.value.status_code == 409
|
||||
assert raised.value.detail["code"] == "today_changed"
|
||||
assert raised.value.detail["today"] == moved["today"]
|
||||
assert raised.value.detail["week"] == moved["week"]
|
||||
@@ -2,14 +2,18 @@ import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
FRONTEND = Path(__file__).parents[1] / "frontend"
|
||||
CONTROLLER = FRONTEND / "week-plan.js"
|
||||
COORDINATOR = FRONTEND / "outbox-coordinator.js"
|
||||
|
||||
|
||||
def run_controller(scenario: str) -> dict:
|
||||
harness = f"""
|
||||
const createWeekPlan = require({json.dumps(str(CONTROLLER))});
|
||||
const createOutboxCoordinator = require({json.dumps(str(COORDINATOR))});
|
||||
(async()=>{{ {scenario} }})().catch(error=>{{console.error(error);process.exit(1);}});
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", harness], check=True, capture_output=True, text=True)
|
||||
@@ -300,6 +304,272 @@ console.log(JSON.stringify({before,refused,moved,added,state:week.state(),pendin
|
||||
assert result["pending"]["days"] == result["state"]["days"]
|
||||
|
||||
|
||||
def test_week_controller_pulls_one_item_into_today_and_adopts_returned_week():
|
||||
result = run_controller("""
|
||||
const requests=[];
|
||||
const week=createWeekPlan({fetchJson:async(url,options={})=>{
|
||||
const body=JSON.parse(options.body);requests.push({url,body});
|
||||
return {today:{revision:5,ids:['active',body.identity],capacity_minutes:120,estimates:{[body.identity]:45}},
|
||||
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['sibling'],capacity_minutes:90,estimates:{sibling:30}}]}};
|
||||
},localDate:()=> '2026-08-20',timeZone:()=> 'UTC'});
|
||||
week.adopt({revision:7,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['pull','sibling'],capacity_minutes:90,estimates:{pull:45,sibling:30}}]});
|
||||
const pulled=await week.pullItem('pull',{revision:4,ids:['active']},'stable-pull',true);
|
||||
console.log(JSON.stringify({pulled,requests,state:week.state()}));
|
||||
""")
|
||||
|
||||
assert result["requests"] == [{
|
||||
"url": "api/v1/week/pull-item",
|
||||
"body": {
|
||||
"operation_id": "stable-pull", "identity": "pull",
|
||||
"today_revision": 4, "week_revision": 7,
|
||||
"allow_over_capacity": True,
|
||||
},
|
||||
}]
|
||||
assert result["pulled"]["today"]["ids"] == ["active", "pull"]
|
||||
assert result["state"]["revision"] == 8
|
||||
assert result["state"]["days"][0]["ids"] == ["sibling"]
|
||||
|
||||
|
||||
def test_week_controller_replays_a_lost_pull_receipt_with_the_same_operation_after_reload():
|
||||
result = run_controller("""
|
||||
const values=new Map(),requests=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
let loseResponse=true;
|
||||
const fetchJson=async(url,options={})=>{
|
||||
const body=JSON.parse(options.body);requests.push(body);
|
||||
if(loseResponse){loseResponse=false;throw new Error('connection lost');}
|
||||
return {today:{revision:5,ids:['active',body.identity],capacity_minutes:120,estimates:{active:30,[body.identity]:45}},
|
||||
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['sibling'],capacity_minutes:90,estimates:{sibling:30}}]}};
|
||||
};
|
||||
const options={storage,getLogin:()=> 'Timmy',fetchJson,localDate:()=> '2026-08-20',timeZone:()=> 'UTC'};
|
||||
const first=createWeekPlan(options);
|
||||
first.adopt({revision:7,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['pull','sibling'],capacity_minutes:90,estimates:{pull:45,sibling:30}}]});
|
||||
const pending=await first.pullItem('pull',{revision:4,ids:['active'],capacity_minutes:120,estimates:{active:30}},'stable-pull');
|
||||
const restored=createWeekPlan(options),resume=restored.resumePull();
|
||||
const confirmed=await restored.flushPull();
|
||||
console.log(JSON.stringify({pending,resume,confirmed,requests,keys:[...values.keys()],state:restored.state()}));
|
||||
""")
|
||||
|
||||
assert result["pending"]["sync_pending"] is True
|
||||
assert result["pending"]["today"]["ids"] == ["active", "pull"]
|
||||
assert result["pending"]["week"]["days"][0]["ids"] == ["sibling"]
|
||||
assert result["resume"]["sync_pending"] is True
|
||||
assert result["resume"]["today"] == result["pending"]["today"]
|
||||
assert [request["operation_id"] for request in result["requests"]] == ["stable-pull", "stable-pull"]
|
||||
assert result["confirmed"]["sync_pending"] is False
|
||||
assert result["confirmed"]["today"]["revision"] == 5
|
||||
assert result["keys"] == ["stackchain.week-confirmed.v1.timmy"]
|
||||
assert result["state"]["revision"] == 8
|
||||
|
||||
|
||||
def test_week_controller_queues_two_offline_pulls_and_replays_them_fifo_after_reload():
|
||||
result = run_controller("""
|
||||
const values=new Map(),delivered=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
let offline=true;
|
||||
let serverToday={revision:4,ids:['active'],capacity_minutes:180,estimates:{active:30}};
|
||||
let serverWeek={revision:7,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['first','second','later'],capacity_minutes:150,estimates:{first:35,second:40,later:45}}]};
|
||||
const fetchJson=async(url,options={})=>{
|
||||
if(offline)throw new Error('connection lost');
|
||||
const body=JSON.parse(options.body);delivered.push(body);
|
||||
if(body.today_revision!==serverToday.revision||body.week_revision!==serverWeek.revision){const error=new Error('changed');error.status=409;throw error;}
|
||||
serverToday={...serverToday,revision:serverToday.revision+1,ids:[...serverToday.ids,body.identity],
|
||||
estimates:{...serverToday.estimates,[body.identity]:serverWeek.days[0].estimates[body.identity]}};
|
||||
serverWeek={...serverWeek,revision:serverWeek.revision+1,days:serverWeek.days.map(day=>({...day,
|
||||
ids:day.ids.filter(id=>id!==body.identity),estimates:Object.fromEntries(Object.entries(day.estimates).filter(([id])=>id!==body.identity))}))};
|
||||
return {today:serverToday,week:serverWeek};
|
||||
};
|
||||
const options={storage,getLogin:()=> 'Timmy',fetchJson,localDate:()=> '2026-08-20',timeZone:()=> 'UTC'};
|
||||
const first=createWeekPlan(options);first.adopt(serverWeek);
|
||||
const queuedFirst=await first.pullItem('first',serverToday,'pull-first');
|
||||
const queuedSecond=await first.pullItem('second',queuedFirst.today,'pull-second');
|
||||
const restored=createWeekPlan(options),resumed=restored.resumePull();
|
||||
offline=false;
|
||||
const confirmed=await restored.flushPull();
|
||||
console.log(JSON.stringify({queuedFirst,queuedSecond,resumed,confirmed,delivered,keys:[...values.keys()],state:restored.state()}));
|
||||
""")
|
||||
|
||||
assert result["queuedFirst"]["today"]["ids"] == ["active", "first"]
|
||||
assert result["queuedSecond"]["today"]["ids"] == ["active", "first", "second"]
|
||||
assert result["resumed"]["today"]["ids"] == ["active", "first", "second"]
|
||||
assert [request["operation_id"] for request in result["delivered"]] == ["pull-first", "pull-second"]
|
||||
assert result["delivered"][1]["today_revision"] == 5
|
||||
assert result["delivered"][1]["week_revision"] == 8
|
||||
assert result["confirmed"]["today"]["ids"] == ["active", "first", "second"]
|
||||
assert result["confirmed"]["week"]["days"][0]["ids"] == ["later"]
|
||||
assert result["confirmed"]["sync_pending"] is False
|
||||
assert result["keys"] == ["stackchain.week-confirmed.v1.timmy"]
|
||||
assert result["state"]["revision"] == 9
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"coordinator_setup",
|
||||
[
|
||||
"""const locks={request:async(name,_options,work)=>{
|
||||
if(held.has(name))return work(null);
|
||||
held.add(name);try{return await work({name});}finally{held.delete(name);}
|
||||
}};
|
||||
const coordinatorA=createOutboxCoordinator({storage,locks,channelFactory:null,tabId:'a'});
|
||||
const coordinatorB=createOutboxCoordinator({storage,locks,channelFactory:null,tabId:'b'});""",
|
||||
"""const coordinatorA=createOutboxCoordinator({storage,locks:null,channelFactory:null,tabId:'a',now:()=>100});
|
||||
const coordinatorB=createOutboxCoordinator({storage,locks:null,channelFactory:null,tabId:'b',now:()=>100});""",
|
||||
],
|
||||
ids=["navigator-lock", "storage-lease"],
|
||||
)
|
||||
def test_week_controller_allows_only_one_tab_to_replay_the_shared_pull_queue(coordinator_setup):
|
||||
result = run_controller("""
|
||||
const values=new Map(),held=new Set();
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
COORDINATOR_SETUP
|
||||
let offline=true,posts=0,release;
|
||||
const gate=new Promise(resolve=>release=resolve);
|
||||
const fetchJson=async(_url,options={})=>{
|
||||
if(offline)throw new Error('connection lost');
|
||||
posts+=1;await gate;
|
||||
const body=JSON.parse(options.body);
|
||||
return {today:{revision:5,ids:['active',body.identity],capacity_minutes:180,estimates:{active:30,[body.identity]:35}},
|
||||
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:[],capacity_minutes:150,estimates:{}}]}};
|
||||
};
|
||||
const options={storage,getLogin:()=> 'timmy',fetchJson,localDate:()=> '2026-08-20',timeZone:()=> 'UTC'};
|
||||
const source=createWeekPlan({...options,coordinator:coordinatorA});source.adopt({revision:7,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['first'],capacity_minutes:150,estimates:{first:35}}]});
|
||||
await source.pullItem('first',{revision:4,ids:['active'],capacity_minutes:180,estimates:{active:30}},'pull-first');
|
||||
offline=false;
|
||||
const first=createWeekPlan({...options,coordinator:coordinatorA}),second=createWeekPlan({...options,coordinator:coordinatorB});
|
||||
const firstFlush=first.flushPull();
|
||||
await Promise.resolve();
|
||||
setImmediate(release);
|
||||
const skipped=await second.flushPull();
|
||||
release();
|
||||
const confirmed=await firstFlush;
|
||||
console.log(JSON.stringify({posts,skipped,confirmed,pending:first.pendingPull()}));
|
||||
""".replace("COORDINATOR_SETUP", coordinator_setup))
|
||||
|
||||
assert result["posts"] == 1
|
||||
assert result["skipped"]["lease_skipped"] is True
|
||||
assert result["confirmed"]["sync_pending"] is False
|
||||
assert result["pending"] is None
|
||||
|
||||
|
||||
def test_week_controller_resumes_server_truth_when_a_fifo_head_conflicts():
|
||||
result = run_controller("""
|
||||
const values=new Map();
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
let offline=true,posts=0;
|
||||
const remoteToday={revision:10,ids:['server-today'],capacity_minutes:180,estimates:{'server-today':30}};
|
||||
const remoteWeek={revision:12,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['second','third','server-week'],capacity_minutes:180,estimates:{second:40,third:45,'server-week':25}}]};
|
||||
const fetchJson=async(url,options={})=>{
|
||||
if(offline)throw new Error('connection lost');
|
||||
if(!options.method)return url.endsWith('/today')?remoteToday:remoteWeek;
|
||||
posts+=1;
|
||||
if(posts===1)return {today:{revision:5,ids:['active','first'],capacity_minutes:180,estimates:{active:30,first:35}},
|
||||
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['second','third'],capacity_minutes:180,estimates:{second:40,third:45}}]}};
|
||||
const error=new Error('changed');error.status=409;throw error;
|
||||
};
|
||||
const options={storage,getLogin:()=> 'timmy',fetchJson,localDate:()=> '2026-08-20',timeZone:()=> 'UTC'};
|
||||
const first=createWeekPlan(options);first.adopt({revision:7,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['first','second','third'],capacity_minutes:180,estimates:{first:35,second:40,third:45}}]});
|
||||
let today={revision:4,ids:['active'],capacity_minutes:180,estimates:{active:30}};
|
||||
today=(await first.pullItem('first',today,'pull-first')).today;
|
||||
today=(await first.pullItem('second',today,'pull-second')).today;
|
||||
await first.pullItem('third',today,'pull-third');
|
||||
offline=false;const conflicted=await first.flushPull();
|
||||
const restored=createWeekPlan(options),resumed=restored.resumePull();
|
||||
console.log(JSON.stringify({conflicted,resumed,state:restored.state(),pending:restored.pendingPull()}));
|
||||
""")
|
||||
|
||||
assert result["conflicted"]["conflict"] is True
|
||||
assert result["resumed"]["conflict"] is True
|
||||
assert result["resumed"]["today"]["ids"] == ["server-today"]
|
||||
assert result["state"]["revision"] == 12
|
||||
assert result["state"]["days"][0]["ids"] == ["second", "third", "server-week"]
|
||||
assert result["pending"]["body"]["operation_id"] == "pull-second"
|
||||
|
||||
|
||||
def test_week_controller_preserves_a_conflicted_pull_intent_and_adopts_server_truth():
|
||||
result = run_controller("""
|
||||
const values=new Map(),requests=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const remoteToday={revision:9,ids:['newer'],capacity_minutes:90,estimates:{newer:30}};
|
||||
const remoteWeek={revision:12,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['pull','server'],capacity_minutes:90,estimates:{pull:45,server:30}}]};
|
||||
const fetchJson=async(url,options={})=>{
|
||||
requests.push({url,method:options.method||'GET'});
|
||||
if(options.method){const error=new Error('changed');error.status=409;throw error;}
|
||||
return url.endsWith('/today')?remoteToday:remoteWeek;
|
||||
};
|
||||
const week=createWeekPlan({storage,getLogin:()=> 'timmy',fetchJson,localDate:()=> '2026-08-20',timeZone:()=> 'UTC'});
|
||||
week.adopt({revision:7,timezone:'UTC',days:[{plan_date:'2026-08-21',ids:['pull'],capacity_minutes:90,estimates:{pull:45}}]});
|
||||
const outcome=await week.pullItem('pull',{revision:4,ids:['active'],capacity_minutes:90,estimates:{active:30}},'conflicted-pull');
|
||||
console.log(JSON.stringify({outcome,state:week.state(),pending:week.pendingPull(),requests}));
|
||||
""")
|
||||
|
||||
assert result["outcome"]["conflict"] is True
|
||||
assert result["outcome"]["today"]["ids"] == ["newer"]
|
||||
assert result["state"]["revision"] == 12
|
||||
assert result["state"]["days"][0]["ids"] == ["pull", "server"]
|
||||
assert result["pending"]["body"]["operation_id"] == "conflicted-pull"
|
||||
assert result["pending"]["conflict"] is True
|
||||
assert result["requests"] == [
|
||||
{"url": "api/v1/week/pull-item", "method": "POST"},
|
||||
{"url": "api/v1/today", "method": "GET"},
|
||||
{"url": "api/v1/week", "method": "GET"},
|
||||
]
|
||||
|
||||
|
||||
def test_week_controller_retires_completed_work_from_every_day_in_one_durable_transition():
|
||||
result = run_controller("""
|
||||
const values=new Map();let writes=0;
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>{writes+=1;values.set(key,value);},removeItem:key=>values.delete(key)};
|
||||
const week=createWeekPlan({storage,getLogin:()=> 'timmy',fetchJson:async()=>({}),
|
||||
localDate:()=> '2026-08-20',timeZone:()=> 'UTC'});
|
||||
week.adopt({revision:6,timezone:'UTC',days:[
|
||||
{plan_date:'2026-08-21',ids:['completed','sibling'],capacity_minutes:90,estimates:{completed:30,sibling:45}},
|
||||
{plan_date:'2026-08-22',ids:['other','completed'],capacity_minutes:120,estimates:{other:60,completed:30}},
|
||||
{plan_date:'2026-08-23',ids:['untouched'],capacity_minutes:75,estimates:{untouched:25}}
|
||||
]});
|
||||
const retired=week.retire('completed');
|
||||
console.log(JSON.stringify({retired,writes,state:week.state(),pending:week.pending()}));
|
||||
""")
|
||||
|
||||
assert result["retired"]["removed"] == 2
|
||||
assert result["retired"]["sync_pending"] is True
|
||||
assert result["writes"] == 1
|
||||
assert result["state"]["days"] == [
|
||||
{"plan_date": "2026-08-21", "ids": ["sibling"], "capacity_minutes": 90,
|
||||
"estimates": {"sibling": 45}},
|
||||
{"plan_date": "2026-08-22", "ids": ["other"], "capacity_minutes": 120,
|
||||
"estimates": {"other": 60}},
|
||||
{"plan_date": "2026-08-23", "ids": ["untouched"], "capacity_minutes": 75,
|
||||
"estimates": {"untouched": 25}},
|
||||
]
|
||||
assert result["pending"]["days"] == result["state"]["days"]
|
||||
|
||||
|
||||
def test_week_controller_unplans_active_work_and_restores_exact_placement():
|
||||
result = run_controller("""
|
||||
const values=new Map();let writes=0;
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>{writes+=1;values.set(key,value);},removeItem:key=>values.delete(key)};
|
||||
const week=createWeekPlan({storage,getLogin:()=> 'timmy',fetchJson:async()=>({}),
|
||||
localDate:()=> '2026-08-20',timeZone:()=> 'UTC'});
|
||||
week.adopt({revision:6,timezone:'UTC',days:[
|
||||
{plan_date:'2026-08-21',ids:['first','remove','last'],capacity_minutes:120,estimates:{first:20,remove:35,last:40}},
|
||||
{plan_date:'2026-08-22',ids:['other'],capacity_minutes:90,estimates:{other:30}}
|
||||
]});
|
||||
const receipt=week.unplan('remove');
|
||||
const removed=week.state();
|
||||
const restored=week.restore(receipt);
|
||||
console.log(JSON.stringify({receipt,removed,restored,writes,state:week.state(),pending:week.pending()}));
|
||||
""")
|
||||
|
||||
assert result["receipt"] == {
|
||||
"id": "remove", "plan_date": "2026-08-21", "index": 1, "estimate": 35,
|
||||
}
|
||||
assert result["removed"]["days"][0]["ids"] == ["first", "last"]
|
||||
assert result["restored"]["sync_pending"] is True
|
||||
assert result["writes"] == 2
|
||||
assert result["state"]["days"][0]["ids"] == ["first", "remove", "last"]
|
||||
assert result["state"]["days"][0]["estimates"]["remove"] == 35
|
||||
assert result["pending"]["days"] == result["state"]["days"]
|
||||
|
||||
|
||||
def test_week_workflow_saves_and_advances_without_closing_the_planner():
|
||||
result = run_controller("""
|
||||
const createWorkflow=createWeekPlan.Workflow;
|
||||
@@ -351,28 +621,37 @@ const dateRoot=makeElement();
|
||||
Object.defineProperty(dateRoot,'innerHTML',{set(value){this.value=value;this.buttons=[];},get(){return this.value||'';}});
|
||||
elements.set('#week-plan-dates',dateRoot);
|
||||
const reviewDays=makeElement();
|
||||
Object.defineProperty(reviewDays,'innerHTML',{set(value){this.value=value;},get(){return this.value||'';}});
|
||||
Object.defineProperty(reviewDays,'innerHTML',{set(value){this.value=value;this.pullButtons=[...value.matchAll(/data-week-pull-item=\"([^\"]+)/g)].map(match=>({
|
||||
dataset:{weekPullItem:match[1]},listeners:{},disabled:false,
|
||||
addEventListener(name,listener){this.listeners[name]=listener;},focus(){this.focused=true;}
|
||||
}));},get(){return this.value||'';}});
|
||||
reviewDays.querySelectorAll=selector=>selector==='[data-week-pull-item]'?reviewDays.pullButtons||[]:[];
|
||||
elements.set('#week-review-days',reviewDays);
|
||||
for(const selector of ['#mobile-week-summary','#my-work-action-status','#week-plan-progress','#save-today-plan',
|
||||
'#week-review','#week-review-duplicates','#confirm-week-plan','#week-review-status','#back-to-week-review',
|
||||
'#edit-week-plan']) if(!elements.has(selector))elements.set(selector,makeElement());
|
||||
let writes=0,opened=0,reviewMode=false;
|
||||
let writes=0,opened=0,reviewMode=false,pullRequest=null,replacedToday=null;
|
||||
const review={days:dates.map((date,index)=>({plan_date:date,label:'Day '+(index+1),
|
||||
ids:index===2?['issue:stackchain/dashboard:42:']:[],capacity_minutes:60,
|
||||
estimates:index===2?{'issue:stackchain/dashboard:42:':30}:{},planned_minutes:index===2?30:0,overloaded:false})),
|
||||
duplicates:[],blockers:[],can_confirm:true};
|
||||
const controller={dates:()=>dates.map((date,index)=>({date,label:'Day '+(index+1)})),day:date=>review.days.find(day=>day.plan_date===date),
|
||||
pass:date=>{const index=dates.indexOf(date);return {position:index+1,total:7,planned:1,next_date:dates[index+1]||null,last:index===6};},
|
||||
load:async()=>({}),summary:()=> '1 item across 1 day',review:()=>review,pending:()=>false,
|
||||
move:()=>true,flush:async()=>{writes+=1;}};
|
||||
load:async()=>({}),summary:()=> '1 item across 1 day',review:()=>review,pending:()=>false,offline:()=>false,
|
||||
move:()=>true,flush:async()=>{writes+=1;},pullItem:async(id,today,operationId)=>{
|
||||
pullRequest={id,today,operationId};return {today:{revision:4,ids:['active',id],estimates:{[id]:30}},week:{revision:8,days:[]}};
|
||||
}};
|
||||
const workflow=createWorkflow({controller,qs:selector=>elements.get(selector),getLogin:()=> 'timmy',
|
||||
getItem:id=>id.includes(':42:')?{kind:'issue',title:'Ship mobile overview',repository:'stackchain/dashboard',number:42}:null,
|
||||
openPlanner:()=>{opened+=1;},setReviewMode:value=>{reviewMode=value;},escapeHtml:value=>value,escapeAttribute:value=>value,
|
||||
todayWork:{replace:()=>{},replacePlanning:()=>{}},refresh:()=>{},warm:()=>{}});
|
||||
today:()=>({revision:3,ids:['active'],estimates:{}}),operationId:()=> 'pull-once',
|
||||
todayWork:{replace:ids=>{replacedToday=ids;},replacePlanning:()=>{}},refresh:()=>{},warm:()=>{}});
|
||||
await workflow.open({disabled:false});
|
||||
const initialMarkup=reviewDays.innerHTML;
|
||||
await reviewDays.pullButtons[0].listeners.click({currentTarget:reviewDays.pullButtons[0]});
|
||||
console.log(JSON.stringify({reviewing:workflow.reviewing(),reviewMode,writes,opened,copy:workflow.copy(),
|
||||
reviewHidden:elements.get('#week-review').hidden,datesHidden:elements.get('#week-plan-dates').hidden,
|
||||
markup:reviewDays.innerHTML,status:elements.get('#week-review-status').textContent,
|
||||
markup:initialMarkup,status:elements.get('#week-review-status').textContent,pullRequest,replacedToday,
|
||||
confirmHidden:elements.get('#confirm-week-plan').hidden,editWeekHidden:elements.get('#edit-week-plan').hidden,
|
||||
editWeekLabel:elements.get('#edit-week-plan').textContent}));
|
||||
""")
|
||||
@@ -388,13 +667,125 @@ console.log(JSON.stringify({reviewing:workflow.reviewing(),reviewMode,writes,ope
|
||||
assert result["datesHidden"] is True
|
||||
assert "Ship mobile overview" in result["markup"]
|
||||
assert "Next up" in result["markup"]
|
||||
assert "Add to Today" in result["markup"]
|
||||
assert result["pullRequest"]["id"] == "issue:stackchain/dashboard:42:"
|
||||
assert result["pullRequest"]["operationId"] == "pull-once"
|
||||
assert result["replacedToday"] == ["active", "issue:stackchain/dashboard:42:"]
|
||||
assert "data-week-move" not in result["markup"]
|
||||
assert result["status"] == "Week Ahead overview · no changes made."
|
||||
assert result["status"] == "Ship mobile overview added to Today."
|
||||
assert result["confirmHidden"] is True
|
||||
assert result["editWeekHidden"] is False
|
||||
assert result["editWeekLabel"] == "Edit week"
|
||||
|
||||
|
||||
def test_week_overview_reviews_today_capacity_before_confirming_an_overload():
|
||||
result = run_controller("""
|
||||
const createWorkflow=createWeekPlan.Workflow;
|
||||
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
|
||||
const elements=new Map();
|
||||
const makeElement=()=>({hidden:false,textContent:'',disabled:false,innerHTML:'',addEventListener:()=>{},focus:()=>{},
|
||||
querySelectorAll:()=>[],querySelector:()=>null,scrollIntoView:()=>{}});
|
||||
elements.set('#week-plan-dates',makeElement());
|
||||
const reviewDays=makeElement();
|
||||
Object.defineProperty(reviewDays,'innerHTML',{set(value){this.value=value;this.pullButtons=[...value.matchAll(/data-week-pull-item=\"([^\"]+)/g)].map(match=>({
|
||||
dataset:{weekPullItem:match[1]},listeners:{},disabled:false,
|
||||
addEventListener(name,listener){this.listeners[name]=listener;},focus(){this.focused=true;}
|
||||
}));},get(){return this.value||'';}});
|
||||
reviewDays.querySelectorAll=selector=>selector==='[data-week-pull-item]'?reviewDays.pullButtons||[]:[];
|
||||
elements.set('#week-review-days',reviewDays);
|
||||
for(const selector of ['#mobile-week-summary','#my-work-action-status','#week-plan-progress','#save-today-plan',
|
||||
'#week-review','#week-review-duplicates','#confirm-week-plan','#week-review-status','#back-to-week-review','#edit-week-plan'])
|
||||
if(!elements.has(selector))elements.set(selector,makeElement());
|
||||
const review={days:dates.map((date,index)=>({plan_date:date,label:'Day '+(index+1),
|
||||
ids:index===0?['issue:stackchain/dashboard:44:']:[],capacity_minutes:60,
|
||||
estimates:index===0?{'issue:stackchain/dashboard:44:':30}:{},planned_minutes:index===0?30:0,overloaded:false})),
|
||||
duplicates:[],blockers:[],can_confirm:true};
|
||||
const pulls=[],confirmations=[];let approve=false;
|
||||
const controller={dates:()=>dates.map((date,index)=>({date,label:'Day '+(index+1)})),day:date=>review.days.find(day=>day.plan_date===date),
|
||||
pass:date=>({position:dates.indexOf(date)+1,total:7,planned:1,next_date:null,last:false}),load:async()=>({}),
|
||||
summary:()=> '1 item across 1 day',review:()=>review,pending:()=>false,offline:()=>false,move:()=>true,flush:async()=>({}),
|
||||
pullItem:async(id,today,operationId,allowOverCapacity)=>{pulls.push({id,operationId,allowOverCapacity});
|
||||
return {today:{revision:4,ids:['active',id],capacity_minutes:60,estimates:{active:45,[id]:30}},week:{revision:8,days:[]}};}};
|
||||
const workflow=createWorkflow({controller,qs:selector=>elements.get(selector),
|
||||
getItem:id=>({kind:'issue',title:'Capacity review',repository:'stackchain/dashboard',number:44}),
|
||||
openPlanner:()=>{},escapeHtml:value=>value,escapeAttribute:value=>value,
|
||||
today:()=>({revision:3,ids:['active'],capacity_minutes:60,estimates:{active:45}}),operationId:()=> 'capacity-pull',
|
||||
confirmEarly:message=>{confirmations.push(message);return approve;},
|
||||
todayWork:{replace:()=>{},replacePlanning:()=>{}},refresh:()=>{},warm:()=>{}});
|
||||
await workflow.open({disabled:false});
|
||||
const markup=reviewDays.innerHTML,button=reviewDays.pullButtons[0];
|
||||
await button.listeners.click({currentTarget:button});
|
||||
const afterCancel={pulls:pulls.length,disabled:button.disabled,status:elements.get('#week-review-status').textContent};
|
||||
approve=true;
|
||||
await button.listeners.click({currentTarget:button});
|
||||
console.log(JSON.stringify({markup,confirmations,afterCancel,pulls}));
|
||||
""")
|
||||
|
||||
assert "75 of 60 min" in result["markup"]
|
||||
assert result["afterCancel"] == {"pulls": 0, "disabled": False, "status": "Week Ahead overview · no changes made."}
|
||||
assert result["confirmations"] == [
|
||||
"Add Capacity review to Today?\n\nToday will be 75 of 60 min · 15 min over capacity.",
|
||||
"Add Capacity review to Today?\n\nToday will be 75 of 60 min · 15 min over capacity.",
|
||||
]
|
||||
assert result["pulls"] == [{
|
||||
"id": "issue:stackchain/dashboard:44:", "operationId": "capacity-pull",
|
||||
"allowOverCapacity": True,
|
||||
}]
|
||||
|
||||
|
||||
def test_week_overview_removes_active_work_and_undo_restores_it():
|
||||
result = run_controller("""
|
||||
const createWorkflow=createWeekPlan.Workflow;
|
||||
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
|
||||
const elements=new Map();
|
||||
const makeElement=()=>({hidden:false,textContent:'',disabled:false,innerHTML:'',listeners:{},dataset:{},
|
||||
addEventListener(name,listener){this.listeners[name]=listener;},focus(){this.focused=true;},querySelectorAll:()=>[],querySelector:()=>null});
|
||||
const reviewDays=makeElement();
|
||||
Object.defineProperty(reviewDays,'innerHTML',{set(value){this.value=value;this.removeButtons=[...value.matchAll(/data-week-unplan=\"([^\"]+)/g)].map(match=>({
|
||||
dataset:{weekUnplan:match[1]},listeners:{},addEventListener(name,listener){this.listeners[name]=listener;},focus(){this.focused=true;}
|
||||
}));},get(){return this.value||'';}});
|
||||
reviewDays.querySelectorAll=selector=>selector==='[data-week-unplan]'?reviewDays.removeButtons||[]:[];
|
||||
elements.set('#week-review-days',reviewDays);
|
||||
const undo=makeElement();elements.set('#undo-week-unplan',undo);
|
||||
for(const selector of ['#week-plan-dates','#mobile-week-summary','#my-work-action-status','#week-plan-progress','#save-today-plan',
|
||||
'#week-review','#week-review-duplicates','#confirm-week-plan','#week-review-status','#back-to-week-review','#edit-week-plan',
|
||||
'#week-offline-snapshot','#retry-week-live','#open-week-capacity-import','#open-week-reflow','#week-unplan-receipt'])
|
||||
if(!elements.has(selector))elements.set(selector,makeElement());
|
||||
let ids=['one','remove','last'],unplanned=null,restored=null,flushes=0,timer=null;
|
||||
const buildReview=()=>({days:dates.map((date,index)=>({plan_date:date,label:'Day '+(index+1),ids:index===0?[...ids]:[],
|
||||
capacity_minutes:120,estimates:index===0?{one:20,remove:35,last:40}:{},planned_minutes:index===0?ids.reduce((sum,id)=>sum+({one:20,remove:35,last:40}[id]),0):0,overloaded:false})),duplicates:[],blockers:[],can_confirm:true});
|
||||
const controller={dates:()=>dates.map((date,index)=>({date,label:'Day '+(index+1)})),day:date=>buildReview().days.find(day=>day.plan_date===date),
|
||||
load:async()=>({}),summary:()=> ids.length+' items across 1 day',review:buildReview,pending:()=>false,offline:()=>false,
|
||||
unplan:id=>{const index=ids.indexOf(id);if(index<0)return false;ids.splice(index,1);return unplanned={id,plan_date:dates[0],index,estimate:35};},
|
||||
restore:receipt=>{ids.splice(receipt.index,0,receipt.id);restored=receipt;return {};},flush:async()=>{flushes+=1;return {};}};
|
||||
const workflow=createWorkflow({controller,qs:selector=>elements.get(selector),getItem:id=>({kind:'issue',title:id==='remove'?'Remove me':id,repository:'r',number:2}),
|
||||
openPlanner:()=>{},setReviewMode:()=>{},escapeHtml:value=>value,escapeAttribute:value=>value,
|
||||
setTimer:callback=>{timer=callback;return 1;},clearTimer:()=>{timer=null;},
|
||||
todayWork:{replace:()=>{},replacePlanning:()=>{}},refresh:()=>{},warm:()=>{}});
|
||||
await workflow.open({disabled:false});
|
||||
const remove=reviewDays.removeButtons.find(button=>button.dataset.weekUnplan==='remove');
|
||||
await remove.listeners.click({currentTarget:remove});
|
||||
const afterRemove={ids:[...ids],flushes,receiptHidden:elements.get('#week-unplan-receipt').hidden,
|
||||
status:elements.get('#week-unplan-receipt').textContent,undoHidden:undo.hidden,timer:Boolean(timer)};
|
||||
await undo.listeners.click({currentTarget:undo});
|
||||
console.log(JSON.stringify({buttonCount:reviewDays.removeButtons.length,unplanned,afterRemove,restored,ids,flushes,
|
||||
receiptHidden:elements.get('#week-unplan-receipt').hidden,undoFocused:undo.focused||false}));
|
||||
""")
|
||||
|
||||
assert result["buttonCount"] == 3
|
||||
assert result["unplanned"] == {
|
||||
"id": "remove", "plan_date": "2026-08-21", "index": 1, "estimate": 35,
|
||||
}
|
||||
assert result["afterRemove"] == {
|
||||
"ids": ["one", "last"], "flushes": 1, "receiptHidden": False,
|
||||
"status": "Remove me removed from Week Ahead.", "undoHidden": False, "timer": True,
|
||||
}
|
||||
assert result["restored"] == result["unplanned"]
|
||||
assert result["ids"] == ["one", "remove", "last"]
|
||||
assert result["flushes"] == 2
|
||||
assert result["receiptHidden"] is True
|
||||
|
||||
|
||||
def test_week_overview_previews_cancels_and_applies_one_reflow():
|
||||
result = run_controller("""
|
||||
const createWorkflow=createWeekPlan.Workflow;
|
||||
@@ -542,7 +933,7 @@ def test_dashboard_routes_week_overview_controls_through_existing_detail_flow_wi
|
||||
|
||||
workflow_mount = dashboard.split("const weekFlow=createWeekPlanWorkflow({", 1)[1].split("});", 1)[0]
|
||||
assert "openItem:openRoutedWork" in workflow_mount
|
||||
assert "t:()=>latestTodayPlan" in workflow_mount
|
||||
assert "t:v=>v?latestTodayPlan=v:latestTodayPlan" in workflow_mount
|
||||
|
||||
assert ".week-review-item-open" in css
|
||||
rule = css.split(".week-review-item-open", 1)[1].split("}", 1)[0]
|
||||
@@ -552,6 +943,78 @@ def test_dashboard_routes_week_overview_controls_through_existing_detail_flow_wi
|
||||
start_rule = css.split(".week-start-early", 1)[1].split("}", 1)[0]
|
||||
assert "min-height:44px" in start_rule
|
||||
assert "width:100%" in start_rule
|
||||
assert ".week-review-pull" in css
|
||||
pull_rule = css.split(".week-review-pull", 1)[1].split("}", 1)[0]
|
||||
assert "min-height:44px" in pull_rule
|
||||
assert "width:100%" in pull_rule
|
||||
|
||||
|
||||
def test_dashboard_restores_and_retries_a_saved_week_to_today_pull_on_mobile_lifecycle():
|
||||
dashboard = (FRONTEND / "dashboard.js").read_text()
|
||||
week_plan = (FRONTEND / "week-plan.js").read_text()
|
||||
|
||||
recovery = dashboard.split(" function syncPendingTomorrow()", 1)[1].split("\n }", 1)[0]
|
||||
assert "weekFlow.resumePull()" in recovery
|
||||
assert "weekFlow.flushPull()" in recovery
|
||||
|
||||
lifecycle = dashboard.split("tomorrowPlan.startLifecycle({", 1)[1].split(" });", 1)[0]
|
||||
assert "syncPendingTomorrow()" in lifecycle
|
||||
assert dashboard.count("syncPendingTomorrow();") >= 2
|
||||
assert "result.sync_pending?String(item?.title||'Work')+' added to Today · sync pending.'" in week_plan
|
||||
|
||||
|
||||
def test_successful_issue_close_notifies_week_ahead_only_after_upstream_confirmation():
|
||||
issue_sheet = (FRONTEND / "issue-sheet.js").read_text()
|
||||
week_plan = (FRONTEND / "week-plan.js").read_text()
|
||||
close_method = issue_sheet.split(" close(item) {", 1)[1].split(" release(item)", 1)[0]
|
||||
|
||||
confirmed = close_method.index("result?.state !== 'closed'")
|
||||
notified = close_method.index("stackchain:issue-closed")
|
||||
assert confirmed < notified
|
||||
assert "detail:item" in close_method
|
||||
assert "addEventListener?.('stackchain:issue-closed'" in week_plan
|
||||
assert "retire(event.detail)" in week_plan
|
||||
|
||||
|
||||
def test_week_workflow_refreshes_the_open_overview_and_reports_pending_retirement():
|
||||
result = run_controller("""
|
||||
const createWorkflow=createWeekPlan.Workflow;
|
||||
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
|
||||
const elements=new Map();
|
||||
const makeElement=()=>({hidden:false,textContent:'',disabled:false,innerHTML:'',dataset:{},focused:false,
|
||||
addEventListener:()=>{},focus(){this.focused=true;},querySelectorAll:()=>[],querySelector:()=>null,scrollIntoView:()=>{}});
|
||||
elements.set('#week-plan-dates',makeElement());
|
||||
const reviewDays=makeElement();elements.set('#week-review-days',reviewDays);
|
||||
for(const selector of ['#mobile-week-summary','#my-work-action-status','#week-plan-progress','#save-today-plan','#week-review',
|
||||
'#week-review-duplicates','#confirm-week-plan','#week-review-status','#back-to-week-review','#edit-week-plan',
|
||||
'#week-offline-snapshot','#retry-week-live','#open-week-capacity-import','#open-week-reflow','#week-reflow-review'])
|
||||
if(!elements.has(selector))elements.set(selector,makeElement());
|
||||
let ids=['completed','sibling'];
|
||||
const review=()=>({days:dates.map((date,index)=>({plan_date:date,label:'Day '+(index+1),ids:index===0?[...ids]:[],
|
||||
capacity_minutes:90,estimates:index===0?Object.fromEntries(ids.map(id=>[id,id==='completed'?30:45])):{},
|
||||
planned_minutes:index===0?ids.reduce((sum,id)=>sum+(id==='completed'?30:45),0):0,overloaded:false})),
|
||||
duplicates:[],blockers:[],can_confirm:true});
|
||||
const controller={dates:()=>dates.map((date,index)=>({date,label:'Day '+(index+1)})),day:date=>review().days.find(day=>day.plan_date===date),
|
||||
load:async()=>({}),summary:()=>ids.length+' items across 1 day',review,pending:()=>false,offline:()=>false,
|
||||
retire:id=>{ids=ids.filter(value=>value!==id);return {removed:1,sync_pending:true};},
|
||||
flush:async()=>{throw new Error('offline');}};
|
||||
let identityKind=null;
|
||||
const workflow=createWorkflow({controller,qs:selector=>elements.get(selector),
|
||||
getItem:id=>({kind:'issue',title:id==='completed'?'Completed work':'Sibling work',repository:'r',number:id==='completed'?1:2}),
|
||||
openPlanner:()=>{},setReviewMode:()=>{},escapeHtml:value=>value,escapeAttribute:value=>value,
|
||||
todayWork:{identity:item=>{identityKind=item.kind;return item.id;},replace:()=>{},replacePlanning:()=>{}},refresh:()=>{},warm:()=>{}});
|
||||
await workflow.open({disabled:false});
|
||||
const outcome=await workflow.retire({id:'completed',title:'Completed work'});
|
||||
console.log(JSON.stringify({outcome,identityKind,markup:reviewDays.innerHTML,status:elements.get('#week-review-status').textContent,
|
||||
editFocused:elements.get('#edit-week-plan').focused}));
|
||||
""")
|
||||
|
||||
assert result["outcome"] == "pending"
|
||||
assert result["identityKind"] == "issue"
|
||||
assert "Completed work" not in result["markup"]
|
||||
assert "Sibling work" in result["markup"]
|
||||
assert result["status"] == "Completed work removed · sync pending."
|
||||
assert result["editFocused"] is True
|
||||
|
||||
|
||||
def test_week_workflow_marks_a_confirmed_fallback_read_only_and_retries_live_data():
|
||||
@@ -1241,7 +1704,7 @@ def test_mobile_week_ahead_review_is_rendered_touch_safe_and_confirmed_explicitl
|
||||
assert 'id="week-review-days"' in index
|
||||
assert 'id="week-review-duplicates"' in index
|
||||
assert 'id="confirm-week-plan"' in index
|
||||
assert "setReviewMode:value=>qs('#plan-today-sheet').classList.toggle('week-review-mode',value)" in dashboard
|
||||
assert "setReviewMode:v=>qs('#plan-today-sheet').classList.toggle('week-review-mode',v)" in dashboard
|
||||
assert "weekFlow.confirm()" in dashboard
|
||||
assert ".week-review-day.is-overloaded" in css
|
||||
assert ".week-review-day button { min-height:44px;" in css
|
||||
|
||||
Reference in new issue
Block a user