Compare commits

...
Author SHA1 Message Date
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
12 changed files with 307 additions and 40 deletions

No files matched your search

+4
View File
@@ -1206,6 +1206,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; }
+9 -8
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(),
});
@@ -1700,7 +1701,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 +2052,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 +2194,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 +2220,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 +2235,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,
@@ -2971,7 +2972,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');
+7
View File
@@ -1655,12 +1655,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>
+43 -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,5 @@
options.eventTarget?.addEventListener('offline', render);
}
return {required, open, refresh, render, start};
return {required, open, refresh, render, start, completeOutcome, adoptRemote};
});
+27 -5
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.
}
@@ -123,7 +133,7 @@ function createTodaySync({ storage, getLogin, fetchJson, onRemoteIds, onRemotePl
}
const operation = record?.operation;
const valid = operation && typeof operation.operation_id === 'string' &&
['add', 'remove', 'move', 'configure', 'rollover'].includes(operation.action) &&
['add', 'remove', 'move', 'configure', 'rollover', 'activate'].includes(operation.action) &&
typeof operation.item_id === 'string' && Number.isFinite(Number(record.queued_at));
if (valid) records.push({ ...record, recordKey });
else {
@@ -151,7 +161,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 +186,7 @@ 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 enqueue(action, itemId, direction = null, fields = {}) {
const operations = pending();
if (action === 'remove' && operations.some(operation =>
operation.action === 'remove' && operation.item_id === itemId
@@ -186,7 +196,7 @@ 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;
@@ -223,6 +233,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 = {
@@ -323,6 +342,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 +354,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, enqueueConfiguration, enqueueActivation, enqueueRollover, migrate, flush, pending, startLifecycle };
}
if (typeof module !== 'undefined' && module.exports) module.exports = createTodaySync;
+9 -1
View File
@@ -553,7 +553,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 +562,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 +581,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 +597,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
+22 -2
View File
@@ -180,6 +180,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 +188,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 +200,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 +211,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:
@@ -598,6 +603,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 +627,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 +646,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 +659,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 +676,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 +723,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 +781,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 +807,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()
+61 -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(
"""
@@ -155,9 +202,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
@@ -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
+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():
+37
View File
@@ -188,6 +188,43 @@ sync.enqueueConfiguration(120, {{'issue:r:1:':60}});
}
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()