Compare commits

...
Author SHA1 Message Date
rockachopa 99b60e5f5f Merge pull request 'Resolve offline Tomorrow plan conflicts on mobile' (#1165) from timmy/1164-tomorrow-conflict-recovery into main
CI / lint (push) Successful in 3m28s
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 3m58s
CI / release-candidate (push) Successful in 8s
2026-08-20 04:12:33 +00:00
timmy 059722de6c fix: bind Tomorrow conflict recovery to operator account
CI / lint (pull_request) Successful in 3m36s
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 3m50s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 04:01:25 +00:00
timmy 16a6ee1136 feat: resolve mobile Tomorrow plan conflicts (Closes #1164)
CI / lint (pull_request) Successful in 3m26s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Failing after 3m49s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 03:46:22 +00:00
rockachopa f9c4938401 Merge pull request 'feat: CI regression: mobile handoff break status assertion fails on main' (#1163) from timmy/1162-ci-regression-mobile-handoff-break-status-assert into main
CI / lint (push) Successful in 3m14s
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 3m54s
CI / release-candidate (push) Successful in 8s
2026-08-20 03:09:59 +00:00
timmy bdf1ddaada fix: restore break status after account confirmation
CI / lint (pull_request) Successful in 3m32s
CI / build-release (pull_request) Successful in 10s
CI / browser-journey (pull_request) Successful in 4m9s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 02:48:56 +00:00
rockachopa cf94624aa9 Merge pull request 'Keep Tomorrow plans through offline saves' (#1161) from timmy/1160-offline-tomorrow-sync into main
CI / lint (push) Successful in 4m11s
CI / build-release (push) Successful in 9s
CI / browser-journey (push) Failing after 4m29s
CI / release-candidate (push) Has been skipped
2026-08-20 02:19:59 +00:00
timmy f42f89ca21 feat: keep Tomorrow plans through offline saves (Closes #1160)
CI / lint (pull_request) Successful in 3m17s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m5s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 02:10:37 +00:00
rockachopa ae632e3562 Merge pull request 'Make Tomorrow planning a first-class mobile queue' (#1159) from timmy/1158-mobile-tomorrow-queue into main
CI / lint (push) Successful in 3m26s
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m0s
CI / release-candidate (push) Successful in 7s
2026-08-20 01:29:18 +00:00
timmy 0fd6314391 feat: make Tomorrow a first-class mobile queue (Closes #1158)
CI / lint (pull_request) Successful in 3m7s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 3m53s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 01:20:27 +00:00
timmy 1ae49df1b0 Merge pull request 'feat: CI: browser journey leaves first-task completion sync pending on main' (#1157) from timmy/1156-ci-browser-journey-leaves-first-task-completion- into main
CI / lint (push) Successful in 3m22s
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 4m1s
CI / release-candidate (push) Successful in 7s
2026-08-20 00:46:35 +00:00
timmy 16841f18e1 fix: drain first-task completion during Today refresh (Closes #1156)
CI / lint (pull_request) Successful in 3m15s
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 3m49s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 00:19:50 +00:00
rockachopa 80863182d4 Merge pull request 'Recover Tomorrow plans after missed midnight and interrupted promotion' (#1155) from timmy/1154-tomorrow-rollover-recovery into main
CI / lint (push) Successful in 3m14s
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Failing after 4m30s
CI / release-candidate (push) Has been skipped
2026-08-19 23:56:19 +00:00
timmy 7c2e9861d7 fix: tolerate unavailable browser timezone data
CI / lint (pull_request) Successful in 3m25s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m2s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 23:39:34 +00:00
timmy 7deb1c1de9 fix: recover Tomorrow promotion after missed rollover (Closes #1154)
CI / lint (pull_request) Successful in 3m39s
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Failing after 3m50s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 23:27:07 +00:00
rockachopa 559fd2dc89 Merge pull request 'Plan tomorrow without disrupting active Today work' (#1153) from timmy/1152-tomorrow-plan into main
CI / lint (push) Successful in 3m14s
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m6s
CI / release-candidate (push) Successful in 8s
2026-08-19 22:56:33 +00:00
timmy 0cb7328aa1 feat: plan tomorrow independently (Closes #1152)
CI / lint (pull_request) Successful in 3m21s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 3m53s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 22:46:56 +00:00
rockachopa 664e5e999f Merge pull request 'Make Done for Today completion durably atomic' (#1151) from timmy/1150-atomic-today-completion into main
CI / lint (push) Successful in 3m47s
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 3m29s
CI / release-candidate (push) Successful in 7s
2026-08-19 22:00:26 +00:00
timmy 37e919f43f fix: preserve first-task completion delivery
CI / lint (pull_request) Successful in 3m9s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 3m36s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 21:52:50 +00:00
timmy d0780a72a7 feat: make Today completion durably atomic (Closes #1150)
CI / lint (pull_request) Successful in 3m0s
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Failing after 3m30s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 21:39:03 +00:00
rockachopa f785134dfe Merge pull request 'Keep first-task completion across devices' (#1149) from timmy/1148-cross-device-first-task into main
CI / lint (push) Successful in 3m17s
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 3m48s
CI / release-candidate (push) Successful in 7s
2026-08-19 20:51:35 +00:00
timmy de405efdbc test: verify first-task completion on a replacement phone
CI / lint (pull_request) Successful in 3m18s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 3m43s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 20:44:03 +00:00
timmy fa47ded3ab feat: sync first-task completion across devices (Closes #1148)
CI / lint (pull_request) Successful in 3m6s
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Failing after 3m27s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 20:34:10 +00:00
rockachopa e2be14d7c7 Merge pull request 'Guide first mobile task through a completed Today outcome' (#1147) from timmy/1146-first-task-completed-outcome into main
CI / lint (push) Successful in 3m9s
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 3m55s
CI / release-candidate (push) Successful in 8s
Merge pull request 'Guide first mobile task through a completed Today outcome' (#1147)
2026-08-19 19:44:43 +00:00
timmy e2b5f6042c feat: coach first mobile task to completion (Closes #1146)
CI / lint (pull_request) Successful in 3m8s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 3m34s
CI / release-candidate (pull_request) Has been skipped
2026-08-19 19:34:31 +00:00
timmy 941a508d4b Finish first-task onboarding with an active Today session
CI / lint (push) Successful in 3m6s
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 3m31s
CI / release-candidate (push) Successful in 7s
Closes #1144
2026-08-19 18:59:13 +00:00
35 changed files with 2071 additions and 112 deletions

No files matched your search

+7 -1
View File
@@ -149,7 +149,13 @@ failure preserves both the reply draft and checkpoint. Finishing or choosing **E
unchanged. Another or unconfirmed account cannot see or resume it. Server revisions prevent delayed
responses from replacing a newer plan; same-account browser tabs exchange fresh snapshots,
and reconnecting or returning to the dashboard refreshes server truth after replaying queued
offline operations. Planning edits can remain offline for up to 30 days. After that, the
offline operations. **Plan Tomorrow** remains independent from active Today work and durably admits the exact
ordered plan, capacity, estimates, next local date, timezone, and server revision to account-bound browser
storage before closing on a phone. The Queues summary marks it **sync pending** while offline; reconnect,
foreground, and midnight lifecycle checks share one delivery flight. A successful account receipt removes
the pending copy, while a revision conflict preserves both the phone plan and fresh server snapshot for
review. Unsynced Tomorrow work is never promoted into Today.
Planning edits can remain offline for up to 30 days. After that, the
expired edit is discarded visibly and the account plan is kept rather than replaying stale
intent. The server retains no more than 4,096 operation receipts per account and removes
receipts older than the same 30-day window; client base revisions keep a pruned replay from
+24
View File
@@ -241,6 +241,25 @@ textarea { resize: vertical; min-height: 120px; }
.plan-today-header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
.plan-today-header h2, .plan-today-header p { margin-top:0; }
.plan-today-header button { min-width:44px; min-height:44px; }
.tomorrow-conflict-review { margin-top:14px; }
.tomorrow-conflict-plans { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }
.tomorrow-conflict-plans > section { min-width:0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
.tomorrow-conflict-plans h4 { margin:0 0 8px; }
.tomorrow-conflict-plan-summary { margin:0 0 8px; color:#bfdbfe; }
.tomorrow-conflict-plan-list { margin:0; padding-left:22px; overflow-wrap:anywhere; }
.tomorrow-conflict-plan-list li + li { margin-top:6px; }
.tomorrow-conflict-actions { display:flex; gap:8px; margin-top:14px; }
.tomorrow-conflict-actions button { min-height:44px; flex:1 1 0; }
.tomorrow-conflict-status { min-height:1.4em; margin-top:8px; }
.plan-today-sheet.tomorrow-conflict-mode .mobile-plan-today-nav,
.plan-today-sheet.tomorrow-conflict-mode #plan-today-fit,
.plan-today-sheet.tomorrow-conflict-mode #plan-today-selected,
.plan-today-sheet.tomorrow-conflict-mode #plan-today-available-work,
.plan-today-sheet.tomorrow-conflict-mode .plan-today-actions { display:none; }
@media (max-width:480px) {
.tomorrow-conflict-plans { grid-template-columns:1fr; }
.tomorrow-conflict-actions { flex-direction:column; }
}
.mobile-plan-today-nav { position:sticky; top:0; z-index:5; display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:4px; margin:0 -18px 10px; padding:4px 18px; background:rgba(11,21,38,.98); border-block:1px solid #2a496e; }
.mobile-plan-today-nav button { min-width:0; min-height:44px; padding:4px; border-color:transparent; font-size:12px; }
.mobile-plan-today-nav button[aria-current="location"] { color:#bfdbfe; background:#17365a; border-color:#31577f; }
@@ -768,6 +787,7 @@ textarea { resize: vertical; min-height: 120px; }
.new-issue { min-height:44px; }
.find-work-action { min-height:44px; }
.my-work-actions { display:flex; flex-wrap:wrap; gap:8px; }
.plan-tomorrow { min-height:44px; }
.start-work-session { min-height:44px; }
.resume-today-session, .end-today-session { min-height:44px; }
.work-session-nav { position:sticky; bottom:0; z-index:5; display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; margin-top:12px; padding:10px 4px; padding-bottom:calc(10px + env(safe-area-inset-bottom)); background:rgba(11,21,38,.98); border-top:1px solid #2a496e; }
@@ -1206,6 +1226,10 @@ textarea { resize: vertical; min-height: 120px; }
.mobile-update-outcome p { margin:0 0 10px; }
.mobile-update-outcome button { width:100%; min-height:44px; }
.mobile-today-hud { position:fixed; left:8px; right:8px; bottom:calc(56px + env(safe-area-inset-bottom)); z-index:44; display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:4px; max-width:100%; padding:8px; border:1px solid #31577f; border-radius:12px 12px 0 0; background:rgba(16,38,65,.98); box-shadow:0 -8px 24px rgba(0,0,0,.28); }
.mobile-first-task-coach { grid-column:1 / -1; display:grid; gap:2px; padding:8px 10px; border-left:3px solid #60a5fa; border-radius:6px; background:#172f4d; }
.mobile-first-task-coach[hidden] { display:none; }
.mobile-first-task-receipt { position:fixed; left:12px; right:12px; bottom:calc(var(--mobile-today-clearance, 166px) + 8px + env(safe-area-inset-bottom)); z-index:46; padding:12px; border:1px solid #34d399; border-radius:10px; background:#0d3b35; font-weight:700; }
.mobile-first-task-receipt[hidden] { display:none; }
.mobile-today-summary { grid-column:1 / 4; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; text-align:left; font-weight:700; }
.mobile-today-hud [data-work-session-progress] { grid-column:4 / 7; align-self:center; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.mobile-today-hud [data-mobile-today-complete] { grid-column:1 / 3; }
+214 -14
View File
@@ -1,6 +1,7 @@
(async function(){
const workspaceLifecycle = await loadWorkspace({ document, window });
const qs = (s, el=document) => el.querySelector(s);
const announceWork = message => qs('#my-work-action-status').textContent = message;
const fmt = (d) => new Date(d).toLocaleString();
const cardPlanning = createCardPlanning(document);
const mobileComposerViewport = createMobileComposerViewport({
@@ -128,7 +129,7 @@
openFiled: openFiledFollowUp,
selectFilter: selectMobileQueue,
firstAction: name => qs('#my-work-list .my-work-card-main, #my-work-list .draft-resume, #my-work-list .draft-continue, #my-work-list .draft-edit'),
announce: message => { qs('#my-work-action-status').textContent = message; },
announce: announceWork,
getCounts: () => mobileQueueCounts,
openFindWork: () => qs('#find-work').click(),
});
@@ -226,8 +227,9 @@
),
queueBadge: qs('#mobile-queue-count'),
deadlineBadge: qs('#mobile-deadline-count'),
onSelectQueue:name => name === 'recaps' ? qs('#open-today-recaps').click() :
name === 'find' ? qs('#find-work').click() : mobileQueueLauncher.open(name),
onSelectQueue:(name, row) => name === 'recaps' ? qs('#open-today-recaps').click() :
name === 'find' ? qs('#find-work').click() :
name === 'tomorrow' ? openTomorrowPlanner(row) : mobileQueueLauncher.open(name),
detour:() => timerView,
overlays: mobileTaskOverlays,
actions: {
@@ -235,6 +237,7 @@
find: () => qs('#find-work').click(),
new: () => qs('#new-issue').click(),
search: () => qs('#open-palette').click(),
queues: () => refreshTomorrowQueueSummary(),
},
observe(callback, overlays) {
const observer = new MutationObserver(callback);
@@ -375,10 +378,94 @@
let rolloverReviewPlan = null;
const outboxCoordinator = createOutboxCoordinator({ storage: localStorage });
const todayRollover = createTodayRollover();
let planningTomorrow = false;
let latestTodayPlan = null;
const tomorrowPlan = createTomorrowPlan({
fetchJson:fetchReviewJson,
localDate:todayRollover.localDate,
timeZone:todayRollover.timeZone,
storage:localStorage,
getLogin:() => planningOwnerLogin,
});
function renderTomorrowQueueSummary(value) {
qs('#mobile-tomorrow-summary').textContent = value ? tomorrowPlan.summary(value) : tomorrowPlan.summary();
}
function syncPendingTomorrow() {
if (!tomorrowPlan.pending()) return Promise.resolve(false);
return tomorrowPlan.flush().then(saved => {
renderTomorrowQueueSummary(saved);
qs('#my-work-action-status').textContent = saved.ids.length ?
`Tomorrow saved for ${saved.plan_date} without changing Today.` :
`Tomorrow cleared for ${saved.plan_date}.`;
return saved;
}).catch(error => {
const conflict = tomorrowPlan.conflict();
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.' :
`${error.message || 'Tomorrow sync is unavailable.'} Saved on this phone · sync pending.`;
return false;
});
}
async function refreshTomorrowQueueSummary() {
try {
const loaded = await tomorrowPlan.load();
if (tomorrowPlan.conflict()) qs('#mobile-tomorrow-summary').textContent = 'Conflict · review required';
else renderTomorrowQueueSummary(loaded);
return true;
} catch (_error) {
qs('#mobile-tomorrow-summary').textContent = 'Unavailable · tap to retry';
return false;
}
}
async function openTomorrowPlanner(trigger) {
if (!planningOwnerLogin) {
qs('#my-work-action-status').textContent = 'Planning is unavailable until your operator identity is restored.';
return false;
}
trigger.disabled = true;
qs('#mobile-tomorrow-summary').textContent = 'Loading Tomorrow…';
try {
const loaded = await tomorrowPlan.load();
renderTomorrowQueueSummary(loaded);
planningTomorrow = true;
openPlanToday(trigger);
qs('#my-work-action-status').textContent = '';
return true;
} catch (error) {
qs('#mobile-tomorrow-summary').textContent = 'Unavailable · tap to retry';
qs('#my-work-action-status').textContent = `${error.message || 'Tomorrow is unavailable.'} Retry when connected.`;
return false;
} finally {
trigger.disabled = false;
}
}
const todayWork = createTodayWork({
storage: localStorage,
getLogin: () => planningOwnerLogin,
});
async function promoteTomorrowIfDue(plan) {
try {
await tomorrowPlan.load();
const promoted = await tomorrowPlan.promote(plan.revision);
if (!promoted) return false;
todayWork.replace(promoted.ids);
todayWork.replacePlanning({
capacity_minutes:promoted.capacity_minutes ?? null,
estimates:promoted.estimates || {},
});
refreshMyWorkView();
warmTodayOffline();
qs('#my-work-action-status').textContent =
'Your saved Tomorrow plan is now Today.';
return true;
} catch (error) {
qs('#my-work-action-status').textContent =
`${error.message || 'Tomorrow needs review before promotion.'} Open Plan Tomorrow to review.`;
return false;
}
}
const todaySync = createTodaySync({
storage: localStorage,
getLogin: () => planningOwnerLogin,
@@ -391,6 +478,8 @@
},
onRemotePlan: plan => {
if (!planningOwnerLogin) return;
latestTodayPlan = plan;
promoteTomorrowIfDue(plan);
todayWork.replacePlanning({
capacity_minutes: plan.capacity_minutes ?? null,
estimates: plan.estimates || {},
@@ -424,6 +513,14 @@
},
});
todaySync.startLifecycle({ window, document });
tomorrowPlan.startLifecycle({
windowObject:window,
documentObject:document,
check:() => Promise.all([
syncPendingTomorrow(),
latestTodayPlan ? promoteTomorrowIfDue(latestTodayPlan) : false,
]),
});
const todayHandoff = createTodayHandoff({
storage:localStorage,
getLogin:() => planningOwnerLogin,
@@ -1700,7 +1797,7 @@
hasCheckpoint: () => updateTriage.resumable(),
resume: () => updateTriage.resume(),
start: () => updateTriage.start(),
announce: message => { qs('#my-work-action-status').textContent = message; },
announce: announceWork,
});
function openUpdateTriage() {
@@ -2051,7 +2148,7 @@
hasCheckpoint: () => Boolean(agendaSessionCheckpoint.read()),
resume: () => workSession.resume(),
start: () => workSession.start(),
announce: message => { qs('#my-work-action-status').textContent = message; },
announce: announceWork,
});
function openAgendaSession() {
return agendaSessionLauncher.open();
@@ -2193,7 +2290,7 @@
qs('[data-work-filter="today"]').click();
workSession.start(item);
},
announce: message => { qs('#my-work-action-status').textContent = message; },
announce: announceWork,
});
function renderCreateStartCapacity() {
const result = createAndStart.capacity(qs('#create-issue-estimate').value);
@@ -2219,7 +2316,7 @@
qs('#my-work-action-status').textContent = 'Checking Today readiness…';
return todayReadiness.run('start', workSession.items(), item);
},
announce: message => { qs('#my-work-action-status').textContent = message; },
announce: announceWork,
});
const selectedSessionItem = kind => ({
@@ -2234,8 +2331,8 @@
workSession,
refresh: () => refreshMyWorkView({ reconcileSession:false }),
warm: warmTodayOffline,
announce: message => { qs('#my-work-action-status').textContent = message; },
advance: () => runTodayTransition('complete'),
announce: announceWork,
advance: () => (mobileFirstTask.completeOutcome(), runTodayTransition('complete')),
});
todayLockScreen = createTodayLockScreen({
storage:localStorage,
@@ -2604,8 +2701,14 @@
return;
}
planToday.cancel();
planningTomorrow = false;
qs('#tomorrow-conflict-review').hidden = true;
qs('#plan-today-sheet').classList.remove('tomorrow-conflict-mode');
qs('#plan-today-sheet').hidden = true;
document.body.classList.remove('task-overlay-open');
if (planTodayTrigger?.dataset.mobileQueue === 'tomorrow') {
if (!qs('#mobile-queue-sheet').open) qs('#mobile-queue-sheet').showModal();
}
planTodayTrigger?.focus();
}
@@ -2637,10 +2740,25 @@
return true;
}
function saveTomorrowPlan(plan) {
const normalized = Array.isArray(plan) ?
{ids:plan, capacity_minutes:null, estimates:{}} : plan;
const staged = tomorrowPlan.stage(normalized);
if (!staged) {
qs('#my-work-action-status').textContent =
'Tomorrow could not be saved on this phone. Free browser storage and retry.';
return false;
}
renderTomorrowQueueSummary(staged);
qs('#my-work-action-status').textContent = 'Tomorrow saved on this phone · sync pending.';
syncPendingTomorrow();
return true;
}
const planToday = createPlanToday({
identity: item => todayWork.identity(item),
limit: todayWork.limit,
save: saveTodayPlan,
save: plan => planningTomorrow ? saveTomorrowPlan(plan) : saveTodayPlan(plan),
start: () => {
qs('[data-work-filter="today"]').click();
startTodaySession();
@@ -2912,23 +3030,73 @@
});
let pendingPlanActualMinutes = null;
function tomorrowConflictPlanMarkup(value) {
const ids = value?.ids || [];
const estimates = value?.estimates || {};
const estimated = ids.reduce((total, id) => total + (Number(estimates[id]) || 0), 0);
const capacity = Number(value?.capacity_minutes) || 0;
const summary = ids.length ? `${ids.length} planned` +
(estimated && capacity ? ` · ${estimated} of ${capacity} min` : '') : 'Nothing planned';
const available = [...todayMyWork, ...activeMyWork];
const items = ids.map(id => {
const item = available.find(candidate => todayWork.identity(candidate) === id);
const label = item?.title || item?.key || id;
const estimate = Number(estimates[id]) || 0;
return `<li><strong>${escapeHtml(label)}</strong>${estimate ? ` <span>· ${estimate}&nbsp;min</span>` : ''}</li>`;
}).join('');
return `<p class="tomorrow-conflict-plan-summary">${summary}</p>` +
(items ? `<ol class="tomorrow-conflict-plan-list">${items}</ol>` : '<p class="muted">No work selected.</p>');
}
function showTomorrowConflict(conflict) {
qs('#plan-today-title').textContent = 'Resolve Tomorrow conflict';
qs('#tomorrow-conflict-phone-plan').innerHTML = tomorrowConflictPlanMarkup(conflict.local);
qs('#tomorrow-conflict-server-plan').innerHTML = tomorrowConflictPlanMarkup(conflict.remote);
qs('#tomorrow-conflict-status').textContent = '';
qs('#tomorrow-conflict-review').hidden = false;
qs('#plan-today-sheet').classList.add('tomorrow-conflict-mode');
qs('#plan-today-sheet').hidden = false;
document.body.classList.add('task-overlay-open');
const keep = qs('#keep-phone-tomorrow');
keep.focus();
requestAnimationFrame(() => keep.focus());
}
function openPlanToday(trigger, navigate = true, actualMinutes = null) {
if (!planningOwnerLogin) {
qs('#my-work-action-status').textContent = 'Planning is unavailable until your operator identity is restored.';
return;
}
if (trigger) planTodayTrigger = trigger;
qs('#plan-today-title').textContent = pendingProtectToday ? 'Protect Today' : (rolloverReviewPlan ? 'New day review' : 'Plan Today');
qs('#plan-today-title').textContent = planningTomorrow ? 'Plan Tomorrow' :
(pendingProtectToday ? 'Protect Today' : (rolloverReviewPlan ? 'New day review' : 'Plan Today'));
if (actualMinutes) pendingPlanActualMinutes = actualMinutes;
if (navigate) {
taskOverlayHistory.open('plan-today');
return;
}
const conflict = planningTomorrow ? tomorrowPlan.conflict() : null;
if (conflict) {
showTomorrowConflict(conflict);
return;
}
qs('#tomorrow-conflict-review').hidden = true;
qs('#plan-today-sheet').classList.remove('tomorrow-conflict-mode');
const recommendations = actualMinutes || pendingPlanActualMinutes || todayRecapView.pendingReplan()?.actual_minutes;
pendingPlanActualMinutes = null;
const protectProposal = pendingProtectToday;
const selected = protectProposal?.selected || todayMyWork;
planToday.open(selected, activeMyWork, todayWork.planning(), recommendations);
const tomorrow = planningTomorrow ? tomorrowPlan.state() : null;
const availablePlanningItems = [...todayMyWork, ...activeMyWork].filter((item, index, items) =>
items.findIndex(candidate => todayWork.identity(candidate) === todayWork.identity(item)) === index
);
const selected = planningTomorrow ? availablePlanningItems.filter(item =>
tomorrow.ids.includes(todayWork.identity(item))
) : (protectProposal?.selected || todayMyWork);
planToday.open(selected, activeMyWork, planningTomorrow ? tomorrow : todayWork.planning(), recommendations);
qs('#today-plan-heading').textContent = planningTomorrow ? 'Tomorrow, in order' : 'Today, in order';
qs('.plan-today-available').firstChild.textContent = planningTomorrow ? 'Available tomorrow' : 'Available today';
qs('#build-today-plan').textContent = planningTomorrow ? 'Build my Tomorrow' : 'Build my Today';
qs('#save-and-start-today').hidden = planningTomorrow;
pendingProtectToday = null;
qs('#discard-recap-replan').hidden = !todayRecapView.pendingReplan();
qs('#plan-today-error').textContent = '';
@@ -2971,7 +3139,7 @@
close: () => workRoute.close(),
refresh: refreshMyWorkView,
focus: () => qs('[data-work-filter="' + selectedWorkFilter + '"]')?.focus(),
announce: message => { qs('#my-work-action-status').textContent = message; },
announce: announceWork,
formatTime: fmt,
});
const laterPickerElement = qs('#later-picker');
@@ -5275,6 +5443,7 @@
planningOwnerLogin = retainedPlanningLogin;
updatePlanningAvailability();
if (planningOwnerLogin) {
syncPendingTomorrow();
todaySync.migrate(todayWork.read());
todaySync.flush();
laterSync.migrate(laterWork.read());
@@ -5285,6 +5454,7 @@
activeFlushLogin = contextIdentityFresh ? String(snapshot.context.user?.login || '').trim() : '';
if (activeFlushLogin) {
confirmedOwnerLogin = activeFlushLogin;
timerView.render();
restoreReleaseReceipt();
updateDeliveryReceiptControls();
interruptionPrompt.restore();
@@ -7632,6 +7802,36 @@
qs('#refresh').addEventListener('click', load);
qs('#plan-today').addEventListener('click', event => openPlanToday(event.currentTarget));
qs('#plan-tomorrow').addEventListener('click', event => openTomorrowPlanner(event.currentTarget));
qs('#keep-phone-tomorrow').addEventListener('click', async () => {
const keep = qs('#keep-phone-tomorrow');
const use = qs('#use-server-tomorrow');
keep.disabled = true;
use.disabled = true;
qs('#tomorrow-conflict-status').textContent = 'Saving this phone’s plan…';
try {
const saved = await tomorrowPlan.keepLocal();
renderTomorrowQueueSummary(saved);
qs('#my-work-action-status').textContent = 'This phone’s Tomorrow plan is saved to your account. Today was not changed.';
closePlanToday();
} catch (error) {
const conflict = tomorrowPlan.conflict();
if (conflict) showTomorrowConflict(conflict);
qs('#tomorrow-conflict-status').textContent = error?.status === 409 ?
'Tomorrow changed again. Both latest plans are still preserved; choose again.' :
`${error.message || 'Tomorrow could not be saved.'} Both plans are still preserved.`;
} finally {
keep.disabled = false;
use.disabled = false;
}
});
qs('#use-server-tomorrow').addEventListener('click', () => {
const adopted = tomorrowPlan.useRemote();
if (!adopted) return;
renderTomorrowQueueSummary(adopted);
qs('#my-work-action-status').textContent = 'Saved account Tomorrow plan selected. Today was not changed.';
closePlanToday();
});
qs('#cancel-plan-today').addEventListener('click', closePlanToday);
qs('#plan-today-sheet').addEventListener('click', event => {
if (event.target === qs('#plan-today-sheet')) closePlanToday();
+30
View File
@@ -192,6 +192,7 @@
<button class="work-filter" data-work-filter="later" aria-pressed="false">Later <span data-work-count="later">0</span></button>
<button class="work-filter" data-work-filter="draft" aria-pressed="false">Drafts <span data-work-count="draft">0</span></button>
</div>
<button class="plan-tomorrow" id="plan-tomorrow" type="button">Plan Tomorrow</button>
<label class="milestone-lane" for="work-milestone-filter"><span class="small">Release lane</span>
<select class="work-milestone-filter" id="work-milestone-filter">
<option value="all">All milestones</option>
@@ -448,6 +449,26 @@
<div><h2 id="plan-today-title">Plan Today</h2><p class="small muted">Choose and order the work you want to finish next.</p></div>
<button id="cancel-plan-today" type="button">Cancel</button>
</div>
<section class="tomorrow-conflict-review" id="tomorrow-conflict-review" aria-labelledby="tomorrow-conflict-title" hidden>
<div class="small">Cross-device change</div>
<h3 id="tomorrow-conflict-title">Choose which Tomorrow plan to keep</h3>
<p class="small muted">Both plans are preserved until one choice succeeds. Today will not change.</p>
<div class="tomorrow-conflict-plans">
<section aria-labelledby="tomorrow-conflict-phone-title">
<h4 id="tomorrow-conflict-phone-title">This phone</h4>
<div id="tomorrow-conflict-phone-plan"></div>
</section>
<section aria-labelledby="tomorrow-conflict-server-title">
<h4 id="tomorrow-conflict-server-title">Saved on your account</h4>
<div id="tomorrow-conflict-server-plan"></div>
</section>
</div>
<div class="tomorrow-conflict-actions">
<button id="keep-phone-tomorrow" type="button">Keep this phone’s plan</button>
<button id="use-server-tomorrow" type="button">Use saved account plan</button>
</div>
<div class="small tomorrow-conflict-status" id="tomorrow-conflict-status" role="status" aria-live="assertive"></div>
</section>
<nav class="mobile-plan-today-nav" aria-label="Plan Today sections">
<button type="button" data-plan-today-section="fit" aria-current="location">Fit</button>
<button type="button" data-plan-today-section="today">Today</button>
@@ -1655,12 +1676,19 @@
</section>
<section class="mobile-today-hud" data-mobile-today-hud aria-label="Active Today session" hidden>
<div class="mobile-first-task-coach small" data-mobile-first-task-coach hidden>
<strong>Complete your first task</strong>
<span>Open it, then use Done &amp; next after a real outcome.</span>
</div>
<button class="mobile-today-summary" data-mobile-today-open type="button" aria-label="Open current Today item"></button>
<div class="small" data-work-session-progress aria-live="polite"></div>
<button data-mobile-today-complete type="button" hidden>Done &amp; next</button>
<button data-mobile-today-toggle data-work-session-timer-toggle type="button">Pause timer</button>
<button data-mobile-today-more type="button" aria-controls="mobile-today-actions" aria-haspopup="dialog">More</button>
</section>
<div class="mobile-first-task-receipt" id="mobile-first-task-receipt" role="status" aria-live="polite" hidden>
First task completed · continue Today
</div>
<dialog class="mobile-today-actions" id="mobile-today-actions" aria-modal="true" aria-labelledby="mobile-today-actions-title">
<section class="mobile-today-actions-panel">
<header><h2 id="mobile-today-actions-title">Today session</h2><button data-mobile-today-actions-close type="button">Close</button></header>
@@ -1802,6 +1830,7 @@
</section>
<div class="mobile-queue-list">
<button data-mobile-queue="today" type="button"><span><strong>Today</strong><small>Planned work</small></span><span data-mobile-queue-count="today">0</span></button>
<button data-mobile-queue="tomorrow" type="button"><span><strong>Tomorrow</strong><small id="mobile-tomorrow-summary" aria-live="polite">Nothing planned</small></span></button>
<button data-mobile-queue="agenda" type="button"><span><strong>Agenda</strong><small>Upcoming deadlines</small></span><span data-mobile-queue-count="agenda">0</span></button>
<button data-mobile-queue="delivery" type="button"><span><strong>Delivery</strong><small>Needs recovery</small></span><span data-mobile-queue-count="delivery">0</span></button>
<button data-mobile-queue="attention" type="button"><span><strong>Attention</strong><small>Needs a response</small></span><span data-mobile-queue-count="attention">0</span></button>
@@ -1911,6 +1940,7 @@
<script src="static/plan-today.js"></script>
<script src="static/plan-today-readiness.js"></script>
<script src="static/plan-today-preview.js"></script>
<script src="static/tomorrow-plan.js"></script>
<script src="static/today-sync.js"></script>
<script src="static/today-rollover.js"></script>
<script src="static/update-ownership.js"></script>
+44 -14
View File
@@ -9,6 +9,7 @@
isOnline: () => typeof navigator === 'undefined' || navigator.onLine,
mediaQuery: win?.matchMedia('(max-width: 600px)') || {matches:false},
eventTarget: win,
setTimer: (...args) => globalThis.setTimeout(...args),
sheet: doc?.querySelector('#mobile-first-task'),
title: doc?.querySelector('#mobile-first-task-title'),
findButton: doc?.querySelector('#mobile-first-task-find'),
@@ -16,6 +17,8 @@
setupButton: doc?.querySelector('#mobile-first-task-setup'),
closeButton: doc?.querySelector('#close-mobile-first-task'),
status: doc?.querySelector('#mobile-first-task-status'),
coach: doc?.querySelector('[data-mobile-first-task-coach]'),
receipt: doc?.querySelector('#mobile-first-task-receipt'),
isTodayActive: () => false,
onFind: () => doc?.querySelector('#find-work')?.click(),
onCreate: () => doc?.querySelector('#new-issue')?.click(),
@@ -32,22 +35,34 @@
return login ? prefix + login : '';
}
function completed() {
function state() {
const currentKey = key();
if (!currentKey) return false;
try { return options.storage.getItem(currentKey) === 'complete'; }
catch (_error) { return false; }
if (!currentKey) return '';
try { return options.storage.getItem(currentKey) || ''; }
catch (_error) { return ''; }
}
function store(value) {
const currentKey = key();
const current = state();
if (!currentKey || current === value || current === 'complete') return false;
try {
options.storage.setItem(currentKey, value);
return true;
} catch (_error) { return false; }
}
function adoptRemote(value) {
return ['coaching', 'complete'].includes(value) && store(value);
}
function required() {
return Boolean(options.mediaQuery.matches && account() && !options.isTodayActive() && !completed());
return Boolean(options.mediaQuery.matches && account() && !options.isTodayActive() && !state());
}
function markComplete() {
const currentKey = key();
if (!currentKey) return;
try { options.storage.setItem(currentKey, 'complete'); }
catch (_error) {}
function renderCoach() {
if (!options.coach) return;
options.coach.hidden = !(options.mediaQuery.matches && state() === 'coaching' && options.isTodayActive());
}
function render() {
@@ -72,16 +87,30 @@
}
function refresh() {
if (account() && options.isTodayActive() && !completed()) {
markComplete();
if (account() && options.isTodayActive() && state() !== 'complete') {
store('coaching');
if (options.sheet.open) options.sheet.close();
return 'completed';
renderCoach();
return 'coaching';
}
renderCoach();
if (options.sheet.open) render();
if (required() && options.hasWork()) return 'awaiting-start';
return required() ? 'required' : 'inactive';
}
function completeOutcome() {
if (state() !== 'coaching') return false;
store('complete');
options.eventTarget?.dispatchEvent?.(new CustomEvent('stackchain:first-task-complete'));
renderCoach();
if (options.receipt) {
options.receipt.hidden = false;
options.setTimer?.(() => { options.receipt.hidden = true; }, 6000);
}
return true;
}
function handoff(callback, requiresOnline = false) {
if (requiresOnline && !options.isOnline()) return;
if (options.sheet.open) options.sheet.close();
@@ -99,5 +128,6 @@
options.eventTarget?.addEventListener('offline', render);
}
return {required, open, refresh, render, start};
globalThis.stackchainFirstTaskCompleting = () => state() === 'coaching';
return {required, open, refresh, render, start, completeOutcome, adoptRemote};
});
+2 -1
View File
@@ -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-v123';
const CACHE = 'stackchain-dashboard-shell-v124';
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;
@@ -68,6 +68,7 @@ const SHELL = [
BASE + 'static/plan-today.js',
BASE + 'static/plan-today-readiness.js',
BASE + 'static/plan-today-preview.js',
BASE + 'static/tomorrow-plan.js',
BASE + 'static/today-sync.js',
BASE + 'static/today-rollover.js',
BASE + 'static/update-ownership.js',
+13 -1
View File
@@ -1,4 +1,5 @@
function createTodayCompletion({ todayWork, todaySync, workSession, refresh, warm, announce, advance = null,
completeActivation = () => globalThis.stackchainFirstTaskCompleting?.(),
now = Date.now, ttlMs = 10000, onOffer = null, onClear = null,
setTimer = globalThis.setTimeout, clearTimer = globalThis.clearTimeout,
undo = [globalThis.document?.getElementById('today-completion-undo'),
@@ -23,7 +24,18 @@ function createTodayCompletion({ todayWork, todaySync, workSession, refresh, war
announce(options.failureMessage || 'Could not update Today on this device. Try again.');
return false;
}
todaySync.enqueue('remove', todayWork.identity(item));
const operations = [
{action:'remove', item_id:identity},
...(completeActivation() ? [{action:'activate', item_id:'first-task', activation_state:'complete'}] : []),
];
const admitted = todaySync.enqueueBatch ? todaySync.enqueueBatch(operations) :
todaySync.enqueue('remove', identity);
if (!admitted) {
todayWork.restore?.(snapshot);
announce(options.admissionFailureMessage ||
'Device storage is full. Free space and try again.');
return false;
}
todaySync.flush();
refresh();
warm();
+65 -22
View File
@@ -61,12 +61,22 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
revision: plan.revision, ids: plan.ids,
capacity_minutes: plan.capacity_minutes ?? null, estimates: plan.estimates || {},
};
if (['coaching', 'complete'].includes(plan.first_task_state)) {
snapshot.first_task_state = plan.first_task_state;
}
if (plan.plan_date) {
snapshot.plan_date = plan.plan_date;
snapshot.timezone = plan.timezone || null;
}
try {
storage?.setItem(snapshotKey(), JSON.stringify(snapshot));
const login = String(getLogin?.() || '').trim().toLowerCase();
const activationKey = login && 'stackchain.first-task.v1:' + login;
const current = activationKey && storage?.getItem(activationKey);
const rank = {'': 0, coaching: 1, complete: 2};
if (activationKey && rank[snapshot.first_task_state] > (rank[current] || 0)) {
storage?.setItem(activationKey, snapshot.first_task_state);
}
} catch (_error) {
// A storage quota failure must not prevent the current tab from using server truth.
}
@@ -121,11 +131,14 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
discardedCount += 1;
continue;
}
const operation = record?.operation;
const valid = operation && typeof operation.operation_id === 'string' &&
['add', 'remove', 'move', 'configure', 'rollover'].includes(operation.action) &&
typeof operation.item_id === 'string' && Number.isFinite(Number(record.queued_at));
if (valid) records.push({ ...record, recordKey });
const operations = Array.isArray(record?.operations) ? record.operations : [record?.operation];
const valid = operations.length && operations.every(operation => operation &&
typeof operation.operation_id === 'string' &&
['add', 'remove', 'move', 'configure', 'rollover', 'activate'].includes(operation.action) &&
typeof operation.item_id === 'string') && Number.isFinite(Number(record.queued_at));
if (valid) operations.forEach((operation, index) => {
records.push({operation, queued_at:Number(record.queued_at) + index / 1000, recordKey});
});
else {
storage.removeItem(recordKey);
knownOperationKeys.delete(recordKey);
@@ -151,7 +164,7 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
? record.operation.base_revision : Math.max(0, savedRevision()),
}))
.filter(operation => operation && typeof operation.operation_id === 'string' &&
['add', 'remove', 'move', 'configure', 'rollover'].includes(operation.action) && typeof operation.item_id === 'string');
['add', 'remove', 'move', 'configure', 'rollover', 'activate'].includes(operation.action) && typeof operation.item_id === 'string');
} catch (_error) {
return [];
}
@@ -176,7 +189,25 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
return Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
}
function enqueue(action, itemId, direction = null) {
function saveOperations(operations, queuedAt = now()) {
const storageKey = key();
if (!storageKey || !storage) return false;
const batched = operations.length > 1;
const recordKey = storageKey + '.operation.' + encodeURIComponent(operations[0].operation_id);
try {
storage.setItem(recordKey, JSON.stringify(batched ?
{operations, queued_at:queuedAt} : {operation:operations[0], queued_at:queuedAt}));
knownOperationKeys.add(recordKey);
coordinator?.notify('today');
onStatus?.('pending');
return true;
} catch (_error) {
onStatus?.('error');
return false;
}
}
function enqueue(action, itemId, direction = null, fields = {}) {
const operations = pending();
if (action === 'remove' && operations.some(operation =>
operation.action === 'remove' && operation.item_id === itemId
@@ -186,20 +217,17 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
}
const operation = {
operation_id: operationId(), action, item_id: itemId, direction,
base_revision: Math.max(0, savedRevision()),
base_revision: Math.max(0, savedRevision()), ...fields,
};
const storageKey = key();
if (!storageKey || !storage) return false;
const recordKey = storageKey + '.operation.' + encodeURIComponent(operation.operation_id);
let saved = false;
try {
storage.setItem(recordKey, JSON.stringify({ operation, queued_at: now() + operations.length }));
knownOperationKeys.add(recordKey);
saved = true;
coordinator?.notify('today');
} catch (_error) { /* Report the persistence failure below. */ }
onStatus?.(saved ? 'pending' : 'error');
return saved;
return saveOperations([operation], now() + operations.length);
}
function enqueueBatch(specifications) {
const operations = specifications.map(specification => ({
operation_id: operationId(), direction: specification.direction ?? null,
base_revision: Math.max(0, savedRevision()), ...specification,
}));
return saveOperations(operations);
}
function enqueueConfiguration(capacityMinutes, estimates) {
@@ -223,6 +251,15 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
}
}
function enqueueActivation(state) {
if (!['coaching', 'complete'].includes(state)) return false;
const rank = {coaching: 1, complete: 2};
const queued = pending().filter(operation => operation.action === 'activate');
if (queued.some(operation => rank[operation.activation_state] >= rank[state])) return true;
queued.forEach(operation => removeOperation(operation.operation_id));
return enqueue('activate', 'first-task', null, {activation_state: state});
}
function enqueueRollover(proposed) {
if (!proposed || proposed.action !== 'rollover') return false;
const operation = {
@@ -266,7 +303,10 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
let operations = pending();
let plan;
let hadConflict = false;
if (!operations.length) plan = await fetchJson('api/v1/today');
if (!operations.length) {
plan = await fetchJson('api/v1/today');
operations = pending();
}
while (operations.length) {
if (key() !== ownerKey) return false;
const batch = operations.slice(0, 50);
@@ -323,6 +363,9 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
function startLifecycle({ window: windowObject, document: documentObject }) {
windowObject?.addEventListener?.('online', flush);
windowObject?.addEventListener?.('stackchain:first-task-complete', () => {
if (enqueueActivation('complete')) flush();
});
documentObject?.addEventListener?.('visibilitychange', () =>
documentObject.hidden ? false : flush()
);
@@ -332,7 +375,7 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
if (change.queue === 'today' && pending().length) flush();
});
return { enqueue, enqueueConfiguration, enqueueRollover, migrate, flush, pending, startLifecycle };
return { enqueue, enqueueBatch, enqueueConfiguration, enqueueActivation, enqueueRollover, migrate, flush, pending, startLifecycle };
}
if (typeof module !== 'undefined' && module.exports) module.exports = createTodaySync;
+171
View File
@@ -0,0 +1,171 @@
function createTomorrowPlan({fetchJson,localDate,timeZone,storage,getLogin}={}) {
let plan={revision:0,ids:[],capacity_minutes:null,estimates:{}};
let flushing=null;
let lastConflict=null;
const storagePrefix='stackchain.tomorrow-sync.v1.';
const state=()=>({...plan,ids:[...plan.ids],estimates:{...plan.estimates}});
function storageKey() {
const login=String(getLogin?.()||'').trim().toLowerCase();
return login?storagePrefix+encodeURIComponent(login):'';
}
function pending() {
const key=storageKey();
if(!key||!storage) return false;
try {
const value=JSON.parse(storage.getItem(key)||'null');
return Number.isInteger(value?.base_revision)&&Array.isArray(value?.ids)?
{...value,ids:[...value.ids],estimates:{...(value.estimates||{})},sync_pending:true}:false;
} catch (_error) { return false; }
}
function adopt(value) {
if (!Number.isInteger(value?.revision)||!Array.isArray(value?.ids)) return false;
plan={revision:value.revision,ids:[...value.ids],capacity_minutes:value.capacity_minutes??null,
estimates:{...(value.estimates||{})},...(value.plan_date?{plan_date:value.plan_date,timezone:value.timezone||null}:{})};
return state();
}
function nextLocalDate() {
const [y,m,d]=localDate().split('-').map(Number);
return new Date(Date.UTC(y,m-1,d+1)).toISOString().slice(0,10);
}
async function load(){
const queued=pending();
return queued?(plan={...queued},state()):adopt(await fetchJson('api/v1/tomorrow'));
}
function stage(value) {
const key=storageKey();
if(!key||!storage) return false;
const queued={base_revision:plan.revision,revision:plan.revision,ids:[...(value.ids||[])],
capacity_minutes:value.capacity_minutes??null,estimates:{...(value.estimates||{})},
plan_date:nextLocalDate(),timezone:timeZone(),sync_pending:true};
try { storage.setItem(key,JSON.stringify(queued)); }
catch (_error) { return false; }
lastConflict=null;
plan=queued;
return state();
}
function deliveryBody(value) {
return {base_revision:value.base_revision,ids:[...value.ids],
capacity_minutes:value.capacity_minutes??null,estimates:{...(value.estimates||{})},
plan_date:value.plan_date,timezone:value.timezone};
}
function flush() {
if(flushing) return flushing;
const queued=pending();
const key=storageKey();
if(!queued||!key) return Promise.resolve(false);
const body=deliveryBody(queued);
flushing=fetchJson('api/v1/tomorrow',{method:'PUT',headers:{'Content-Type':'application/json'},
body:JSON.stringify(body)}).then(saved=>{
const current=pending();
if(current&&JSON.stringify(deliveryBody(current))===JSON.stringify(body)) storage.removeItem(key);
if(!pending()) adopt(saved);
return saved;
}).catch(async error=>{
if(error?.status===409) {
const remote=await fetchJson('api/v1/tomorrow');
lastConflict={key,local:pending(),remote:{...remote,ids:[...remote.ids],estimates:{...(remote.estimates||{})}}};
}
throw error;
}).finally(()=>{flushing=null;});
return flushing;
}
async function keepLocal() {
if(!lastConflict||lastConflict.key!==storageKey()) return false;
const conflictKey=lastConflict.key;
const local={...lastConflict.local,ids:[...lastConflict.local.ids],estimates:{...lastConflict.local.estimates}};
const body=deliveryBody({...local,base_revision:lastConflict.remote.revision});
try {
const saved=await fetchJson('api/v1/tomorrow',{method:'PUT',headers:{'Content-Type':'application/json'},
body:JSON.stringify(body)});
const current=pending();
if(current&&JSON.stringify(deliveryBody(current))===JSON.stringify(deliveryBody(local))) storage.removeItem(storageKey());
if(!pending()) adopt(saved);
lastConflict=null;
return saved;
} catch(error) {
if(error?.status===409) {
const remote=await fetchJson('api/v1/tomorrow');
lastConflict={key:conflictKey,local,remote:{...remote,ids:[...remote.ids],estimates:{...(remote.estimates||{})}}};
}
throw error;
}
}
function useRemote() {
if(!lastConflict||lastConflict.key!==storageKey()) return false;
const remote=lastConflict.remote;
const key=storageKey();
if(key&&storage) storage.removeItem(key);
const adopted=adopt(remote);
lastConflict=null;
return adopted;
}
async function save(value) {
const body={base_revision:plan.revision,ids:[...(value.ids||[])],
capacity_minutes:value.capacity_minutes??null,estimates:{...(value.estimates||{})},
plan_date:nextLocalDate(),timezone:timeZone()};
return adopt(await fetchJson('api/v1/tomorrow',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}));
}
async function promote(today_revision) {
if (pending()||!plan.plan_date||plan.plan_date>localDate()||!plan.ids.length) return false;
const promotion_id=`tomorrow-${plan.plan_date}-r${plan.revision}`;
return fetchJson('api/v1/tomorrow/promote',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({promotion_id,tomorrow_revision:plan.revision,today_revision})});
}
function millisecondsUntilNextDay() {
const now=Date.now();
const zone=timeZone();
let formatter;
try {
formatter=new Intl.DateTimeFormat('en-CA',{timeZone:zone,year:'numeric',month:'2-digit',day:'2-digit',
hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'});
} catch (_error) {
const next=new Date(now);
next.setHours(24,0,0,250);
return Math.max(1,next.getTime()-now);
}
const zoned=value=>Object.fromEntries(formatter.formatToParts(new Date(value))
.filter(part=>part.type!=='literal').map(part=>[part.type,Number(part.value)]));
const current=zoned(now);
const targetWall=Date.UTC(current.year,current.month-1,current.day+1);
let candidate=targetWall;
for(let attempt=0;attempt<2;attempt+=1){
const parts=zoned(candidate);
const offset=Date.UTC(parts.year,parts.month-1,parts.day,parts.hour,parts.minute,parts.second)-candidate;
candidate=targetWall-offset;
}
return Math.max(1,candidate-now+250);
}
function summary(value=plan) {
const ids=Array.isArray(value?.ids)?value.ids:[];
const suffix=value?.sync_pending?' · sync pending':'';
if(!ids.length) return 'Nothing planned'+suffix;
const label=`${ids.length} planned`;
const estimates=value.estimates||{};
const estimated=ids.reduce((total,id)=>total+(Number(estimates[id])||0),0);
const capacity=Number(value.capacity_minutes)||0;
return (estimated&&capacity?`${label} · ${estimated} of ${capacity} min`:label)+suffix;
}
function startLifecycle({windowObject,documentObject,check,setTimer=setTimeout,clearTimer=clearTimeout,
nextDelay=millisecondsUntilNextDay}={}) {
let flight=null;
let timer=null;
const schedule=()=>{
if(timer!==null) clearTimer(timer);
timer=setTimer(run,nextDelay());
};
function run(){
if(!flight) flight=Promise.resolve().then(check).finally(()=>{flight=null;schedule();});
return flight;
}
windowObject?.addEventListener?.('online',run);
documentObject?.addEventListener?.('visibilitychange',()=>documentObject.hidden?false:run());
run();
return {run,stop(){if(timer!==null)clearTimer(timer);timer=null;}};
}
function conflict() {
return lastConflict?.key===storageKey()?{local:{...lastConflict.local,ids:[...lastConflict.local.ids],estimates:{...lastConflict.local.estimates}},
remote:{...lastConflict.remote,ids:[...lastConflict.remote.ids],estimates:{...lastConflict.remote.estimates}}}:null;
}
return {adopt,load,save,stage,pending,flush,conflict,keepLocal,useRemote,promote,state,summary,nextLocalDate,startLifecycle};
}
if(typeof module!=='undefined'&&module.exports)module.exports=createTomorrowPlan;
+8 -6
View File
@@ -11,16 +11,18 @@ async function loadWorkspace({
window?.addEventListener('online', captureOnline);
const status = document.querySelector('#my-work-action-status');
const retryButton = document.querySelector('#retry-workspace');
const url = document.querySelector(
'meta[name="stackchain-feature-today-timer"]'
)?.content || '';
const urls = {'today-timer':url};
const urls = Object.fromEntries(['today-timer', 'planning'].map(name => [name,
document.querySelector(`meta[name="stackchain-feature-${name}"]`)?.content || ''
]));
const originalUrls = {...urls};
const loader = createLoader({document, urls});
let attempts = 0;
const load = () => {
if (attempts++) urls['today-timer'] = url + '?retry=' + attempts;
return loader.load('today-timer');
if (attempts++) Object.keys(urls).forEach(name => {
urls[name] = originalUrls[name] + '?retry=' + attempts;
});
return Promise.all(Object.keys(urls).map(name => loader.load(name)));
};
const waitForRecovery = () => new Promise(resolve => {
if (status) status.textContent = 'Workspace unavailable. Reconnect or retry.';
+7 -2
View File
@@ -33,10 +33,15 @@ FEATURE_SOURCES = {
"static/device-storage.js", "static/mobile-device-setup.js",
),
"security-center": ("static/security-center.js",),
"planning": (
"static/plan-today.js", "static/plan-today-readiness.js",
"static/plan-today-preview.js", "static/today-rollover.js",
"static/tomorrow-plan.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-plan-today-nav.js", "static/mobile-find-work-nav.js", "static/mobile-pull-refresh.js", "static/live-data-status.js",
"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",
"static/today-completion.js", "static/card-planning.js", "static/work-detail-position.js", "static/work-route.js", "static/commands.js", "static/saved-searches.js", "static/task-overlay-history.js", "static/search-preview.js", "static/mobile-search-preview-nav.js", "static/search-reply-draft-store.js", "static/conversation-reply-draft-store.js", "static/conversation-photo-drafts.js", "static/search-defer.js", "static/mobile-search-viewport.js", "static/agenda-replan.js", "static/agenda-calendar.js", "static/my-work.js", "static/protect-today.js", "static/mobile-today-command-bar.js", "static/mobile-task-dock.js", "static/mobile-first-task.js", "static/mobile-work-entry.js", "static/mobile-queue-launcher.js", "static/mobile-delivery-recovery.js", "static/mobile-start-day.js", "static/update-triage-session.js", "static/update-review-handoff.js", "static/update-triage-launcher.js", "static/update-triage-gesture.js", "static/notification-undo.js", "static/today-timer.js", "static/today-break.js", "static/today-progress.js", "static/today-lock-screen.js", "static/today-session-sync.js", "static/today-recap.js", "static/today-wrap-up.js", "static/today-summary.js", "static/today-handoff.js",
"static/today-rollover.js", "static/later-work.js", "static/detail-defer.js", "static/later-picker.js", "static/drafts.js", "static/unfiled-captures.js", "static/unfiled-draft-sync.js",
"static/later-work.js", "static/detail-defer.js", "static/later-picker.js", "static/drafts.js", "static/unfiled-captures.js", "static/unfiled-draft-sync.js",
"static/assign-and-start.js", "static/filed-claim.js", "static/queue-today.js", "static/create-and-start.js",
"static/draft-filing-session.js", "static/draft-capacity-dialog.js", "static/work-selection.js",
"static/today-work.js", "static/today-sync.js", "static/pick-work.js", "static/batch-find-work.js",
+104 -3
View File
@@ -72,7 +72,10 @@ from src.unfiled_draft_store import (
from src.security_event_store import SecurityEventStore, SecurityEventStoreError
from src.suggestion_engine import compute
from src.later_store import LaterStore
from src.today_store import TodayPlanFull, TodaySessionConflict, TodayStore
from src.today_store import (
TodayPlanFull, TodayPromotionConflict, TodaySessionConflict, TodayStore,
TomorrowPlanConflict, TomorrowPlanNotDue,
)
from src.state_encryption import PrivateStateEncryptionError
from src.views import FRONTEND_BUILD, router as frontend_router
@@ -553,7 +556,7 @@ class NotificationReadBatch(BaseModel):
class TodayOperation(BaseModel):
operation_id: str = Field(min_length=1, max_length=100)
action: Literal["add", "remove", "move", "configure", "rollover"]
action: Literal["add", "remove", "move", "configure", "rollover", "activate"]
item_id: str = Field(min_length=1, max_length=500)
direction: Literal["up", "down"] | None = None
base_revision: int | None = Field(default=None, ge=0)
@@ -562,6 +565,7 @@ class TodayOperation(BaseModel):
plan_date: str | None = Field(default=None, min_length=10, max_length=10)
timezone: str | None = Field(default=None, min_length=1, max_length=100)
ids: list[str] = Field(default_factory=list, max_length=5)
activation_state: Literal["coaching", "complete"] | None = None
@model_validator(mode="after")
def validate_action_fields(self):
@@ -580,6 +584,11 @@ class TodayOperation(BaseModel):
raise ValueError("rollover IDs must be unique")
elif self.plan_date is not None or self.timezone is not None or self.ids:
raise ValueError("date, timezone, and IDs are only valid for rollover")
if self.action == "activate":
if self.item_id != "first-task" or self.activation_state is None:
raise ValueError("activate requires a first-task activation state")
elif self.activation_state is not None:
raise ValueError("activation state is only valid for activate")
if any(not item_id or len(item_id) > 500 or minutes < 5 or minutes > 1440
for item_id, minutes in self.estimates.items()):
raise ValueError("estimates must use bounded item IDs and minutes")
@@ -591,6 +600,8 @@ class TodayOperation(BaseModel):
data.pop("plan_date", None)
data.pop("timezone", None)
data.pop("ids", None)
if self.action != "activate":
data.pop("activation_state", None)
return data
@@ -650,6 +661,32 @@ class TodayOperationBatch(BaseModel):
operations: list[TodayOperation] = Field(min_length=1, max_length=50)
class TomorrowPlanUpdate(BaseModel):
base_revision: int = Field(ge=0)
ids: list[str] = Field(max_length=5)
capacity_minutes: int | None = Field(default=None, ge=15, le=1440)
estimates: dict[str, int] = Field(default_factory=dict, max_length=5)
plan_date: str = Field(min_length=10, max_length=10)
timezone: str = Field(min_length=1, max_length=100)
@model_validator(mode="after")
def validate_plan(self):
if len(set(self.ids)) != len(self.ids):
raise ValueError("Tomorrow IDs must be unique")
if any(not item_id or len(item_id) > 500 for item_id in self.ids):
raise ValueError("Tomorrow IDs must be bounded")
if any(not item_id or len(item_id) > 500 or minutes < 5 or minutes > 1440
for item_id, minutes in self.estimates.items()):
raise ValueError("estimates must use bounded item IDs and minutes")
return self
class TomorrowPromotion(BaseModel):
promotion_id: str = Field(min_length=1, max_length=100)
tomorrow_revision: int = Field(ge=0)
today_revision: int = Field(ge=0)
class LaterOperationBatch(BaseModel):
operations: list[LaterOperation] = Field(min_length=1, max_length=50)
@@ -1354,7 +1391,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/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/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 (
@@ -2582,6 +2619,70 @@ async def update_today_plan(payload: TodayOperation | TodayOperationBatch):
)
@app.get("/api/v1/tomorrow")
async def get_tomorrow_plan():
login = await _confirmed_login()
try:
return await asyncio.to_thread(_today_store().get_tomorrow, login)
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Tomorrow synchronization is unavailable",
headers={"Retry-After": "1"},
)
@app.put("/api/v1/tomorrow")
async def replace_tomorrow_plan(payload: TomorrowPlanUpdate):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_today_store().replace_tomorrow, login, **payload.model_dump()
)
except TomorrowPlanConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "tomorrow_changed", "snapshot": error.snapshot},
)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Tomorrow synchronization is unavailable",
headers={"Retry-After": "1"},
)
@app.post("/api/v1/tomorrow/promote")
async def promote_tomorrow_plan(payload: TomorrowPromotion):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_today_store().promote_tomorrow, login, **payload.model_dump()
)
except TomorrowPlanConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "tomorrow_changed", "snapshot": error.snapshot},
)
except TodayPromotionConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "today_changed", "today": error.today},
)
except TomorrowPlanNotDue as error:
raise HTTPException(
status_code=409,
detail={"code": "tomorrow_not_due", "plan_date": error.plan_date},
)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Tomorrow promotion is unavailable",
headers={"Retry-After": "1"},
)
@app.get("/api/v1/today/session")
async def get_today_session():
login = await _confirmed_login()
+214 -5
View File
@@ -3,8 +3,9 @@
import json
import sqlite3
import time
from datetime import date
from datetime import date, datetime
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
@@ -22,6 +23,30 @@ class TodaySessionConflict(ValueError):
self.session = session
class TomorrowPlanConflict(ValueError):
"""Raised when Tomorrow was edited from an obsolete revision."""
def __init__(self, snapshot: dict):
super().__init__("Tomorrow plan changed on another device")
self.snapshot = snapshot
class TomorrowPlanNotDue(ValueError):
"""Raised when Tomorrow is promoted before its saved local date."""
def __init__(self, plan_date: str):
super().__init__("Tomorrow plan is not due")
self.plan_date = plan_date
class TodayPromotionConflict(ValueError):
"""Raised when rollover would overwrite a changed Today plan."""
def __init__(self, today: dict):
super().__init__("Today changed before Tomorrow could be promoted")
self.today = today
class TodayStore:
def __init__(
self,
@@ -50,7 +75,7 @@ class TodayStore:
def _initialize(self) -> None:
connection = connect_private_sqlite(self.path, timeout=self.timeout)
if connection.execute("PRAGMA user_version").fetchone()[0] >= 3:
if connection.execute("PRAGMA user_version").fetchone()[0] >= 4:
connection.close()
return
connection.execute("PRAGMA journal_mode=WAL")
@@ -137,7 +162,16 @@ class TodayStore:
session_columns = {row[1] for row in connection.execute("PRAGMA table_info(today_sessions)")}
if "break_deadline_at" not in session_columns:
connection.execute("ALTER TABLE today_sessions ADD COLUMN break_deadline_at INTEGER")
connection.execute("PRAGMA user_version = 3")
connection.execute(
"CREATE TABLE IF NOT EXISTS tomorrow_plans ("
"login TEXT PRIMARY KEY, revision INTEGER NOT NULL, payload TEXT NOT NULL)"
)
connection.execute(
"CREATE TABLE IF NOT EXISTS tomorrow_promotions ("
"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 = 4")
connection.commit()
connection.close()
@@ -180,6 +214,7 @@ class TodayStore:
capacity_minutes = payload.get("capacity_minutes")
plan_date = payload.get("plan_date")
timezone = payload.get("timezone")
first_task_state = payload.get("first_task_state", "")
else:
legacy = True
ids = json.loads(row[1])
@@ -187,6 +222,7 @@ class TodayStore:
capacity_minutes = row[2]
plan_date = row[4] if len(row) > 4 else None
timezone = row[5] if len(row) > 5 else None
first_task_state = ""
if not isinstance(ids, list) or not isinstance(estimates, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
snapshot = {
@@ -198,6 +234,8 @@ class TodayStore:
if plan_date:
snapshot["plan_date"] = plan_date
snapshot["timezone"] = timezone
if first_task_state in {"coaching", "complete"}:
snapshot["first_task_state"] = first_task_state
return snapshot, legacy
def _sealed_plan(self, login: str, snapshot: dict) -> str:
@@ -207,6 +245,7 @@ class TodayStore:
"estimates": snapshot["estimates"],
"plan_date": snapshot.get("plan_date"),
"timezone": snapshot.get("timezone"),
"first_task_state": snapshot.get("first_task_state", ""),
}, binding=f"plan:{login}")
def get(self, login: str) -> dict:
@@ -226,6 +265,161 @@ class TodayStore:
)
return snapshot
@staticmethod
def _empty_tomorrow(revision: int = 0) -> dict:
return {"revision": revision, "ids": [], "capacity_minutes": None, "estimates": {}}
def _tomorrow_snapshot(self, row, login: str) -> dict:
if row is None:
return self._empty_tomorrow()
payload, _legacy = self._cipher.open(row[1], binding=f"tomorrow:{login}")
if not isinstance(payload, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
snapshot = {"revision": int(row[0]), **payload}
if not isinstance(snapshot.get("ids"), list) or not isinstance(snapshot.get("estimates"), dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
return snapshot
def get_tomorrow(self, login: str) -> dict:
login = self._normalize_login(login)
with self._connect() as connection:
row = connection.execute(
"SELECT revision, payload FROM tomorrow_plans WHERE login = ?", (login,)
).fetchone()
return self._tomorrow_snapshot(row, login)
def _normalize_tomorrow(
self, *, ids: list[str], capacity_minutes: int | None,
estimates: dict[str, int], plan_date: str, timezone: str,
) -> dict:
try:
if date.fromisoformat(plan_date or "").isoformat() != plan_date:
raise ValueError
except (TypeError, ValueError):
raise ValueError("plan_date must be an ISO calendar date") from None
if not isinstance(timezone, str) or not timezone.strip() or len(timezone) > 100:
raise ValueError("timezone is required and bounded")
timezone = timezone.strip()
try:
ZoneInfo(timezone)
except (ZoneInfoNotFoundError, ValueError):
raise ValueError("timezone must be a valid IANA timezone") from None
if not isinstance(ids, list) or len(ids) > self.limit or any(
not isinstance(item_id, str) or not item_id or len(item_id) > 500 for item_id in ids
):
raise ValueError("Tomorrow IDs are invalid or exceed the plan limit")
if len(set(ids)) != len(ids):
raise ValueError("Tomorrow IDs must be unique")
if capacity_minutes is not None and (
not isinstance(capacity_minutes, int) or isinstance(capacity_minutes, bool)
or capacity_minutes < 15 or capacity_minutes > 1440
):
raise ValueError("capacity_minutes must be between 15 and 1440")
if not isinstance(estimates, dict):
raise ValueError("estimates must be an object")
normalized_estimates = {}
for item_id, minutes in estimates.items():
if item_id not in ids:
continue
if not isinstance(minutes, int) or isinstance(minutes, bool) or minutes < 5 or minutes > 1440:
raise ValueError("estimate minutes must be between 5 and 1440")
normalized_estimates[item_id] = minutes
return {
"ids": list(ids), "capacity_minutes": capacity_minutes,
"estimates": normalized_estimates, "plan_date": plan_date,
"timezone": timezone.strip(),
}
def replace_tomorrow(self, login: str, *, base_revision: int, **plan) -> dict:
login = self._normalize_login(login)
if not isinstance(base_revision, int) or isinstance(base_revision, bool) or base_revision < 0:
raise ValueError("base_revision must be a non-negative integer")
normalized = self._normalize_tomorrow(**plan)
with self._connect() as connection:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"SELECT revision, payload FROM tomorrow_plans WHERE login = ?", (login,)
).fetchone()
current = self._tomorrow_snapshot(row, login)
if current["revision"] != base_revision:
raise TomorrowPlanConflict(current)
snapshot = {"revision": base_revision + 1, **normalized}
sealed = self._cipher.seal(normalized, binding=f"tomorrow:{login}")
connection.execute(
"INSERT INTO tomorrow_plans(login, revision, payload) VALUES (?, ?, ?) "
"ON CONFLICT(login) DO UPDATE SET revision=excluded.revision, payload=excluded.payload",
(login, snapshot["revision"], sealed),
)
return snapshot
def promote_tomorrow(
self, login: str, *, promotion_id: str, tomorrow_revision: int, today_revision: int,
) -> dict:
login = self._normalize_login(login)
if not isinstance(promotion_id, str) or not promotion_id.strip() or len(promotion_id) > 100:
raise ValueError("promotion_id is required and bounded")
promotion_id = promotion_id.strip()
with self._connect() as connection:
connection.execute("BEGIN IMMEDIATE")
receipt = connection.execute(
"SELECT result FROM tomorrow_promotions WHERE login = ? AND promotion_id = ?",
(login, promotion_id),
).fetchone()
if receipt:
result, _legacy = self._cipher.open(
receipt[0], binding=f"tomorrow-promotion:{login}:{promotion_id}"
)
if not isinstance(result, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
return result
tomorrow_row = connection.execute(
"SELECT revision, payload FROM tomorrow_plans WHERE login = ?", (login,)
).fetchone()
tomorrow = self._tomorrow_snapshot(tomorrow_row, login)
if tomorrow["revision"] != tomorrow_revision or not tomorrow.get("plan_date"):
raise TomorrowPlanConflict(tomorrow)
local_date = datetime.fromtimestamp(
self.clock(), ZoneInfo(tomorrow["timezone"])
).date().isoformat()
if local_date < tomorrow["plan_date"]:
raise TomorrowPlanNotDue(tomorrow["plan_date"])
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)
if today["revision"] != today_revision:
raise TodayPromotionConflict(today)
result = {"revision": today_revision + 1, **{
key: tomorrow[key] for key in
("ids", "capacity_minutes", "estimates", "plan_date", "timezone")
}}
sealed_today = self._sealed_plan(login, result)
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, result["revision"], sealed_today),
)
empty = self._empty_tomorrow(tomorrow_revision + 1)
sealed_empty = self._cipher.seal(
{key: empty[key] for key in ("ids", "capacity_minutes", "estimates")},
binding=f"tomorrow:{login}",
)
connection.execute(
"UPDATE tomorrow_plans SET revision = ?, payload = ? WHERE login = ?",
(empty["revision"], sealed_empty, login),
)
sealed_result = self._cipher.seal(
result, binding=f"tomorrow-promotion:{login}:{promotion_id}"
)
connection.execute(
"INSERT INTO tomorrow_promotions(login, promotion_id, result, created_at) VALUES (?, ?, ?, ?)",
(login, promotion_id, sealed_result, self.clock()),
)
return result
@staticmethod
def _empty_session() -> dict:
return {
@@ -598,6 +792,7 @@ class TodayStore:
"ids": ids, "capacity_minutes": snapshot["capacity_minutes"],
"estimates": estimates, "plan_date": snapshot.get("plan_date"),
"timezone": snapshot.get("timezone"),
"first_task_state": snapshot.get("first_task_state", ""),
})
if row is None:
connection.execute(
@@ -621,6 +816,8 @@ class TodayStore:
if snapshot.get("plan_date"):
result["plan_date"] = snapshot["plan_date"]
result["timezone"] = snapshot["timezone"]
if snapshot.get("first_task_state"):
result["first_task_state"] = snapshot["first_task_state"]
return result
def apply_batch(self, login: str, operations: list[dict]) -> dict:
@@ -638,6 +835,7 @@ class TodayStore:
estimates = dict(snapshot["estimates"])
plan_date = snapshot.get("plan_date")
timezone = snapshot.get("timezone")
first_task_state = snapshot.get("first_task_state", "")
revision = snapshot["revision"]
accepted: list[str] = []
duplicates: list[str] = []
@@ -650,7 +848,7 @@ class TodayStore:
direction = operation.get("direction")
if not operation_id or not item_id:
raise ValueError("operation_id and item_id are required")
if action not in {"add", "remove", "move", "configure", "rollover"}:
if action not in {"add", "remove", "move", "configure", "rollover", "activate"}:
raise ValueError("unsupported Today action")
if action == "move" and direction not in {"up", "down"}:
raise ValueError("move direction must be up or down")
@@ -667,7 +865,7 @@ class TodayStore:
base_revision = snapshot["revision"]
if not isinstance(base_revision, int) or isinstance(base_revision, bool) or base_revision < 0:
raise ValueError("base_revision must be a non-negative integer")
if base_revision < snapshot["revision"]:
if action != "activate" and base_revision < snapshot["revision"]:
self._record_operation(connection, login, operation_id)
rejected.append({"operation_id": operation_id, "reason": "stale_intent"})
continue
@@ -714,6 +912,14 @@ class TodayStore:
changed = capacity_minutes != proposed_capacity or estimates != normalized_estimates
capacity_minutes = proposed_capacity
estimates = normalized_estimates
elif action == "activate":
proposed_state = operation.get("activation_state")
if item_id != "first-task" or proposed_state not in {"coaching", "complete"}:
raise ValueError("first-task activation state is invalid")
rank = {"": 0, "coaching": 1, "complete": 2}
changed = rank[proposed_state] > rank[first_task_state]
if changed:
first_task_state = proposed_state
else:
proposed_date = operation.get("plan_date")
proposed_timezone = operation.get("timezone")
@@ -764,6 +970,7 @@ class TodayStore:
sealed = self._sealed_plan(login, {
"ids": ids, "capacity_minutes": capacity_minutes, "estimates": estimates,
"plan_date": plan_date, "timezone": timezone,
"first_task_state": first_task_state,
})
if row is None:
connection.execute(
@@ -789,4 +996,6 @@ class TodayStore:
if plan_date:
result["plan_date"] = plan_date
result["timezone"] = timezone
if first_task_state:
result["first_task_state"] = first_task_state
return result
@@ -64,6 +64,45 @@ def test_release_artifact_guides_an_empty_mobile_account_to_first_work(
expect(page.locator("#mobile-first-task-status")).to_contain_text("Create a task now")
expect(page.locator("#mobile-first-task-create")).to_be_enabled()
expect(page.locator("#mobile-first-task-create")).to_be_focused()
page.locator("#close-mobile-first-task").click()
context.set_offline(False)
page.evaluate(
"""() => {
document.querySelector('[data-mobile-today-hud]').hidden = false;
localStorage.setItem('stackchain.first-task.v1:timmy', 'coaching');
window.firstTaskOutcomeProbe = createMobileFirstTask({
getLogin: () => 'timmy', hasWork: () => true, isTodayActive: () => true,
});
return window.firstTaskOutcomeProbe.refresh();
}"""
)
coach = page.locator("[data-mobile-first-task-coach]")
expect(coach).to_be_visible()
expect(coach).to_contain_text("Complete your first task")
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
assert page.evaluate("window.firstTaskOutcomeProbe.completeOutcome()") is True
expect(page.locator("#mobile-first-task-receipt")).to_be_visible()
expect(coach).to_be_hidden()
expect(page.locator("#today-sync-status")).to_contain_text("Today saved to account")
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
fresh_context = browser.new_context(
viewport={"width": width, "height": height}, ignore_https_errors=True
)
fresh_page = fresh_context.new_page()
fresh_page.goto(origin + "/", wait_until="networkidle")
fresh_page.locator('input[name="device_label"]').fill("Replacement release phone")
fresh_page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
fresh_page.locator("#submit-sign-in").click()
fresh_page.wait_for_url(origin + "/", wait_until="networkidle")
expect(fresh_page.locator("#my-work-status")).to_contain_text("No assigned work")
assert fresh_page.evaluate(
"localStorage.getItem('stackchain.first-task.v1:timmy')"
) == "complete"
fresh_page.locator('[data-mobile-task="work"]').click()
expect(fresh_page.locator("#mobile-first-task")).to_be_hidden()
fresh_context.close()
browser.close()
finally:
fake.shutdown()
@@ -180,6 +219,18 @@ def test_release_artifact_bootstraps_mobile_home_and_returns_from_insights(
bounds = control.bounding_box()
assert bounds and bounds["height"] >= 44
page.locator("#work-settings-toggle").click()
tomorrow = page.locator("#plan-tomorrow")
expect(tomorrow).to_be_visible()
tomorrow_bounds = tomorrow.bounding_box()
assert tomorrow_bounds and tomorrow_bounds["height"] >= 44
tomorrow.click()
expect(page.locator("#plan-today-sheet")).to_be_visible()
expect(page.locator("#plan-today-title")).to_have_text("Plan Tomorrow")
expect(page.locator("#save-and-start-today")).to_be_hidden()
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
page.locator("#cancel-plan-today").click()
page.locator('[data-mobile-task="queues"]').click()
delivery_queue = page.locator('[data-mobile-queue="delivery"]')
expect(delivery_queue).to_be_visible()
@@ -0,0 +1,142 @@
from __future__ import annotations
import json
import os
import threading
from pathlib import Path
import pytest
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
pytest.skip("packaged Tomorrow conflict 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_resolves_cross_device_tomorrow_conflicts_on_mobile(
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))
fake_thread = threading.Thread(target=fake.serve_forever, daemon=True)
fake_thread.start()
fake_url = f"http://127.0.0.1:{fake.server_port}"
put_bodies: list[dict] = []
try:
with release_server(archives[0], tmp_path, fake_url) as origin, sync_playwright() as playwright:
browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
context = browser.new_context(
viewport={"width": width, "height": height}, ignore_https_errors=True
)
page = context.new_page()
def tomorrow_route(route):
if route.request.method == "PUT":
body = json.loads(route.request.post_data or "{}")
put_bodies.append(body)
if body.get("base_revision") != 12:
route.fulfill(status=409, content_type="application/json", body='{"detail":"changed elsewhere"}')
return
route.fulfill(
status=200,
content_type="application/json",
body=json.dumps({"revision": 13, **body}),
)
return
route.fulfill(
status=200,
content_type="application/json",
body=json.dumps(
{
"revision": 12,
"ids": ["issue:acme/mobile:server:"],
"capacity_minutes": 60,
"estimates": {"issue:acme/mobile:server:": 30},
"plan_date": "2026-08-21",
"timezone": "UTC",
}
),
)
page.route("**/api/v1/tomorrow", tomorrow_route)
page.goto(origin + "/", wait_until="networkidle")
page.locator('input[name="device_label"]').fill("Tomorrow conflict 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")
def stage_phone_plan():
page.evaluate(
"""() => {
localStorage.setItem('stackchain.tomorrow-sync.v1.timmy', JSON.stringify({
base_revision:11, revision:11,
ids:['issue:acme/mobile:phone:'], capacity_minutes:90,
estimates:{'issue:acme/mobile:phone:':45},
plan_date:'2026-08-21', timezone:'UTC', sync_pending:true,
}));
window.dispatchEvent(new Event('online'));
}"""
)
expect(page.locator("#mobile-tomorrow-summary")).to_have_text(
"Conflict · review required"
)
def open_conflict():
queue_sheet = page.locator("#mobile-queue-sheet")
if not queue_sheet.evaluate("element => element.open"):
page.locator('[data-mobile-task="queues"]').click()
page.locator('[data-mobile-queue="tomorrow"]').click()
review = page.locator("#tomorrow-conflict-review")
expect(review).to_be_visible()
expect(page.locator("#plan-today-title")).to_have_text(
"Resolve Tomorrow conflict"
)
expect(page.locator("#tomorrow-conflict-phone-plan")).to_contain_text(
"issue:acme/mobile:phone:"
)
expect(page.locator("#tomorrow-conflict-phone-plan")).to_contain_text(
"45 min"
)
expect(page.locator("#tomorrow-conflict-server-plan")).to_contain_text(
"issue:acme/mobile:server:"
)
expect(page.locator("#tomorrow-conflict-server-plan")).to_contain_text(
"30 min"
)
expect(page.locator("#keep-phone-tomorrow")).to_be_focused()
for selector in ("#keep-phone-tomorrow", "#use-server-tomorrow"):
bounds = page.locator(selector).bounding_box()
assert bounds and bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
stage_phone_plan()
open_conflict()
initial_puts = len(put_bodies)
page.locator("#use-server-tomorrow").click()
expect(page.locator("#plan-today-sheet")).to_be_hidden()
expect(page.locator("#mobile-tomorrow-summary")).to_contain_text("1 planned")
assert len(put_bodies) == initial_puts
stage_phone_plan()
open_conflict()
page.locator("#keep-phone-tomorrow").click()
expect(page.locator("#plan-today-sheet")).to_be_hidden()
expect(page.locator("#mobile-tomorrow-summary")).to_contain_text("1 planned · 45 of 90 min")
assert put_bodies[-1]["base_revision"] == 12
assert put_bodies[-1]["ids"] == ["issue:acme/mobile:phone:"]
assert page.evaluate(
"localStorage.getItem('stackchain.tomorrow-sync.v1.timmy')"
) is None
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
browser.close()
finally:
fake.shutdown()
fake.server_close()
fake_thread.join(timeout=5)
+1 -1
View File
@@ -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-v123" in worker
assert "stackchain-dashboard-shell-v124" in worker
+4 -1
View File
@@ -50,7 +50,7 @@ def test_product_workflows_are_stable_lazy_feature_chunks(tmp_path):
assert set(first.feature_bundles) == {
"comment-actions", "issue-capture", "pull-workflow", "push-notifications", "sign-out", "device-setup",
"today-timer", "security-center",
"today-timer", "security-center", "planning",
}
assert first.dashboard_html.count("<script src=") == 1
assert f'<script src="{first.runtime_name}"></script>' in first.dashboard_html
@@ -71,6 +71,9 @@ def test_product_workflows_are_stable_lazy_feature_chunks(tmp_path):
assert b"function createAssignAndStart" in first.feature_bundles["today-timer"].runtime_bytes
assert b"function createQueueToday" not in first.runtime_bytes
assert b"function createQueueToday" in first.feature_bundles["today-timer"].runtime_bytes
assert b"function createPlanToday" in first.feature_bundles["planning"].runtime_bytes
assert b"function createTomorrowPlan" in first.feature_bundles["planning"].runtime_bytes
assert b"function createPlanToday" not in first.runtime_bytes
assert b"function createConversationPager" in first.feature_bundles["today-timer"].runtime_bytes
assert b"function createConversationPager" not in first.feature_bundles["comment-actions"].runtime_bytes
assert b"function createMobileDeliveryRecovery" not in first.runtime_bytes
+1 -1
View File
@@ -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-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/later-sync.js'" in source
+1 -1
View File
@@ -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-v123" in worker
assert "stackchain-dashboard-shell-v124" in worker
+1 -1
View File
@@ -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-v123" in worker
assert "stackchain-dashboard-shell-v124" in worker
def test_all_conversation_composers_offer_accessible_mobile_mentions():
+1 -1
View File
@@ -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-v123" in worker
assert "stackchain-dashboard-shell-v124" in worker
assert ".device-setup-panel" in css
assert ".device-readiness-card" in css
assert "overflow-x:hidden" in css
+89 -9
View File
@@ -28,31 +28,39 @@ class Element {{
return json.loads(result.stdout)
def test_first_task_activation_is_account_bound_and_completes_only_when_today_is_active():
def test_first_task_activation_is_account_bound_and_completes_only_after_a_today_outcome():
result = run_node(
"""
const values = new Map();
const storage = {getItem:key => values.get(key) || null, setItem:(key,value) => values.set(key,value)};
const sheet = new Element();
const coach = new Element(); coach.hidden = true;
const receipt = new Element(); receipt.hidden = true;
let login = 'Timmy';
let hasWork = false;
let todayActive = false;
let hideReceipt;
const controller = createFirstTask({
storage, getLogin:() => login, hasWork:() => hasWork, isTodayActive:() => todayActive,
isOnline:() => true, mediaQuery:{matches:true}, sheet, title:new Element(),
isOnline:() => true, mediaQuery:{matches:true}, sheet, title:new Element(), coach, receipt,
findButton:new Element(), createButton:new Element(), setupButton:new Element(),
closeButton:new Element(), status:new Element(), onFind() {}, onCreate() {}, onSetup() {},
setTimer:callback => { hideReceipt = callback; return {unref() {}}; },
});
const before = [controller.required(), controller.open(), sheet.open];
hasWork = true;
const awaitingStart = controller.refresh();
const stillRequired = controller.required();
todayActive = true;
const completed = controller.refresh();
const timmyRequired = controller.required();
const coaching = controller.refresh();
const afterStart = {required:controller.required(), sheetOpen:sheet.open, coachHidden:coach.hidden, stored:values.get('stackchain.first-task.v1:timmy')};
const completed = controller.completeOutcome();
const afterOutcome = {required:controller.required(), coachHidden:coach.hidden, receiptHidden:receipt.hidden, stored:values.get('stackchain.first-task.v1:timmy')};
hideReceipt();
const receiptHiddenAfterTimeout = receipt.hidden;
login = 'alexander'; hasWork = false; todayActive = false;
const alexanderRequired = controller.required();
process.stdout.write(JSON.stringify({before, awaitingStart, stillRequired, completed, sheetOpen:sheet.open, timmyRequired, alexanderRequired, values:[...values]}));
process.stdout.write(JSON.stringify({before, awaitingStart, stillRequired, coaching, afterStart, completed, afterOutcome, receiptHiddenAfterTimeout, alexanderRequired}));
"""
)
@@ -60,11 +68,22 @@ process.stdout.write(JSON.stringify({before, awaitingStart, stillRequired, compl
"before": [True, True, True],
"awaitingStart": "awaiting-start",
"stillRequired": True,
"completed": "completed",
"sheetOpen": False,
"timmyRequired": False,
"coaching": "coaching",
"afterStart": {
"required": False,
"sheetOpen": False,
"coachHidden": False,
"stored": "coaching",
},
"completed": True,
"afterOutcome": {
"required": False,
"coachHidden": True,
"receiptHidden": False,
"stored": "complete",
},
"receiptHiddenAfterTimeout": True,
"alexanderRequired": True,
"values": [["stackchain.first-task.v1:timmy", "complete"]],
}
@@ -99,6 +118,34 @@ process.stdout.write(JSON.stringify({
}
def test_first_task_adopts_remote_completion_without_crossing_accounts():
result = run_node(
"""
const values = new Map(); let login='timmy'; let todayActive=false;
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)};
const controller=createFirstTask({
storage,getLogin:()=>login,hasWork:()=>false,isTodayActive:()=>todayActive,isOnline:()=>true,
mediaQuery:{matches:true},sheet:new Element(),title:new Element(),coach:new Element(),receipt:new Element(),
findButton:new Element(),createButton:new Element(),setupButton:new Element(),closeButton:new Element(),
status:new Element(),
});
const adopted=controller.adoptRemote('complete');
const timmy={required:controller.required(),stored:values.get('stackchain.first-task.v1:timmy')};
login='alexander'; const alexanderRequired=controller.required();
todayActive=true; controller.refresh(); controller.completeOutcome();
process.stdout.write(JSON.stringify({adopted,timmy,alexanderRequired,
alexander:values.get('stackchain.first-task.v1:alexander')}));
"""
)
assert result == {
"adopted": True,
"timmy": {"required": False, "stored": "complete"},
"alexanderRequired": True,
"alexander": "complete",
}
def test_first_task_activation_routes_existing_flows_and_keeps_create_available_offline():
result = run_node(
"""
@@ -143,6 +190,34 @@ process.stdout.write(JSON.stringify({offline, calls, sheetOpen:sheet.open}));
}
def test_first_task_exposes_completion_operation_before_showing_local_success():
result = run_node(
"""
const values = new Map([['stackchain.first-task.v1:timmy', 'coaching']]);
let dispatched = 0;
const controller = createFirstTask({
storage:{getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value)},
getLogin:()=> 'timmy',hasWork:()=>true,isTodayActive:()=>true,isOnline:()=>true,
mediaQuery:{matches:true},sheet:new Element(),title:new Element(),coach:new Element(),receipt:new Element(),
findButton:new Element(),createButton:new Element(),setupButton:new Element(),closeButton:new Element(),status:new Element(),
eventTarget:{dispatchEvent:()=>{dispatched += 1}}, setTimer:()=>({unref(){}}),
});
const before = globalThis.stackchainFirstTaskCompleting();
const globalProbe = globalThis.stackchainFirstTaskCompleting();
const completed = controller.completeOutcome();
process.stdout.write(JSON.stringify({before,globalProbe,completed,stored:values.get('stackchain.first-task.v1:timmy'),dispatched}));
"""
)
assert result == {
"before": True,
"globalProbe": True,
"completed": True,
"stored": "complete",
"dispatched": 1,
}
@pytest.mark.anyio
async def test_dashboard_renders_and_wires_phone_safe_first_task_activation():
html = await dashboard()
@@ -155,9 +230,14 @@ async def test_dashboard_renders_and_wires_phone_safe_first_task_activation():
assert '<script src="static/mobile-first-task.js"></script>' in html
assert "const mobileFirstTask = createMobileFirstTask({" in html
assert "isTodayActive: () => workSession.checkpointed()" in html
assert "shouldActivate: () => mobileFirstTask.required()" in html
assert "openActivation: () => mobileFirstTask.open()" in html
assert "mobileFirstTask.refresh()" in html
assert 'data-mobile-first-task-coach hidden' in html
assert 'Complete your first task' in html
assert 'id="mobile-first-task-receipt" role="status" aria-live="polite" hidden' in html
assert "advance: () => (mobileFirstTask.completeOutcome(), runTodayTransition('complete'))" in html
assert '.mobile-first-task { box-sizing:border-box; width:100%;' in html
assert 'padding-bottom:calc(16px + env(safe-area-inset-bottom))' in html
assert '.mobile-first-task-actions button { min-height:48px;' in html
+1 -1
View File
@@ -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-v123" in worker
assert "stackchain-dashboard-shell-v124" in worker
assert "BASE + 'static/mobile-insights.js'" in worker
+1 -1
View File
@@ -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-v123" in service_worker
assert "stackchain-dashboard-shell-v124" in service_worker
@pytest.mark.anyio
+1 -1
View File
@@ -3829,7 +3829,7 @@ async def test_checkpointed_detail_defer_completes_today_and_advertises_next_ite
assert "continueSession: item => completeTodayItem(item, {" in html
assert "successMessage: 'Deferred to Later. Next Today item opened.'" in html
assert "advance: () => runTodayTransition('complete')" in html
assert "advance: () => (mobileFirstTask.completeOutcome(), runTodayTransition('complete'))" in html
assert "button.textContent = active ? 'Later today & next' : 'Later today'" in html
assert "button.textContent = active ? 'Tomorrow & next' : 'Tomorrow'" in html
assert "button.textContent = active ? 'Choose date & time & next' : 'Choose date & time'" in html
+1 -1
View File
@@ -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-v123" in source
assert "stackchain-dashboard-shell-v124" 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
+15 -14
View File
@@ -168,13 +168,13 @@ async function dispatchPush(payload) {{
def test_offline_activation_migration_rolls_the_shell_cache():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" in source
def test_resumable_today_session_ships_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/my-work.js'" in source
assert "BASE + 'static/dashboard.js'" in source
assert "BASE + 'static/dashboard.css'" in source
@@ -183,7 +183,7 @@ def test_resumable_today_session_ships_in_a_new_offline_shell():
def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" 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
@@ -192,7 +192,7 @@ def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/issue-evidence-review.js'" in source
assert "BASE + 'static/issue-attachment.js'" in source
@@ -200,14 +200,14 @@ def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
def test_ownership_exit_runtime_rolls_the_offline_shell_cache():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" 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-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/today-completion.js'" in source
assert "BASE + 'static/dashboard.js'" in source
@@ -215,7 +215,7 @@ def test_offline_review_next_ships_today_completion_atomically():
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/create-issue-sheet.js'" in source
assert "BASE + 'static/dashboard.js'" in source
@@ -223,7 +223,7 @@ def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" 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
@@ -233,14 +233,14 @@ def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" 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-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/dashboard.css'" in source
assert "BASE + 'static/dashboard.js'" in source
assert "BASE + 'static/install-app.js'" in source
@@ -249,21 +249,21 @@ def test_navigation_deadline_ships_in_a_new_shell_cache():
def test_today_convergence_ships_in_a_new_shell_cache():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v123" in source
assert "stackchain-dashboard-shell-v124" 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-v123" in source
assert "stackchain-dashboard-shell-v124" 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-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/update-ownership.js'" in source
@@ -1137,7 +1137,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-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/queue-today.js'" in source
@@ -1212,6 +1212,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
"/dashboard/static/plan-today.js",
"/dashboard/static/plan-today-readiness.js",
"/dashboard/static/plan-today-preview.js",
"/dashboard/static/tomorrow-plan.js",
"/dashboard/static/today-sync.js",
"/dashboard/static/today-rollover.js",
"/dashboard/static/update-ownership.js",
+8
View File
@@ -185,6 +185,14 @@ process.stdout.write(JSON.stringify({{opened,cancelled,started,expired,final:{{c
}
def test_confirming_the_account_renders_a_persisted_break_immediately():
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
confirmation = dashboard.split("if (activeFlushLogin) {", 1)[1].split("}", 1)[0]
assert "confirmedOwnerLogin = activeFlushLogin;" in confirmation
assert "timerView.render();" in confirmation
def test_timed_break_is_packaged_as_an_accessible_mobile_flow():
html = (ROOT / "frontend" / "index.html").read_text()
css = (ROOT / "frontend" / "dashboard.css").read_text()
+1 -1
View File
@@ -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-v123';" in service_worker
assert "const CACHE = 'stackchain-dashboard-shell-v124';" in service_worker
assert "BASE + 'static/today-readiness.js'" in service_worker
+48
View File
@@ -304,6 +304,36 @@ def test_initialized_today_reads_remain_available_during_a_planning_write(tmp_pa
writer.close()
def test_first_task_completion_is_monotonic_durable_and_account_scoped(tmp_path):
path = tmp_path / "today.sqlite3"
key = b"f" * 32
store = TodayStore(path, encryption_key=key)
store.apply("timmy", "plan-change", "add", "issue:r:1:")
completed = store.apply_batch("Timmy", [{
"operation_id": "first-task-complete",
"action": "activate",
"item_id": "first-task",
"activation_state": "complete",
"base_revision": 0,
}])
replayed_coaching = store.apply_batch("timmy", [{
"operation_id": "late-coaching",
"action": "activate",
"item_id": "first-task",
"activation_state": "coaching",
"base_revision": 0,
}])
assert completed["first_task_state"] == "complete"
assert replayed_coaching["first_task_state"] == "complete"
assert TodayStore(path, encryption_key=key).get("timmy")["first_task_state"] == "complete"
assert "first_task_state" not in store.get("alexander")
retained = path.read_bytes()
assert b'first_task_state' not in retained
assert b'complete' not in retained
def test_capacity_and_estimates_are_durable_account_scoped_and_follow_item_identity(tmp_path):
path = tmp_path / "today.sqlite3"
store = TodayStore(path, limit=3)
@@ -499,6 +529,24 @@ def test_today_api_model_accepts_bounded_capacity_configuration():
}
def test_today_api_model_accepts_only_bounded_first_task_activation():
operation = main.TodayOperation(
operation_id="activation", action="activate", item_id="first-task",
activation_state="complete", base_revision=7,
)
assert operation.model_dump() == {
"operation_id": "activation", "action": "activate", "item_id": "first-task",
"direction": None, "base_revision": 7, "capacity_minutes": None,
"estimates": {}, "activation_state": "complete",
}
with pytest.raises(ValueError):
main.TodayOperation(
operation_id="bad", action="activate", item_id="another-flow",
activation_state="complete",
)
@pytest.mark.anyio
async def test_single_capacity_configuration_uses_atomic_batch_path(monkeypatch):
async def user():
+153 -1
View File
@@ -84,6 +84,53 @@ sync.enqueue('add', 'issue:r:1:');
}
def test_activation_queued_during_an_empty_inflight_refresh_is_drained_before_it_settles():
script = f"""
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
const values = new Map();
const storage = {{get length(){{return values.size}},key:i=>[...values.keys()][i]||null,
getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
let releaseRefresh;
const refreshStarted = new Promise(resolve => {{ globalThis.refreshStarted = resolve; }});
const patches = [];
const statuses = [];
const sync = createTodaySync({{
storage, getLogin: () => 'timmy', createOperationId: () => 'activation-1',
fetchJson: async (_url, options={{}}) => {{
if (!options.method) {{
globalThis.refreshStarted();
await new Promise(resolve => {{ releaseRefresh = resolve; }});
return {{revision:0, ids:[]}};
}}
const operations = JSON.parse(options.body).operations;
patches.push(...operations);
return {{revision:1, ids:[], first_task_state:'complete',
accepted_operation_ids:operations.map(item => item.operation_id)}};
}},
onRemoteIds: () => {{}}, onStatus: state => statuses.push(state),
}});
(async () => {{
const refreshing = sync.flush();
await refreshStarted;
sync.enqueueActivation('complete');
const sharedFlush = sync.flush();
releaseRefresh();
await sharedFlush;
process.stdout.write(JSON.stringify({{
sharesInflight: refreshing === sharedFlush, patches, pending:sync.pending(), statuses,
}}));
}})();
"""
result = json.loads(subprocess.run(
["node", "-e", script], check=True, capture_output=True, text=True
).stdout)
assert result["sharesInflight"] is True
assert [operation["activation_state"] for operation in result["patches"]] == ["complete"]
assert result["pending"] == []
assert result["statuses"][-1] == "saved"
def test_operations_queued_in_the_same_millisecond_preserve_enqueue_order():
script = f"""
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
@@ -188,10 +235,115 @@ sync.enqueueConfiguration(120, {{'issue:r:1:':60}});
}
def test_today_batch_admission_leaves_no_partial_operations_when_storage_fails():
script = f"""
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
const values = new Map(); let writes = 0; let sequence = 0;
const storage = {{
get length() {{ return values.size; }}, key: index => [...values.keys()][index] || null,
getItem: key => values.get(key) || null,
setItem: (key, value) => {{ writes += 1; throw new Error('quota'); }},
removeItem: key => values.delete(key),
}};
const sync = createTodaySync({{
storage, getLogin: () => 'timmy', createOperationId: () => 'batch-' + (++sequence),
fetchJson: async () => {{ throw new Error('must not deliver'); }}, onStatus: () => {{}},
}});
const admitted = sync.enqueueBatch([
{{action:'remove', item_id:'issue:r:1:'}},
{{action:'activate', item_id:'first-task', activation_state:'complete'}},
]);
process.stdout.write(JSON.stringify({{admitted, writes, pending:sync.pending(), keys:[...values.keys()]}}));
"""
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
assert result.returncode == 0, result.stderr
assert json.loads(result.stdout) == {
"admitted": False,
"writes": 1,
"pending": [],
"keys": [],
}
def test_today_batch_delivers_remove_and_activation_together_then_clears_receipts():
script = f"""
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
const values = new Map(); let sequence = 0; const patches = [];
const storage = {{
get length() {{ return values.size; }}, key: index => [...values.keys()][index] || null,
getItem: key => values.get(key) || null, setItem: (key,value) => values.set(key,value),
removeItem: key => values.delete(key),
}};
const sync = createTodaySync({{
storage, getLogin: () => 'timmy', createOperationId: () => 'batch-' + (++sequence),
fetchJson: async (_url, options={{}}) => {{
const operations = JSON.parse(options.body).operations; patches.push(operations);
return {{revision:3, ids:[], first_task_state:'complete',
accepted_operation_ids:operations.map(item => item.operation_id)}};
}}, onRemoteIds: () => {{}}, onStatus: () => {{}},
}});
const admitted = sync.enqueueBatch([
{{action:'remove', item_id:'issue:r:1:'}},
{{action:'activate', item_id:'first-task', activation_state:'complete'}},
]);
const before = sync.pending();
(async()=>{{await sync.flush();process.stdout.write(JSON.stringify({{
admitted, before, patches, after:sync.pending(), operationKeys:[...values.keys()].filter(key=>key.includes('.operation.')),
}}));}})();
"""
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
assert result.returncode == 0, result.stderr
data = json.loads(result.stdout)
assert data["admitted"] is True
assert [[item["action"] for item in batch] for batch in data["patches"]] == [["remove", "activate"]]
assert data["before"] == data["patches"][0]
assert data["after"] == []
assert data["operationKeys"] == []
def test_first_task_activation_uses_today_outbox_and_adopts_remote_completion():
script = f"""
const createTodaySync = require({json.dumps(str(TODAY_SYNC))});
const values = new Map(); let sequence=0; const adopted=[]; const delivered=[]; const listeners={{}};
const storage = {{get length(){{return values.size}},key:i=>[...values.keys()][i]||null,
getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
const sync = createTodaySync({{
storage, getLogin:()=> 'timmy', createOperationId:()=> 'activation-' + (++sequence),
fetchJson:async(_url, options={{}})=>{{
if (!options.method) return {{revision:4,ids:[],first_task_state:'complete'}};
const operations=JSON.parse(options.body).operations; delivered.push(...operations);
return {{revision:5,ids:[],first_task_state:'complete',accepted_operation_ids:operations.map(x=>x.operation_id)}};
}},
onRemotePlan:plan=>adopted.push(plan.first_task_state), onRemoteIds:()=>{{}}, onStatus:()=>{{}},
}});
sync.startLifecycle({{window:{{addEventListener:(name,callback)=>listeners[name]=callback}},document:{{addEventListener(){{}}}}}});
listeners['stackchain:first-task-complete']();
listeners['stackchain:first-task-complete']();
(async()=>{{await sync.flush();process.stdout.write(JSON.stringify({{
delivered,adopted,pending:sync.pending(),hydrated:values.get('stackchain.first-task.v1:timmy')
}}));}})();
"""
result = json.loads(subprocess.run(
["node", "-e", script], check=True, capture_output=True, text=True
).stdout)
assert result == {
"delivered": [{
"operation_id": "activation-1", "action": "activate", "item_id": "first-task",
"direction": None, "activation_state": "complete", "base_revision": 0,
}],
"adopted": ["complete"],
"pending": [],
"hydrated": "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-v123" in source
assert "stackchain-dashboard-shell-v124" in source
assert "BASE + 'static/today-sync.js'" in source
+37
View File
@@ -319,6 +319,43 @@ process.stdout.write(JSON.stringify({{completed, calls}}));
}
def test_done_for_today_restores_plan_and_keeps_session_when_durable_batch_admission_fails():
script = f"""
const createTodayWork = require({json.dumps(str(TODAY_WORK))});
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
const values = new Map();
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
const todayWork = createTodayWork({{storage, getLogin:()=> 'timmy'}});
const item = {{kind:'issue', repository:'r', number:1}};
todayWork.replace(['issue:r:1:', 'issue:r:2:']);
const calls = []; let offered = false;
globalThis.stackchainFirstTaskCompleting = () => true;
const complete = createTodayCompletion({{
todayWork,
todaySync: {{enqueueBatch: operations => {{calls.push(['batch', operations]); return false;}},
flush: () => calls.push(['flush'])}},
refresh: () => calls.push(['refresh']), warm: () => calls.push(['warm']),
workSession: {{complete: () => calls.push(['advance'])}},
announce: message => calls.push(['announce', message]), onOffer: () => {{offered = true;}},
}});
const completed = complete(item);
process.stdout.write(JSON.stringify({{completed, ids:todayWork.read(), calls, offered}}));
"""
assert json.loads(run_node(script)) == {
"completed": False,
"ids": ["issue:r:1:", "issue:r:2:"],
"calls": [
["batch", [
{"action": "remove", "item_id": "issue:r:1:"},
{"action": "activate", "item_id": "first-task", "activation_state": "complete"},
]],
["announce", "Device storage is full. Free space and try again."],
],
"offered": False,
}
def test_today_completion_reports_context_specific_success_and_partial_failure():
script = f"""
const createTodayCompletion = require({json.dumps(str(TODAY_COMPLETION))});
+173
View File
@@ -0,0 +1,173 @@
import sqlite3
from datetime import datetime, timezone
import pytest
from src import main
from src.today_store import TodayPromotionConflict, TodayStore, TomorrowPlanConflict
def test_tomorrow_plan_is_encrypted_scoped_and_promotes_atomically_exactly_once(tmp_path):
path = tmp_path / "today.sqlite3"
key = b"n" * 32
store = TodayStore(
path,
encryption_key=key,
clock=lambda: datetime(2026, 8, 21, tzinfo=timezone.utc).timestamp(),
)
store.apply("timmy", "today-1", "add", "issue:r:1:")
tomorrow = store.replace_tomorrow(
"Timmy", base_revision=0,
ids=["issue:secret/repo:3:", "issue:secret/repo:2:"],
capacity_minutes=150,
estimates={"issue:secret/repo:3:": 60, "issue:secret/repo:2:": 45},
plan_date="2026-08-20", timezone="America/Los_Angeles",
)
assert tomorrow == {
"revision": 1,
"ids": ["issue:secret/repo:3:", "issue:secret/repo:2:"],
"capacity_minutes": 150,
"estimates": {"issue:secret/repo:3:": 60, "issue:secret/repo:2:": 45},
"plan_date": "2026-08-20",
"timezone": "America/Los_Angeles",
}
assert store.get("timmy")["ids"] == ["issue:r:1:"]
assert store.get_tomorrow("alexander")["ids"] == []
retained = path.read_bytes()
assert b"issue:secret/repo" not in retained
assert b"America/Los_Angeles" not in retained
promoted = store.promote_tomorrow(
"timmy", promotion_id="rollover-2026-08-20",
tomorrow_revision=1, today_revision=1,
)
replay = store.promote_tomorrow(
"timmy", promotion_id="rollover-2026-08-20",
tomorrow_revision=1, today_revision=1,
)
assert replay == promoted
assert promoted["ids"] == tomorrow["ids"]
assert promoted["capacity_minutes"] == 150
assert promoted["plan_date"] == "2026-08-20"
assert store.get_tomorrow("timmy") == {
"revision": 2, "ids": [], "capacity_minutes": None, "estimates": {}
}
def test_tomorrow_edit_and_promotion_reject_stale_revisions_without_touching_today(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3",
encryption_key=b"s" * 32,
clock=lambda: datetime(2026, 8, 21, tzinfo=timezone.utc).timestamp(),
)
original_today = store.apply("timmy", "today", "add", "issue:r:1:")
first = store.replace_tomorrow(
"timmy", base_revision=0, ids=["issue:r:2:"], capacity_minutes=60,
estimates={"issue:r:2:": 30}, plan_date="2026-08-20", timezone="UTC",
)
with pytest.raises(TomorrowPlanConflict) as stale_edit:
store.replace_tomorrow(
"timmy", base_revision=0, ids=["issue:r:9:"], capacity_minutes=None,
estimates={}, plan_date="2026-08-20", timezone="UTC",
)
assert stale_edit.value.snapshot == first
store.apply("timmy", "today-changed", "add", "issue:r:3:")
with pytest.raises(TodayPromotionConflict) as stale_today:
store.promote_tomorrow(
"timmy", promotion_id="rollover", tomorrow_revision=1,
today_revision=original_today["revision"],
)
assert stale_today.value.today["ids"] == ["issue:r:1:", "issue:r:3:"]
assert store.get_tomorrow("timmy") == first
def test_tomorrow_promotion_rejects_the_day_before_in_the_saved_timezone(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3",
clock=lambda: datetime(2026, 8, 20, 6, 59, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "today", "add", "issue:r:1:")
tomorrow = store.replace_tomorrow(
"timmy", base_revision=0, ids=["issue:r:2:"], capacity_minutes=60,
estimates={}, plan_date="2026-08-20", timezone="America/Los_Angeles",
)
with pytest.raises(ValueError, match="Tomorrow plan is not due"):
store.promote_tomorrow(
"timmy", promotion_id="tomorrow-2026-08-20-r1",
tomorrow_revision=tomorrow["revision"], today_revision=today["revision"],
)
assert store.get("timmy") == today
assert store.get_tomorrow("timmy") == tomorrow
def test_tomorrow_validation_is_bounded_and_date_specific(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3")
with pytest.raises(ValueError, match="ISO calendar date"):
store.replace_tomorrow(
"timmy", base_revision=0, ids=[], capacity_minutes=None, estimates={},
plan_date="tomorrow", timezone="UTC",
)
with pytest.raises(ValueError, match="unique"):
store.replace_tomorrow(
"timmy", base_revision=0, ids=["same", "same"], capacity_minutes=None,
estimates={}, plan_date="2026-08-20", timezone="UTC",
)
@pytest.mark.anyio
async def test_tomorrow_api_round_trip_and_conflict_contract(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"a" * 32)
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
payload = main.TomorrowPlanUpdate(
base_revision=0, ids=["issue:r:2:"], capacity_minutes=90,
estimates={"issue:r:2:": 45}, plan_date="2026-08-20", timezone="UTC",
)
saved = await main.replace_tomorrow_plan(payload)
assert await main.get_tomorrow_plan() == saved
with pytest.raises(main.HTTPException) as raised:
await main.replace_tomorrow_plan(payload)
assert raised.value.status_code == 409
assert raised.value.detail == {"code": "tomorrow_changed", "snapshot": saved}
@pytest.mark.anyio
async def test_tomorrow_api_reports_an_early_promotion_without_mutation(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(
tmp_path / "today.sqlite3",
clock=lambda: datetime(2026, 8, 20, 6, 59, tzinfo=timezone.utc).timestamp(),
)
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
today = store.apply("timmy", "today", "add", "issue:r:1:")
tomorrow = store.replace_tomorrow(
"timmy", base_revision=0, ids=["issue:r:2:"], capacity_minutes=60,
estimates={}, plan_date="2026-08-20", timezone="America/Los_Angeles",
)
with pytest.raises(main.HTTPException) as raised:
await main.promote_tomorrow_plan(main.TomorrowPromotion(
promotion_id="tomorrow-2026-08-20-r1",
tomorrow_revision=tomorrow["revision"], today_revision=today["revision"],
))
assert raised.value.status_code == 409
assert raised.value.detail == {
"code": "tomorrow_not_due", "plan_date": "2026-08-20"
}
assert store.get("timmy") == today
assert store.get_tomorrow("timmy") == tomorrow
+423
View File
@@ -0,0 +1,423 @@
import json
import subprocess
from pathlib import Path
FRONTEND = Path(__file__).parents[1] / "frontend"
CONTROLLER = FRONTEND / "tomorrow-plan.js"
INDEX = FRONTEND / "index.html"
CSS = FRONTEND / "dashboard.css"
def run_controller(scenario: str) -> dict:
harness = f"""
const createTomorrowPlan = 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_tomorrow_planner_restores_an_account_bound_plan_before_network_delivery():
result = run_controller("""
const values=new Map();
const storage={
getItem:key=>values.has(key)?values.get(key):null,
setItem:(key,value)=>values.set(key,value),
removeItem:key=>values.delete(key),
};
let login='Timmy';
let requests=0;
const options={storage,getLogin:()=>login,fetchJson:async()=>{requests+=1;throw new Error('offline');},
localDate:()=> '2026-08-19',timeZone:()=> 'America/New_York'};
const first=createTomorrowPlan(options);
first.adopt({revision:7,ids:[],capacity_minutes:null,estimates:{}});
const queued=first.stage({ids:['issue:r:3:','issue:r:2:'],capacity_minutes:120,
estimates:{'issue:r:3:':45,'issue:r:2:':30}});
const restored=await createTomorrowPlan(options).load();
login='alexander';
let otherError='';
try { await createTomorrowPlan(options).load(); } catch(error) { otherError=error.message; }
console.log(JSON.stringify({queued,restored,requests,otherError,keys:[...values.keys()]}));
""")
assert result["queued"]["sync_pending"] is True
assert result["restored"] == result["queued"]
assert result["requests"] == 1
assert result["otherError"] == "offline"
assert result["keys"] == ["stackchain.tomorrow-sync.v1.timmy"]
def test_tomorrow_planner_flushes_once_and_removes_pending_only_after_server_receipt():
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 resolveRequest;
let requests=0;
const fetchJson=async (_url,options={})=>{
requests+=1;
const body=JSON.parse(options.body);
await new Promise(resolve=>{resolveRequest=()=>resolve({revision:9,...body});});
return {revision:9,...body};
};
const planner=createTomorrowPlan({storage,getLogin:()=> 'timmy',fetchJson,
localDate:()=> '2026-08-19',timeZone:()=> 'UTC'});
planner.adopt({revision:8,ids:[],capacity_minutes:null,estimates:{}});
planner.stage({ids:['issue:r:4:'],capacity_minutes:60,estimates:{'issue:r:4:':30}});
const first=planner.flush();
const second=planner.flush();
await Promise.resolve();
const pendingDuring=planner.pending();
resolveRequest();
const [saved,reused]=await Promise.all([first,second]);
console.log(JSON.stringify({requests,pendingDuring,saved,reused,pendingAfter:planner.pending(),keys:[...values.keys()]}));
""")
assert result["requests"] == 1
assert result["pendingDuring"]["ids"] == ["issue:r:4:"]
assert result["saved"]["revision"] == 9
assert result["reused"]["revision"] == 9
assert result["pendingAfter"] is False
assert result["keys"] == []
def test_tomorrow_planner_preserves_local_and_server_plans_on_revision_conflict():
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)};
const requests=[];
const fetchJson=async (_url,options={})=>{
requests.push(options.method||'GET');
if(options.method==='PUT'){const error=new Error('changed elsewhere');error.status=409;throw error;}
return {revision:12,ids:['issue:r:server:'],capacity_minutes:60,estimates:{},plan_date:'2026-08-20',timezone:'UTC'};
};
const planner=createTomorrowPlan({storage,getLogin:()=> 'timmy',fetchJson,
localDate:()=> '2026-08-19',timeZone:()=> 'UTC'});
planner.adopt({revision:11,ids:[],capacity_minutes:null,estimates:{}});
planner.stage({ids:['issue:r:phone:'],capacity_minutes:90,estimates:{}});
let message='';
try { await planner.flush(); } catch(error) { message=error.message; }
console.log(JSON.stringify({requests,message,pending:planner.pending(),conflict:planner.conflict()}));
""")
assert result["requests"] == ["PUT", "GET"]
assert result["message"] == "changed elsewhere"
assert result["pending"]["ids"] == ["issue:r:phone:"]
assert result["conflict"]["local"]["ids"] == ["issue:r:phone:"]
assert result["conflict"]["remote"]["ids"] == ["issue:r:server:"]
assert result["conflict"]["remote"]["revision"] == 12
def test_tomorrow_planner_keeps_phone_plan_by_rebasing_once_onto_conflict_revision():
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)};
const requests=[];
let puts=0;
const fetchJson=async (_url,options={})=>{
requests.push({method:options.method||'GET',body:options.body?JSON.parse(options.body):null});
if(options.method==='PUT'&&puts++===0){const error=new Error('changed elsewhere');error.status=409;throw error;}
if(options.method==='PUT') return {revision:13,...JSON.parse(options.body)};
return {revision:12,ids:['issue:r:server:'],capacity_minutes:60,estimates:{'issue:r:server:':30},plan_date:'2026-08-20',timezone:'UTC'};
};
const planner=createTomorrowPlan({storage,getLogin:()=> 'timmy',fetchJson,
localDate:()=> '2026-08-19',timeZone:()=> 'UTC'});
planner.adopt({revision:11,ids:[],capacity_minutes:null,estimates:{}});
planner.stage({ids:['issue:r:phone:'],capacity_minutes:90,estimates:{'issue:r:phone:':45}});
try { await planner.flush(); } catch(_error) {}
const saved=await planner.keepLocal();
console.log(JSON.stringify({saved,requests,pending:planner.pending(),conflict:planner.conflict(),state:planner.state()}));
""")
assert [request["method"] for request in result["requests"]] == ["PUT", "GET", "PUT"]
assert result["requests"][2]["body"]["base_revision"] == 12
assert result["requests"][2]["body"]["ids"] == ["issue:r:phone:"]
assert result["saved"]["revision"] == 13
assert result["pending"] is False
assert result["conflict"] is None
assert result["state"]["ids"] == ["issue:r:phone:"]
def test_tomorrow_planner_uses_server_plan_without_a_second_write():
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)};
const requests=[];
const fetchJson=async (_url,options={})=>{
requests.push(options.method||'GET');
if(options.method==='PUT'){const error=new Error('changed elsewhere');error.status=409;throw error;}
return {revision:12,ids:['issue:r:server:'],capacity_minutes:60,estimates:{'issue:r:server:':30},plan_date:'2026-08-20',timezone:'UTC'};
};
const planner=createTomorrowPlan({storage,getLogin:()=> 'timmy',fetchJson,
localDate:()=> '2026-08-19',timeZone:()=> 'UTC'});
planner.adopt({revision:11,ids:[],capacity_minutes:null,estimates:{}});
planner.stage({ids:['issue:r:phone:'],capacity_minutes:90,estimates:{'issue:r:phone:':45}});
try { await planner.flush(); } catch(_error) {}
const adopted=planner.useRemote();
console.log(JSON.stringify({adopted,requests,pending:planner.pending(),conflict:planner.conflict(),state:planner.state()}));
""")
assert result["requests"] == ["PUT", "GET"]
assert result["adopted"]["revision"] == 12
assert result["adopted"]["ids"] == ["issue:r:server:"]
assert result["pending"] is False
assert result["conflict"] is None
assert result["state"] == result["adopted"]
def test_tomorrow_conflict_cannot_be_read_or_resolved_after_account_switch():
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 login='timmy';
const fetchJson=async (_url,options={})=>{
if(options.method==='PUT'){const error=new Error('changed elsewhere');error.status=409;throw error;}
return {revision:12,ids:['issue:private:timmy:'],capacity_minutes:60,estimates:{},plan_date:'2026-08-20',timezone:'UTC'};
};
const planner=createTomorrowPlan({storage,getLogin:()=>login,fetchJson,
localDate:()=> '2026-08-19',timeZone:()=> 'UTC'});
planner.adopt({revision:11,ids:[],capacity_minutes:null,estimates:{}});
planner.stage({ids:['issue:private:phone:'],capacity_minutes:90,estimates:{}});
try { await planner.flush(); } catch(_error) {}
const before=planner.conflict();
login='alexander';
const after=planner.conflict();
const keep=await planner.keepLocal();
const use=planner.useRemote();
login='timmy';
const restored=planner.conflict();
console.log(JSON.stringify({before,after,keep,use,restored}));
""")
assert result["before"]["remote"]["ids"] == ["issue:private:timmy:"]
assert result["after"] is None
assert result["keep"] is False
assert result["use"] is False
assert result["restored"]["local"]["ids"] == ["issue:private:phone:"]
def test_tomorrow_planner_loads_and_saves_independently_from_today():
result = run_controller("""
const requests=[];
const fetchJson=async (url, options={})=>{
requests.push({url,method:options.method||'GET',body:options.body ? JSON.parse(options.body) : null});
if ((options.method||'GET') === 'GET') return {
revision:2, ids:['issue:r:2:'], capacity_minutes:90,
estimates:{'issue:r:2:':45}, plan_date:'2026-08-20', timezone:'UTC'
};
return {revision:3,...JSON.parse(options.body)};
};
const planner=createTomorrowPlan({fetchJson, localDate:()=> '2026-08-19', timeZone:()=> 'UTC'});
const loaded=await planner.load();
const saved=await planner.save({ids:['issue:r:3:'],capacity_minutes:120,estimates:{'issue:r:3:':60}});
console.log(JSON.stringify({loaded,saved,requests}));
""")
assert result["loaded"]["ids"] == ["issue:r:2:"]
assert result["saved"]["plan_date"] == "2026-08-20"
assert result["requests"] == [
{"url": "api/v1/tomorrow", "method": "GET", "body": None},
{
"url": "api/v1/tomorrow",
"method": "PUT",
"body": {
"base_revision": 2,
"ids": ["issue:r:3:"],
"capacity_minutes": 120,
"estimates": {"issue:r:3:": 60},
"plan_date": "2026-08-20",
"timezone": "UTC",
},
},
]
assert all(request["url"] != "api/v1/today" for request in result["requests"])
def test_pending_tomorrow_plan_is_not_promoted_before_account_sync():
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)};
const requests=[];
let date='2026-08-19';
const planner=createTomorrowPlan({storage,getLogin:()=> 'timmy',fetchJson:async(url)=>{requests.push(url);return {};},
localDate:()=> date,timeZone:()=> 'UTC'});
planner.adopt({revision:3,ids:['issue:r:2:'],capacity_minutes:60,estimates:{},plan_date:'2026-08-20',timezone:'UTC'});
planner.stage({ids:['issue:r:2:'],capacity_minutes:60,estimates:{}});
date='2026-08-22';
const promoted=await planner.promote(7);
console.log(JSON.stringify({promoted,requests,pending:planner.pending()}));
""")
assert result["promoted"] is False
assert result["requests"] == []
assert result["pending"]["ids"] == ["issue:r:2:"]
def test_tomorrow_planner_promotes_overdue_plans_with_a_stable_retry_identity():
result = run_controller("""
const requests=[];
const fetchJson=async (url, options={})=>{
requests.push({url,body:options.body ? JSON.parse(options.body) : null});
return {ids:['issue:r:2:'],revision:8};
};
const before=createTomorrowPlan({fetchJson,localDate:()=> '2026-08-19',timeZone:()=> 'UTC'});
before.adopt({revision:3,ids:['issue:r:2:'],capacity_minutes:60,estimates:{},plan_date:'2026-08-20',timezone:'UTC'});
const early=await before.promote(7);
const overdue=createTomorrowPlan({fetchJson,localDate:()=> '2026-08-22',timeZone:()=> 'UTC'});
overdue.adopt({revision:3,ids:['issue:r:2:'],capacity_minutes:60,estimates:{},plan_date:'2026-08-20',timezone:'UTC'});
const promoted=await overdue.promote(7);
const retried=await overdue.promote(7);
console.log(JSON.stringify({early,promoted,retried,requests}));
""")
assert result["early"] is False
assert result["promoted"]["revision"] == 8
assert result["retried"]["revision"] == 8
assert result["requests"] == [
{
"url": "api/v1/tomorrow/promote",
"body": {
"promotion_id": "tomorrow-2026-08-20-r3",
"tomorrow_revision": 3,
"today_revision": 7,
},
},
{
"url": "api/v1/tomorrow/promote",
"body": {
"promotion_id": "tomorrow-2026-08-20-r3",
"tomorrow_revision": 3,
"today_revision": 7,
},
},
]
def test_tomorrow_rollover_checks_startup_reconnect_foreground_and_next_midnight_single_flight():
result = run_controller("""
const listeners={};
const timers=[];
const cleared=[];
let checks=0;
const planner=createTomorrowPlan({fetchJson:async()=>({}),localDate:()=> '2026-08-20',timeZone:()=> 'UTC'});
const windowObject={addEventListener:(name,fn)=>listeners['window:'+name]=fn};
const documentObject={hidden:false,addEventListener:(name,fn)=>listeners['document:'+name]=fn};
const lifecycle=planner.startLifecycle({
windowObject,documentObject,check:async()=>{checks+=1;await Promise.resolve();return true;},
setTimer:(fn,delay)=>{timers.push({fn,delay});return timers.length;},
clearTimer:id=>cleared.push(id),nextDelay:()=>1234,
});
await lifecycle.run();
const reconnect=listeners['window:online']();
const foreground=listeners['document:visibilitychange']();
await Promise.all([reconnect,foreground]);
await timers[timers.length-1].fn();
console.log(JSON.stringify({checks,delays:timers.map(timer=>timer.delay),cleared}));
""")
assert result["checks"] == 3
assert result["delays"] == [1234, 1234, 1234]
assert result["cleared"] == [1, 2]
def test_tomorrow_rollover_falls_back_when_the_reported_timezone_is_invalid():
result = run_controller("""
let scheduled=null;
const planner=createTomorrowPlan({fetchJson:async()=>({}),localDate:()=> '2026-08-20',timeZone:()=> 'Etc/Unknown'});
const lifecycle=planner.startLifecycle({
check:async()=>false,setTimer:(_fn,delay)=>{scheduled=delay;return 1;},clearTimer:()=>{},
});
await lifecycle.run();
console.log(JSON.stringify({scheduled:Number.isFinite(scheduled)&&scheduled>0}));
""")
assert result == {"scheduled": True}
def test_tomorrow_planner_summarizes_empty_and_capacity_aware_plans_for_mobile_queues():
result = run_controller("""
const planner=createTomorrowPlan({fetchJson:async()=>({}),localDate:()=> '2026-08-20',timeZone:()=> 'UTC'});
const empty=planner.summary({ids:[],capacity_minutes:null,estimates:{}});
const planned=planner.summary({
ids:['issue:r:1:','issue:r:2:','issue:r:3:'], capacity_minutes:120,
estimates:{'issue:r:1:':30,'issue:r:2:':45,'issue:r:3:':30}
});
const unestimated=planner.summary({ids:['issue:r:4:'],capacity_minutes:null,estimates:{}});
const pending=planner.summary({ids:['issue:r:5:'],capacity_minutes:60,estimates:{'issue:r:5:':30},sync_pending:true});
console.log(JSON.stringify({empty,planned,unestimated,pending}));
""")
assert result == {
"empty": "Nothing planned",
"planned": "3 planned · 105 of 120 min",
"unestimated": "1 planned",
"pending": "1 planned · 30 of 60 min · sync pending",
}
def test_mobile_tomorrow_conflict_review_exposes_two_touch_safe_resolution_paths():
index = INDEX.read_text()
css = CSS.read_text()
dashboard = (FRONTEND / "dashboard.js").read_text()
assert 'id="tomorrow-conflict-review"' in index
assert 'id="tomorrow-conflict-phone-plan"' in index
assert 'id="tomorrow-conflict-server-plan"' in index
assert 'id="keep-phone-tomorrow"' in index
assert 'id="use-server-tomorrow"' in index
assert "Conflict · review required" in dashboard
assert "if (tomorrowPlan.conflict())" in dashboard
assert "tomorrowPlan.keepLocal()" in dashboard
assert "tomorrowPlan.useRemote()" in dashboard
assert ".tomorrow-conflict-actions button { min-height:44px;" in css
def test_mobile_tomorrow_save_is_admitted_before_background_delivery():
dashboard = (FRONTEND / "dashboard.js").read_text()
assert "storage:localStorage" in dashboard
assert "getLogin:() => planningOwnerLogin" in dashboard
assert "const staged = tomorrowPlan.stage(normalized);" in dashboard
assert "if (!staged) {" in dashboard
assert "Free browser storage and retry." in dashboard
assert "renderTomorrowQueueSummary(staged);" in dashboard
assert "Tomorrow saved on this phone · sync pending." in dashboard
assert "tomorrowPlan.flush().then" in dashboard
assert "syncPendingTomorrow()" in dashboard
assert dashboard.count("syncPendingTomorrow();") >= 2
assert "Another device changed Tomorrow" in dashboard
def test_mobile_queues_expose_tomorrow_and_keep_duplicate_header_actions_hidden():
index = INDEX.read_text()
css = CSS.read_text()
dashboard = (FRONTEND / "dashboard.js").read_text()
assert 'data-mobile-queue="tomorrow"' in index
assert 'id="mobile-tomorrow-summary"' in index
assert '>Nothing planned<' in index
assert "name === 'tomorrow' ? openTomorrowPlanner" in dashboard
assert "tomorrowPlan.summary()" in dashboard
assert "renderTomorrowQueueSummary(saved)" in dashboard
assert "planTodayTrigger?.dataset.mobileQueue === 'tomorrow'" in dashboard
assert "qs('#mobile-queue-sheet').showModal()" in dashboard
assert ".my-work-actions { display:none; }\n .my-work-actions { display:flex; }" not in css
assert ".my-work-actions { display:none; }" in css
def test_tomorrow_plan_has_a_touch_safe_mobile_entry_and_reuses_the_ordered_planner():
index = INDEX.read_text()
css = CSS.read_text()
dashboard = (FRONTEND / "dashboard.js").read_text()
assert '<button class="plan-tomorrow" id="plan-tomorrow" type="button">Plan Tomorrow</button>' in index
assert ".plan-tomorrow { min-height:44px;" in css
assert '<script src="static/tomorrow-plan.js"></script>' in index
assert "const tomorrowPlan = createTomorrowPlan" in dashboard
assert "qs('#plan-tomorrow').addEventListener('click'" in dashboard
assert "planningTomorrow ? saveTomorrowPlan(plan) : saveTodayPlan(plan)" in dashboard
assert "tomorrowPlan.load()" in dashboard
assert "tomorrowPlan.promote(plan.revision)" in dashboard
assert "tomorrowPlan.startLifecycle" in dashboard
+15 -8
View File
@@ -25,16 +25,23 @@ const status={textContent:''};
const document={
querySelector(selector) {
if (selector === 'meta[name="stackchain-feature-today-timer"]') return {content:'feature-workspace-abc.js'};
if (selector === 'meta[name="stackchain-feature-planning"]') return {content:'feature-planning-def.js'};
if (selector === '#my-work-action-status') return status;
return null;
}
};
let requested='';
const createLoader=options=>({load:async name=>{requested=name + ':' + options.urls[name];}});
const requested=[];
const createLoader=options=>({load:async name=>{requested.push(name + ':' + options.urls[name]);}});
await loadWorkspace({document,createLoader});
console.log(JSON.stringify({requested,status:status.textContent}));
""")
assert result == {"requested": "today-timer:feature-workspace-abc.js", "status": ""}
assert result == {
"requested": [
"today-timer:feature-workspace-abc.js",
"planning:feature-planning-def.js",
],
"status": "",
}
def test_workspace_bootstrap_recovers_one_transient_failure_in_place():
@@ -51,7 +58,7 @@ const schedule=callback=>{callback();};
await loadWorkspace({document,createLoader,schedule});
console.log(JSON.stringify({attempts,status:status.textContent,retryHidden:retry.hidden}));
""")
assert result == {"attempts": 2, "status": "", "retryHidden": True}
assert result == {"attempts": 4, "status": "", "retryHidden": True}
def test_workspace_bootstrap_offers_single_flight_manual_retry_without_reloading():
@@ -65,7 +72,7 @@ const document={querySelector(selector) {
return null;
}};
const window={location:{reload(){reloads++;}},addEventListener(){},removeEventListener(){}};
const createLoader=()=>({load:async()=>{attempts++; if (attempts < 3) throw new Error('offline');}});
const createLoader=()=>({load:async()=>{attempts++; if (attempts < 5) throw new Error('offline');}});
const loading=loadWorkspace({document,window,createLoader,schedule:callback=>callback()});
await new Promise(resolve=>setImmediate(resolve));
const offered={hidden:retry.hidden,disabled:retry.disabled,status:status.textContent};
@@ -74,7 +81,7 @@ await Promise.all([first,second,loading]);
console.log(JSON.stringify({attempts,reloads,offered,status:status.textContent,retryHidden:retry.hidden}));
""")
assert result == {
"attempts": 3,
"attempts": 6,
"reloads": 0,
"offered": {
"hidden": False,
@@ -109,7 +116,7 @@ const window={
addEventListener(name,callback) { listeners[name]=callback; },
removeEventListener(name,callback) { if (listeners[name] === callback) delete listeners[name]; },
};
const createLoader=()=>({load:async()=>{attempts++; if (attempts < 3) throw new Error('offline');}});
const createLoader=()=>({load:async()=>{attempts++; if (attempts < 5) throw new Error('offline');}});
const loading=loadWorkspace({document,window,createLoader,schedule:callback=>callback()});
await new Promise(resolve=>setImmediate(resolve));
const waiting=Boolean(listeners.online);
@@ -118,7 +125,7 @@ await loading;
console.log(JSON.stringify({attempts,waiting,reloads,status:status.textContent}));
""")
assert result == {
"attempts": 3,
"attempts": 6,
"waiting": True,
"reloads": 0,
"status": "",