Compare commits

...

3 Commits

Author SHA1 Message Date
6c2e457225 T14.3 (D26, BL-061): the sync badge shows the true state and gets out of the way
The badge words live in one function, badgeModel(). States: sending, retrying,
held for sign-in, not saved on this device, rejected (with the reason), read and
queue, another person's changes, and all sent. Every state names the project.
Sign in is a real link to login.html?next=. Dismiss is a real button and removes
only the changes the project refused. Both are 44px or more with a focus ring.

BL-061: the console pages (Admin, User Directory) never show the badge. All sent
shows only after real work. The badge picks a free spot on the screen. One very
dense screen case is left and logged as BL-072.

tests/sync_badge_check.py (87 checks). autosave_check reads the new badge words.
2026-10-17 15:12:25 -07:00
b78b9b3707 docs: remove stray merge markers from backlog.md
Three conflict marker lines (ours, divider, theirs) were committed in an earlier
merge. Both sides are separate items (BL-069 and BL-062 to BL-068), so only the
marker lines are removed. No item text changed.
2026-10-17 14:47:54 -07:00
40827d5371 T14.2 (D27): the offline sign-in window follows the server
/api/auth/me returns session_expires_at (the session token exp, UTC). The browser
keeps it and never extends it: the fixed 12 hours and the sliding reset are gone.
Offline before that time the app opens as normal. Offline after it the app opens in
read-and-queue mode: no redirect, one mode line, changes are queued and held until
a page load gets a good answer from the server. wpCacheAuth refreshes the cached
user without moving the end time.

D26 and D27 recorded as Accepted. tests/session_expiry_check.py (22 checks) fails
against the old 12 hour rule.
2026-10-17 14:18:53 -07:00
12 changed files with 858 additions and 96 deletions

View File

@@ -696,8 +696,9 @@ deliberately deferred.
- **Suggested wave or follow-up:** wave 14, alongside T14.1's badge changes:
do not show the badge on pages with nothing to sync, and keep it clear of
page controls.
- **Status:** fixed at T14.3 (2026-10-17). The console pages never show the badge, "Everything sent" shows only
after real work, and the badge moves to a free spot. One dense-screen case is left: BL-072.
<<<<<<< ours
### BL-069 - The sync has no cap on one run and no last-admin guard
- **Found during:** T13.3 (D18)
@@ -714,7 +715,6 @@ deliberately deferred.
- **Suggested wave or follow-up:** before the first live run, or in T13.6 if
Matt decides. Needs Matt.
=======
## Future build: mobile app and scaling
Logged 2026-10-12 from the meeting with Nick. The answers are in
@@ -816,7 +816,6 @@ boundary"). Do not use `localStorage` as the store of record.
- **Related:** BL-019 (closed) made a stored code that has left the list stay
as an option. Keep that behavior when the list changes.
- **Suggested wave or follow-up:** future wave, after the codes arrive.
>>>>>>> theirs
### BL-070 - Shell scripts get CRLF line endings on Windows, and the backup container cannot start
@@ -841,3 +840,16 @@ boundary"). Do not use `localStorage` as the store of record.
- **Why not now:** it is a test-script quirk and not part of D18. The documented usage lines show `http://localhost:8000`.
- **Suggested wave or follow-up:** next housekeeping pass: use the domain `localhost.local` for a dotless host,
or change the usage lines to `127.0.0.1`.
### BL-072 - The sync badge can cover a control on a very dense screen
- **Found during:** T14.3 (D26, BL-061)
- **Where:** `html/project-data.js` `placeBadge()`; seen on `wp-creation-index.html` at 390px
- **What:** the badge looks for a free spot on the screen, and it covers no control when the screen has room for it.
With the longest state (a change refused by the project, with a long reason) on the creator page at 390px, no free
spot of that size exists. The badge then covers the one control it overlaps least ("Load sample data" at the
time of the check). The person can press Dismiss, or scroll (the badge moves again within 2 seconds).
- **Why not now:** a fixed overlay cannot fix a screen with no gap. The real fix is a layout change: a bar that
takes its own space in the page, or a place for it in the shared header. That is a design decision for all pages,
not part of T14.3.
- **Suggested wave or follow-up:** decide with Nick whether the shared page layout reserves a status line.

View File

@@ -1,8 +1,13 @@
# Decisions: October 17, 2026
Status key: **Proposed** means the text is a recommendation. It needs Matt's OK before any build starts.
**Accepted** means Matt approved it and the work may start.
## D26: a sign-in problem never destroys a queued change (Proposed)
Matt accepted D26 and D27 as written on 2026-10-17 (open questions 1, 2 and 3 in `wave-14.md`: hold the changes of
another person, the offline window ends with the session and then works in read-and-queue mode, and a full device
keeps the change in memory and tells the person). The idle time (question 4) was not decided. It belongs to `T13.1`.
## D26: a sign-in problem never destroys a queued change (Accepted)
**Why:** The outbox (`html/project-data.js`) marks any `4xx` answer except `429` as dead. A `401` means the session ended, and it
gets the same treatment. With a session limit (D25, 8 hours) or an idle timeout (T13.1), a crew that works offline past the limit
@@ -18,7 +23,7 @@ change under whoever is signed in, not under the person who made it.
**Tasks:** `T14.1`, `T14.3`. **Needs Matt:** open questions 1 and 3 in `wave-14.md`.
## D27: the offline sign-in window follows the server (Proposed)
## D27: the offline sign-in window follows the server (Accepted)
**Why:** `auth-guard.js` allows the app to open offline for a fixed 12 hours after the last good check, and every page load resets that
time. The server session lasts 8 hours (D25). The two do not agree.

View File

@@ -2,7 +2,7 @@
**Items:** `D26`, `D27`, `BL-061` (`B5` is context only: its wording rules stay, and this wave does not widen it)
**Depends on:** wave 13 merged (it is, except T13.1). Independent of wave 15.
**Decision record:** `docs/waves/decisions-2026-10-17.md` (D26 and D27 are **proposed**; they need Matt's OK, see "Open questions")
**Decision record:** `docs/waves/decisions-2026-10-17.md` (D26 and D27 are **accepted** as of 2026-10-17, see "Open questions")
**Unblocks:** `T13.1` (idle timeout). T13.1 must not reach `main` before T14.1 and T14.2 are done.
**Branch rule:** one task for each pull request. Cut each branch from `main`.
@@ -63,13 +63,15 @@ badge is a `div` with `pointer-events:none`. A badge that must ask a person to s
**Done when:**
- [ ] a queue of N changes meets a `401`: all N are still in the queue, none is dead, `tries` did not change, and the badge state is "held"
- [ ] after a good sign-in, all N changes reach the server in their original order, and the queue is empty
- [ ] a `403` marks only that change dead, with a reason that names the cause
- [ ] a full device store (a forced `QuotaExceededError`) is reported to the caller and the badge. No change disappears silently
- [ ] a change queued by person A is not sent when person B is signed in; it is sent after A signs in
- [ ] `tests/outbox_check.py` covers each case above and fails when `flush()` is put back to the old rule (a mutation check)
- [ ] the full suite passes, at 390 px and 1440 px
- [x] a queue of N changes meets a `401`: all N are still in the queue, none is dead, `tries` did not change, and the badge state is "held"
- [x] after a good sign-in, all N changes reach the server in their original order, and the queue is empty
- [x] a `403` marks only that change dead, with a reason that names the cause
- [x] a full device store (a forced `QuotaExceededError`) is reported to the caller and the badge. No change disappears silently
- [x] a change queued by person A is not sent when person B is signed in; it is sent after A signs in
- [x] `tests/outbox_check.py` covers each case above and fails when `flush()` is put back to the old rule (a mutation check)
- [x] the full suite passes (2026-10-17: 52 of 54 checks pass; the 2 others are `generalinfo_check` and `token_check`, known and not regressions). `mobile_check` covers 390 px. No before and after screenshots were taken: the badge looks the same until T14.3. The badge words for the new states are plain text. T14.3 gives them their final wording and the Sign in control.
**Built (2026-10-17):** commit `73f0b5e`. Open question 1 as accepted: another person's changes are held and the badge names the owner. A change queued before the sign-in check finished has no owner and can be sent by anyone, as before.
---
@@ -99,12 +101,14 @@ badge is a `div` with `pointer-events:none`. A badge that must ask a person to s
**Done when:**
- [ ] `/api/auth/me` returns `session_expires_at`, and it matches the token (`tests/` check, no database change)
- [ ] the fixed 12 hours is gone from `auth-guard.js`
- [ ] opening the app offline before the time works; opening it offline after the time gives read-and-queue mode and does not redirect
- [ ] online with a dead session: redirect to `login.html?next=...`, queue kept, changes sent after sign-in
- [ ] a page load does not extend the cached window
- [ ] the mode line is announced by a screen reader (`aria-live`) and fits at 390 px
- [x] `/api/auth/me` returns `session_expires_at`, and it matches the token (`tests/session_expiry_check.py`, no database change)
- [x] the fixed 12 hours is gone from `auth-guard.js`
- [x] opening the app offline before the time works; opening it offline after the time gives read-and-queue mode and does not redirect
- [x] online with a dead session: redirect to `login.html?next=...`, queue kept, changes sent after sign-in (the send after sign-in is the T14.1 test, section 3)
- [x] a page load does not extend the cached window
- [x] the mode line is announced by a screen reader (`aria-live`) and fits at 390 px. The line is in the badge, which has `role="status"`. T14.3 checks that it fits at 390 px and covers no control (`sync_badge_check.py`, state `readqueue`). It was **not** tried with a real screen reader.
**Built (2026-10-17):** `tests/session_expiry_check.py` (22 checks) fails when the old 12 hour rule is put back (7 failures). The mode line shows only in read-and-queue mode, not when the app opens offline before the session ends, because "sign in again" would be wrong while the session is still good. In read-and-queue mode the outbox does not send at all until a page load gets a good answer from the server. Saving display preferences refreshes the cached user and keeps the end time (`wpCacheAuth`).
---
@@ -130,12 +134,14 @@ badge is a `div` with `pointer-events:none`. A badge that must ask a person to s
**Done when:**
- [ ] each state shows in a browser test, with its text, at 390 px and 1440 px
- [ ] "Sign in" works with the keyboard and by touch, and goes to `login.html?next=...`
- [ ] the badge covers no control on the User Directory at 1440 px or the bulk bar at 390 px (the two places `BL-061` named)
- [ ] no badge on the console pages
- [ ] the contrast check passes for every state
- [ ] `autosave_check.py` and `a11y_check.py` pass
- [x] each state shows in a browser test, with its text (`tests/sync_badge_check.py`). The states are checked at 1440 px; the placement is checked at 390 px and 1440 px
- [x] "Sign in" is a real link (`<a>`), reachable by keyboard, 44 px or more, with a focus ring, and goes to `login.html?next=...`. Touch is covered by the size and by the element type: no touch event was sent
- [x] the badge covers no control on the User Directory or the bulk bar: the console pages never show it (`data-wp-no-sync-badge`)
- [x] no badge on the console pages
- [x] the contrast check passes for every state (4.5:1 or better, light theme only; the dark theme was **not** checked)
- [x] `autosave_check.py` and `a11y_check.py` pass. Full suite 2026-10-17: 53 of 55 pass; `generalinfo_check` and `token_check` fail as before (known, not regressions). `sync_badge_check.py` (87 checks) fails when the "nothing to send" rule and the console opt-out are removed (3 failures)
**Built (2026-10-17):** the badge words are in one function, `badgeModel()`. The mode line for read-and-queue mode now says "...to send your changes to the project." so it follows the B5 rule. "Dismiss" removes only the changes the project refused, after the person presses it. The badge picks a free spot on the screen (BL-061). One case is left, a very dense screen with no free gap: `BL-072`. No before and after screenshots were taken: the check measures overlap in the browser instead. A person should look at the badge once on a phone.
---
@@ -160,7 +166,9 @@ T13.1 (`6cde6e3`) onto `main`, run `tests/session_idle_check.py` and the same ha
---
## Open questions (needs Matt before T14.1 and T14.2 start)
## Open questions
**Answered 2026-10-17 (Matt accepted the proposal for questions 1, 2 and 3).** Question 4 is still open and belongs to `T13.1`.
1. **Shared devices.** If person B signs in on a device that holds unsent changes from person A, what must happen?
Proposed: hold A's changes, name A in the badge, send them when A signs in. Do not send them as B and do not discard them.

View File

@@ -58,7 +58,7 @@
}
</style>
</head>
<body>
<body data-wp-no-sync-badge>
<!-- SHARED DARK APP BAR -->
<header class="wp-appbar">

View File

@@ -163,6 +163,31 @@
}
}
// D27. The offline sign-in window is the SERVER session, not a timer of the
// browser's own. /api/auth/me returns `session_expires_at` (the session token's
// exp), and that is what the cache keeps. Only a good answer from the server
// changes it: loading a page offline, or saving preferences, never extends it.
// (This replaced a fixed 12 hour window that slid forward on every page load and
// disagreed with AUTH_SESSION_HOURS.)
function readAuthCache() {
try { return JSON.parse(localStorage.getItem('wp_auth_cache') || 'null'); } catch (e) { return null; }
}
function writeAuthCache(user, expMs) {
try { if (user) localStorage.setItem('wp_auth_cache', JSON.stringify({ user: user, exp: expMs || 0, at: Date.now() })); } catch (e) {}
}
// For callers that refresh the cached user (the preferences dialog): the user
// changes, the end of the session does not.
window.wpCacheAuth = function (user) {
var c = readAuthCache();
writeAuthCache(user, c && c.exp);
};
// 'online' (a good answer from the server), 'offline' (opened from the cache
// before the session ended) or 'readqueue' (opened from the cache after it ended:
// cached data can be read and changes are queued, but nothing is sent until a
// good sign-in). The sync badge shows the one line for 'readqueue'.
window.WP_SESSION_MODE = 'online';
fetch('/api/auth/me', { headers: { 'Accept': 'application/json' } })
.then(function (r) {
if (r.status === 401 || r.status === 403) { try { localStorage.removeItem('wp_auth_cache'); } catch (e) {} goToLogin(); return; }
@@ -171,17 +196,26 @@
var user = data && data.user;
// Remember the last good auth so the PWA can open offline. The server is
// still the real gate; offline writes queue in the outbox until reconnect.
try { if (user) localStorage.setItem('wp_auth_cache', JSON.stringify({ user: user, at: Date.now() })); } catch (e) {}
var expMs = data && data.session_expires_at ? Date.parse(data.session_expires_at) : 0;
writeAuthCache(user, isNaN(expMs) ? 0 : expMs);
proceed(user);
});
})
.catch(function () {
// Offline / API unreachable: fall back to a recent cached auth if present,
// so the app (and the field view) still open without a network.
try {
var c = JSON.parse(localStorage.getItem('wp_auth_cache') || 'null');
if (c && c.user && (Date.now() - (c.at || 0)) < 12 * 3600 * 1000) { proceed(c.user); return; }
} catch (e) {}
// Offline / API unreachable: open from the cached sign-in so the app (and the
// field view) still work without a network. With no cache this device has
// never signed in, so there is nothing to open: go to the sign-in page.
var c = readAuthCache();
if (c && c.user) {
// Before the session ends: open as normal. After it (or when the cache has
// no end time, an older cache): read and queue. The page does NOT redirect,
// because login.html cannot reach Okta without a network.
var live = !!c.exp && Date.now() < c.exp;
window.WP_SESSION_MODE = live ? 'offline' : 'readqueue';
proceed(c.user);
try { document.dispatchEvent(new CustomEvent('wp-session-mode', { detail: window.WP_SESSION_MODE })); } catch (e) {}
return;
}
goToLogin();
});
})();

View File

@@ -276,6 +276,7 @@
_mem = _mem.filter(function (o) { return o.opId !== opId; });
qWrite(qRead().filter(function (o) { return o.opId !== opId; }));
}
function readQueueMode() { try { return window.WP_SESSION_MODE === 'readqueue'; } catch (e) { return false; } }
function sameUser(a, b) { return String(a || '').toLowerCase() === String(b || '').toLowerCase(); }
// Append an op, coalescing by (kind,key) so only the latest write per entity is
@@ -347,7 +348,9 @@
// (429/5xx/network) stay queued.
function flush() {
if (_flushing) return Promise.resolve();
if (_held) { notifySync(); return Promise.resolve(); }
// D27: opened offline after the session ended (read and queue). Changes are kept
// and wait; nothing is sent until a page load gets a good answer from the server.
if (_held || readQueueMode()) { notifySync(); return Promise.resolve(); }
var q = sendableOps();
if (!q.length) { notifySync(); return Promise.resolve(); }
_flushing = true; notifySync();
@@ -420,74 +423,212 @@
renderSyncBadge(c);
}
// Tiny sync indicator (bottom-left). This was gated on being the top-level
// window so it was not drawn twice - once by the suite page and again inside
// the embedded creator. B7/T7.1 dissolved that frame, so there is one document
// and one badge. The 'storage' listener below stays: it is what keeps two
// TABS in step, which is a different thing and still happens.
var _badgeHideTimer = null;
// The sync badge (D26, BL-061). It reports the OUTBOX: whether saved records have
// reached the project. This was gated on being the top-level window so it was not
// drawn twice (the suite page and the embedded creator); B7/T7.1 dissolved that
// frame, so there is one document and one badge. The 'storage' listener below
// stays: it is what keeps two TABS in step, which is a different thing.
var _badgeHideTimer = null, _badgePlaceTimer = null, _hadWork = false;
// BL-011 (fixed at T9.9): the badge used to mount on the FIRST SYNC EVENT,
// which is async, so the three fixed overlays on the SOP page landed in a
// different DOM order run to run and every index-keyed comparison saw
// phantom diffs. Mounting the (hidden) holder at DOMContentLoaded puts the
// three in script order, deterministically.
document.addEventListener('DOMContentLoaded', function () { renderSyncBadge(null); });
// BL-061: the console pages (Admin, User Directory) never queue project work, and
// the badge used to sit over their bottom-right buttons. They opt out with
// data-wp-no-sync-badge on <body>.
function badgeExempt() { return !!(document.body && document.body.hasAttribute('data-wp-no-sync-badge')); }
// Discard the changes the project refused. The person has read the reason and
// chose to dismiss it; nothing else ever removes a queued change by itself.
function dismissRejected() {
_mem = _mem.filter(function (o) { return !o.dead; });
qWrite(qRead().filter(function (o) { return !o.dead; }));
notifySync();
}
function signInUrl() {
return 'login.html?next=' + encodeURIComponent(location.pathname + location.search);
}
// One place decides what the badge says. B5: every string names the PROJECT, so it
// cannot be read as the draft indicator (WPAutosave.mountIndicator), which speaks
// for the form. tone is one of neutral, ok, warn, error.
function badgeModel(c) {
var n;
if (c.deviceFull) {
n = c.unsaved;
return { tone: 'error', text: '✕ ' + n + ' change' + (n === 1 ? ' is' : 's are') + ' not saved on this device. Keep this page open until it is sent to the project.' };
}
if (readQueueMode()) {
return { tone: 'warn', text: 'Working offline. Sign in again when you have a signal to send your changes to the project.', signIn: true };
}
if (c.held) {
return { tone: 'warn', text: '⚠ Sign in again to send your changes to the project. They are kept on this device.', signIn: true };
}
if (c.dead) {
return { tone: 'error', text: '✕ ' + c.dead + ' change' + (c.dead === 1 ? '' : 's') + ' rejected by the project. Not saved.', reason: c.reason, dismiss: true };
}
if (c.failed) {
return { tone: 'warn', text: '⚠ ' + c.failed + ' change' + (c.failed === 1 ? '' : 's') + ' not yet sent to the project. Retrying.' };
}
if (c.pending) {
return { tone: 'neutral', text: '↻ Sending ' + c.pending + ' change' + (c.pending === 1 ? '' : 's') + ' to the project…' };
}
if (c.others) {
return { tone: 'warn', text: '⚠ ' + c.others + ' change' + (c.others === 1 ? ' belongs' : 's belong') + ' to ' + c.otherOwner + '. ' + (c.others === 1 ? 'It goes' : 'They go') + ' to the project when ' + c.otherOwner + ' signs in.' };
}
// Nothing to report. "Everything sent" follows real work only: on a page that
// never queued anything it is noise that sits over the controls (BL-061).
if (!_hadWork) return null;
return { tone: 'ok', text: '✓ Everything sent to the project', autoHide: true };
}
var TONES = {
neutral: ['var(--cds-text-secondary)', 'var(--cds-border-subtle)', 'var(--cds-layer)'],
ok: ['var(--wp-status-success-text)', 'var(--wp-status-success-border-a)', 'var(--wp-status-success-bg)'],
warn: ['var(--wp-status-warning-text)', 'var(--cds-support-warning)', 'var(--wp-status-warning-bg)'],
error: ['var(--wp-status-error-text)', 'var(--wp-status-error-border-a)', 'var(--wp-status-error-bg)']
};
function ensureBadgeStyle() {
if (document.getElementById('wp-sync-badge-style')) return;
var st = document.createElement('style');
st.id = 'wp-sync-badge-style';
// Controls are real <a> and <button> elements: reachable by keyboard and touch,
// at least 44px high, with a focus ring from the shared focus token.
st.textContent =
'#wp-sync-badge{max-width:min(420px,calc(100vw - 24px));box-sizing:border-box}' +
'@media (max-width:480px){#wp-sync-badge{max-width:min(300px,calc(100vw - 24px))}}' +
'#wp-sync-badge .wp-sb-msg{display:flex;flex-direction:column;gap:2px;min-width:0}' +
'#wp-sync-badge .wp-sb-reason{font-weight:400}' +
'#wp-sync-badge .wp-sb-ctl{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;' +
'min-width:44px;min-height:44px;padding:0 10px;margin:-6px -12px -6px -4px;border:0;background:transparent;color:inherit;' +
'font-family:inherit;font-weight:600;font-size:12px;line-height:1.3;text-decoration:underline;cursor:pointer}' +
'#wp-sync-badge .wp-sb-ctl:focus-visible{outline:2px solid var(--cds-focus);outline-offset:-2px}';
(document.head || document.documentElement).appendChild(st);
}
// BL-061: keep the badge clear of page controls. Measure every visible control,
// then put the badge in the first free spot: the four corners first, then any gap
// on the screen that is big enough, scanning from the bottom up. Page headers and
// bottom bars fill the width at 390px, so fixed corners alone cannot clear them.
// If no spot is free, take the one that covers the fewest controls.
var CONTROLS = 'a[href],button,input,select,textarea,summary,[role="button"],[tabindex]:not([tabindex="-1"])';
function controlRects(el) {
var out = [], list = document.querySelectorAll(CONTROLS);
for (var i = 0; i < list.length; i++) {
var o = list[i];
if (o === el || el.contains(o)) continue;
var b = o.getBoundingClientRect();
if (!b.width || !b.height || !o.getClientRects().length) continue;
var cs = window.getComputedStyle(o);
if (cs.visibility === 'hidden' || cs.display === 'none') continue;
out.push(b);
}
return out;
}
function hitCount(rects, x, y, w, h) {
var n = 0;
for (var i = 0; i < rects.length; i++) {
var b = rects[i];
if (b.left < x + w && b.right > x && b.top < y + h && b.bottom > y) n++;
}
return n;
}
function placeBadge(el) {
if (el.style.display === 'none') return;
var vw = document.documentElement.clientWidth, vh = window.innerHeight;
// Measure at the left edge, where the box has all the room it will ever have,
// then pin that width: a box measured near the right edge wraps and grows.
el.style.width = ''; el.style.right = 'auto'; el.style.bottom = 'auto';
el.style.left = '0px'; el.style.top = '0px';
var r = el.getBoundingClientRect(), w = Math.ceil(r.width), h = Math.ceil(r.height), m = 12;
el.style.width = w + 'px';
var rects = controlRects(el);
var spots = [
[vw - w - m, vh - h - m], [m, vh - h - m], [vw - w - m, m], [m, m]
];
// Then every gap, bottom to top, right to left, in 8px steps.
for (var y = vh - h - m; y >= m; y -= 8) {
for (var x = vw - w - m; x >= m; x -= 8) spots.push([x, y]);
}
var best = spots[0], bestN = Infinity;
for (var i = 0; i < spots.length; i++) {
var n = hitCount(rects, spots[i][0], spots[i][1], w, h);
if (n < bestN) { bestN = n; best = spots[i]; }
if (n === 0) break;
}
el.style.right = 'auto'; el.style.bottom = 'auto';
el.style.left = Math.max(0, Math.round(best[0])) + 'px';
el.style.top = Math.max(0, Math.round(best[1])) + 'px';
}
function renderSyncBadge(c) {
if (!document.body) return;
var el = document.getElementById('wp-sync-badge');
if (!el) {
ensureBadgeStyle();
el = document.createElement('div');
el.id = 'wp-sync-badge';
// S10. Polite: this reports background syncing, and interrupting someone to
// say a queue drained is exactly the noise that gets aria-live turned off.
el.setAttribute('role', 'status');
el.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:9998;pointer-events:none;display:none;align-items:center;gap:7px;' +
el.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:9998;pointer-events:none;display:none;align-items:center;gap:12px;' +
'font:500 12px/1.3 "IBM Plex Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;' +
'padding:6px 12px;border:1px solid var(--cds-border-subtle);background:var(--cds-layer);color:var(--cds-text-secondary);box-shadow:0 1px 4px rgba(0,0,0,.12);transition:opacity .2s;';
document.body.appendChild(el);
window.addEventListener('resize', function () { placeBadge(el); });
}
if (!c) return; // the eager DOMContentLoaded mount: holder only, no state yet
if (_badgeHideTimer) { clearTimeout(_badgeHideTimer); _badgeHideTimer = null; }
// A dead op is a refusal, not a hiccup — "retrying" would be a lie, and the
// reason is the only thing that tells the user what to do (e.g. the project is
// archived). Stack it under the headline; the badge never hides in this state.
el.style.flexDirection = c.dead ? 'column' : 'row';
el.style.alignItems = c.dead ? 'flex-start' : 'center';
el.style.maxWidth = c.dead ? 'min(340px, calc(100vw - 32px))' : 'none';
// B5. This badge reports the OUTBOX — whether saved records have reached the
// project — and it used to say "✓ All changes saved", which is what a draft
// autosave says. So the app was already making the promise B5 says it does not
// keep: the badge went green when the queue emptied, whether or not anything in
// the form had been saved at all.
//
// Every string here now names the project explicitly. The draft indicator
// (WPAutosave.mountIndicator) is the one that speaks for the form, and the two
// can no longer be read as each other.
// D26. These three are the states that used to be invisible or wrong. T14.3
// gives them their final wording and controls; until then they are plain text.
if (c.deviceFull) {
el.textContent = '✕ ' + c.unsaved + ' change' + (c.unsaved === 1 ? ' is' : 's are') + ' not saved on this device. Keep this page open until it is sent to the project.';
el.style.color = 'var(--wp-status-error-text)'; el.style.borderColor = 'var(--wp-status-error-border-a)'; el.style.background = 'var(--wp-status-error-bg)'; el.style.display = 'inline-flex';
} else if (c.held) {
el.textContent = '⚠ Sign in again to send your changes to the project. They are kept on this device.';
el.style.color = 'var(--wp-status-warning-text)'; el.style.borderColor = 'var(--cds-support-warning)'; el.style.background = 'var(--wp-status-warning-bg)'; el.style.display = 'inline-flex';
} else if (c.dead) {
el.innerHTML = '<span>✕ ' + c.dead + ' change' + (c.dead === 1 ? '' : 's') + ' rejected by the project — not saved</span>' +
(c.reason ? '<span style="font-weight:400">' + esc(c.reason) + '</span>' : '');
el.style.color = 'var(--wp-status-error-text)'; el.style.borderColor = 'var(--wp-status-error-border-a)'; el.style.background = 'var(--wp-status-error-bg)'; el.style.display = 'inline-flex';
} else if (c.failed) {
el.textContent = '⚠ ' + c.failed + ' change' + (c.failed === 1 ? '' : 's') + ' not yet sent to the project — retrying';
el.style.color = 'var(--wp-status-warning-text)'; el.style.borderColor = 'var(--cds-support-warning)'; el.style.background = 'var(--wp-status-warning-bg)'; el.style.display = 'inline-flex';
} else if (c.pending) {
el.textContent = '↻ Sending ' + c.pending + ' change' + (c.pending === 1 ? '' : 's') + ' to the project…';
el.style.color = 'var(--cds-text-secondary)'; el.style.borderColor = 'var(--cds-border-subtle)'; el.style.background = 'var(--cds-layer)'; el.style.display = 'inline-flex';
} else if (c.others) {
el.textContent = '⚠ ' + c.others + ' change' + (c.others === 1 ? ' belongs' : 's belong') + ' to ' + c.otherOwner + '. ' + (c.others === 1 ? 'It goes' : 'They go') + ' to the project when ' + c.otherOwner + ' signs in.';
el.style.color = 'var(--wp-status-warning-text)'; el.style.borderColor = 'var(--cds-support-warning)'; el.style.background = 'var(--wp-status-warning-bg)'; el.style.display = 'inline-flex';
} else {
el.textContent = '✓ Everything sent to the project';
el.style.color = 'var(--wp-status-success-text)'; el.style.borderColor = 'var(--wp-status-success-border-a)'; el.style.background = 'var(--wp-status-success-bg)'; el.style.display = 'inline-flex';
if (_badgePlaceTimer) { clearInterval(_badgePlaceTimer); _badgePlaceTimer = null; }
if (c.pending || c.failed || c.held || c.others || c.deviceFull) _hadWork = true;
var m = badgeExempt() ? null : badgeModel(c);
if (!m) { el.style.display = 'none'; el.style.pointerEvents = 'none'; return; }
var t = TONES[m.tone] || TONES.neutral;
el.style.color = t[0]; el.style.borderColor = t[1]; el.style.background = t[2];
el.style.pointerEvents = (m.signIn || m.dismiss) ? 'auto' : 'none';
// Rebuild the contents. The container keeps role="status", so a change of text
// is announced; the controls inside it are ordinary focusable elements.
while (el.firstChild) el.removeChild(el.firstChild);
var msg = document.createElement('span');
msg.className = 'wp-sb-msg';
var head = document.createElement('span');
head.textContent = m.text;
msg.appendChild(head);
if (m.reason) {
var why = document.createElement('span');
why.className = 'wp-sb-reason';
why.textContent = String(m.reason);
msg.appendChild(why);
}
el.appendChild(msg);
if (m.signIn) {
var a = document.createElement('a');
a.className = 'wp-sb-ctl';
a.href = signInUrl();
a.textContent = 'Sign in';
el.appendChild(a);
}
if (m.dismiss) {
var d = document.createElement('button');
d.type = 'button';
d.className = 'wp-sb-ctl';
d.textContent = 'Dismiss';
d.addEventListener('click', dismissRejected);
el.appendChild(d);
}
el.style.display = 'inline-flex';
placeBadge(el);
if (m.autoHide) {
_hadWork = false; // the next "sent" needs new work
_badgeHideTimer = setTimeout(function () { if (el) el.style.display = 'none'; }, 1800);
} else {
// A state that stays: re-check the spot now and then, since the page under it changes.
_badgePlaceTimer = setInterval(function () { placeBadge(el); }, 2000);
}
}
@@ -501,6 +642,7 @@
// D26: the one thing that releases a held queue. auth-guard fires this after a
// good /api/auth/me (or the offline cache), and the next flush finds out for
// itself whether the session is really good: a 401 holds the queue again.
document.addEventListener('wp-session-mode', function () { notifySync(); });
document.addEventListener('wp-auth-ready', function () { _held = false; _backoff = 0; notifySync(); scheduleFlush(0); });
} catch (e) {}
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { notifySync(); scheduleFlush(0); }); }

View File

@@ -77,7 +77,7 @@
}
</style>
</head>
<body>
<body data-wp-no-sync-badge>
<!-- SHARED DARK APP BAR -->
<header class="wp-appbar">

View File

@@ -220,7 +220,8 @@
.then(function (res) {
if (!res.ok) { msg((res.j && res.j.detail) || ('Could not save (HTTP ' + res.status + ').'), false); return; }
if (res.j && res.j.user) window.WP_USER = res.j.user;
try { localStorage.setItem('wp_auth_cache', JSON.stringify({ user: window.WP_USER, at: Date.now() })); } catch (e) {}
// D27: refresh the cached user, but not the end of the session.
try { if (window.wpCacheAuth) window.wpCacheAuth(window.WP_USER); } catch (e) {}
msg('Saved. Reloading so every date on the page agrees…', true);
// Dates are formatted at render time all over the app; a reload is the
// honest way to apply the change everywhere at once.

View File

@@ -834,12 +834,22 @@ if okta_fake.is_active():
@app.get("/api/auth/me")
def whoami(user: models.User = Depends(auth.get_current_user)):
def whoami(request: Request, user: models.User = Depends(auth.get_current_user)):
"""Who is logged in. The frontend guard calls this on every page load.
`role` is normalized here so no page has to know that a pre-roles account stores
'user' where it now means 'project_user'."""
return {"user": {**user.to_dict(), "role": auth.normalize_role(user.role)}}
'user' where it now means 'project_user'.
D27: `session_expires_at` is the `exp` claim of the session token, as a UTC time.
The browser keeps it so the offline sign-in window ends when the server session
ends. No column holds it: get_current_user has already validated this token, so
the claim is read back from the same cookie."""
claims = auth.is_request_authenticated(request) or {}
exp = claims.get("exp")
expires_at = (datetime.fromtimestamp(exp, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if isinstance(exp, (int, float)) else None)
return {"user": {**user.to_dict(), "role": auth.normalize_role(user.role)},
"session_expires_at": expires_at}
# ── Display preferences (self-service) ─────────────────────────────────────────

View File

@@ -241,18 +241,16 @@ def main():
# Only what the badge RENDERS counts. The phrase still appears in the
# comment explaining why it was changed, and asserting on that would be
# asserting that the reason cannot be written down.
rendered = [ln for ln in src.split("\n")
if ("el.textContent" in ln or "el.innerHTML" in ln)
and "All changes saved" in ln]
# T14.3: the badge's words now live in one place, badgeModel(), as
# `text: '...'` entries. Those are the lines that render.
texts = [ln for ln in src.split("\n") if "text: '" in ln and "tone: '" in ln]
rendered = [ln for ln in texts if "All changes saved" in ln]
chk("the badge no longer renders 'All changes saved'", not rendered, rendered[:1])
chk("the badge words were found (a rename must not make this check empty)", len(texts) >= 7,
"found %d" % len(texts))
chk("...and every state it renders names the project",
all("the project" in ln
for ln in src.split("\n")
if ("el.textContent = '" in ln or "el.innerHTML = '" in ln)
and "wp-sync-badge" not in ln and ("✓" in ln or "⚠" in ln or "↻" in ln or "✕" in ln)),
[ln.strip()[:70] for ln in src.split("\n")
if ("el.textContent = '" in ln or "el.innerHTML = '" in ln)
and "the project" not in ln and ("✓" in ln or "⚠" in ln or "↻" in ln or "✕" in ln)])
all("the project" in ln for ln in texts),
[ln.strip()[:70] for ln in texts if "the project" not in ln])
print("\n7. autosave's own registration survives the retired analytics tracker")
# This section used to also assert the per-browser usage-analytics dwell

View File

@@ -0,0 +1,220 @@
#!/usr/bin/env python3
"""Does the offline sign-in window follow the server? - D27 / T14.2.
auth-guard.js used to let the app open offline for a fixed 12 hours after the last
good check, and every page load reset that time. The server session lasts
AUTH_SESSION_HOURS (8). This check proves the browser now uses the server's own end
time.
1. /api/auth/me returns session_expires_at and it matches the token's exp
2. the browser keeps it, and the fixed 12 hours is gone from the code
3. offline before that time: the app opens as normal
4. offline after that time: read and queue. No redirect, the mode line shows,
a new change is queued and held, not sent
5. an older cache with no end time is treated as ended (no hidden 12 hours)
6. a page load offline does not extend the cached window
7. no cache at all, offline: sign-in page
8. online with a dead session: sign-in page with next=, and the outbox is kept
9. refreshing the cached user keeps the end of the session
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import base64
import calendar
import json
import os
import re
import subprocess
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
HERE = os.path.dirname(os.path.abspath(__file__))
HTML = os.path.join(os.path.dirname(HERE), "html")
KEY = "wp_sync_outbox_v1"
# Makes /api/auth/me fail like a missing network when localStorage.x_me_offline is set.
OFFLINE_SHIM = """(() => {
const real = window.fetch.bind(window);
window.fetch = function (u, o) {
let off = false; try { off = !!localStorage.getItem('x_me_offline'); } catch (e) {}
if (off && String(u).indexOf('/api/auth/me') !== -1) return Promise.reject(new TypeError('Failed to fetch'));
return real(u, o);
};
})();"""
STUB = """(() => {
if (!window.__realFetch) window.__realFetch = window.fetch.bind(window);
window.__calls = [];
window.fetch = function (url, opts) {
const m = ((opts && opts.method) || 'GET').toUpperCase();
if (m === 'POST' && /\\/api\\/(wps|sops)$/.test(String(url))) {
window.__calls.push(String(url));
return Promise.resolve(new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }));
}
return window.__realFetch(url, opts);
};
return true;
})()"""
def token_exp(token):
body = token.split(".")[1]
body += "=" * (-len(body) % 4)
return int(json.loads(base64.urlsafe_b64decode(body))["exp"])
def cache(page):
return json.loads(page.eval("localStorage.getItem('wp_auth_cache') || 'null'") or "null")
def load(page, base, path="/field.html"):
page.goto(base + path)
time.sleep(2.0)
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
tmpdir = tempfile.mkdtemp(prefix="wpsuite-expiry-")
db_path = os.path.join(tmpdir, "check.db")
server = None
try:
tok = seed(db_path)
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
if server is None:
print("the test server would not start.")
return 2
print("\nThe offline window follows the server - D27 / T14.2\nTarget: %s" % base)
browser = cdp.Browser(exe)
page = browser.page()
try:
page.ws.call("Page.addScriptToEvaluateOnNewDocument", {"source": OFFLINE_SHIM})
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
want = token_exp(tok["root"])
print("\n1-2. the server sends its own end time and the browser keeps it")
load(page, base)
me = page.eval("fetch('/api/auth/me').then(r => r.json())")
got = (me or {}).get("session_expires_at")
chk("/api/auth/me returns session_expires_at", bool(got), json.dumps(me)[:200])
chk("it is a UTC time that matches the token exp",
bool(got) and bool(re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$", got)) and
abs(calendar.timegm(time.strptime(got, "%Y-%m-%dT%H:%M:%SZ")) - want) <= 1,
"%s vs %s" % (got, want))
c = cache(page)
chk("the cache holds the server's end time",
bool(c) and abs((c.get("exp") or 0) / 1000.0 - want) <= 1, json.dumps(c)[:200])
src = open(os.path.join(HTML, "auth-guard.js"), encoding="utf-8").read()
code = re.sub(r"/\*.*?\*/|//[^\n]*", "", src, flags=re.S)
chk("the fixed 12 hours is gone from auth-guard.js", "12 * 3600" not in code and "43200000" not in code)
user = json.dumps(c["user"]) if c else "{}"
now_ms = int(time.time() * 1000)
def set_cache(obj):
page.eval("localStorage.setItem('wp_auth_cache', %s); localStorage.setItem('x_me_offline','1'); true"
% json.dumps(json.dumps(obj)))
print("\n3. offline before the end time: opens as normal")
future = now_ms + 3600 * 1000
set_cache({"user": c["user"], "exp": future, "at": 111})
load(page, base)
chk("no redirect", page.eval("location.pathname") == "/field.html", page.eval("location.href"))
chk("the user is the cached user", page.eval("window.WP_USER && window.WP_USER.username") == "root")
chk("mode is offline, not read-and-queue", page.eval("window.WP_SESSION_MODE") == "offline",
page.eval("window.WP_SESSION_MODE"))
print("\n6. a page load offline does not extend the window")
c2 = cache(page)
chk("the end time did not move", c2 and c2.get("exp") == future, json.dumps(c2))
chk("the cache was not rewritten", c2 and c2.get("at") == 111, json.dumps(c2))
print("\n4. offline after the end time: read and queue")
set_cache({"user": c["user"], "exp": now_ms - 3600 * 1000, "at": now_ms})
load(page, base)
chk("no redirect to the sign-in page", page.eval("location.pathname") == "/field.html",
page.eval("location.href"))
chk("the user is the cached user", page.eval("window.WP_USER && window.WP_USER.username") == "root")
chk("mode is read and queue", page.eval("window.WP_SESSION_MODE") == "readqueue",
page.eval("window.WP_SESSION_MODE"))
badge = page.eval("(document.getElementById('wp-sync-badge')||{}).textContent || ''")
chk("the mode line shows", "Working offline. Sign in again when you have a signal to send your changes to the project." in badge,
badge)
chk("the line sits in the live region",
page.eval("(document.getElementById('wp-sync-badge')||{getAttribute(){}}).getAttribute('role')") == "status")
page.eval(STUB)
page.eval("localStorage.removeItem(%r); ProjectData.pushWP({id:'wp_rq', name:'rq'}, 'projA'); true" % KEY)
page.eval("ProjectData.flushSync()")
time.sleep(0.5)
q = json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
chk("a new change is queued", [o.get("key") for o in q] == ["wp_rq"], json.dumps(q)[:200])
chk("and held: nothing was sent", page.eval("window.__calls") == [], str(page.eval("window.__calls")))
print("\n5. an older cache with no end time counts as ended")
set_cache({"user": c["user"], "at": now_ms})
load(page, base)
chk("read and queue, no redirect, no hidden window",
page.eval("location.pathname") == "/field.html" and page.eval("window.WP_SESSION_MODE") == "readqueue",
page.eval("location.href") + " " + str(page.eval("window.WP_SESSION_MODE")))
print("\n9. refreshing the cached user keeps the end of the session")
set_cache({"user": c["user"], "exp": future, "at": 1})
page.eval("window.wpCacheAuth({username: 'renamed'}); true")
c3 = cache(page)
chk("the user changed", c3 and c3["user"].get("username") == "renamed", json.dumps(c3))
chk("the end time did not", c3 and c3.get("exp") == future, json.dumps(c3))
print("\n7. no cache, offline: the sign-in page")
page.eval("localStorage.removeItem('wp_auth_cache'); localStorage.setItem('x_me_offline','1'); true")
load(page, base)
chk("sent to login.html", page.eval("location.pathname") == "/login.html", page.eval("location.href"))
print("\n8. online with a dead session: sign-in page and the outbox is kept")
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
page.goto(base + "/field.html")
time.sleep(1.5)
page.eval("localStorage.removeItem('x_me_offline'); localStorage.setItem(%r, %s); true" % (
KEY, json.dumps(json.dumps([{"kind": "wp", "key": "wp_keep", "opId": "wp:wp_keep:1", "tries": 0,
"owner": "root", "body": {"id": "wp_keep"}}]))))
page.clear_cookies()
page.set_cookie("wp_session", "not-a-valid-token")
load(page, base)
loc = page.eval("location.pathname + location.search")
chk("online with a dead session: redirect to login.html?next=",
loc.startswith("/login.html") and "next=" in loc, loc)
q = json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
chk("the queued change is still there", [o.get("key") for o in q] == ["wp_keep"], json.dumps(q)[:200])
finally:
page.close()
browser.close()
finally:
if server is not None:
server.kill()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
pass
try:
from server.db import engine
engine.dispose()
except Exception:
pass
print("\n%d passed, %d failed" % (len(_PASS), len(_FAIL)))
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())

332
tests/sync_badge_check.py Normal file
View File

@@ -0,0 +1,332 @@
#!/usr/bin/env python3
"""Does the sync badge tell the truth, work by keyboard and touch, and stay out of
the way? - D26 and BL-061 / T14.3.
1. every state shows, in words that name the PROJECT
2. Sign in and Dismiss are real <a> and <button> elements: focusable, at least
44px, with a visible focus ring. Sign in goes to login.html?next=
3. Dismiss removes only the changes the project refused
4. text contrast is 4.5:1 or better in every state
5. "Everything sent" follows real work and then hides; a page with nothing to
send shows no badge
6. the console pages (Admin, User Directory) never show it
7. at 390 and 1440 the badge covers no visible control on any page that shows it
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import json
import os
import subprocess
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
KEY = "wp_sync_outbox_v1"
STUB = """(() => {
if (!window.__realFetch) window.__realFetch = window.fetch.bind(window);
window.__calls = []; window.__status = 200; window.__never = false;
window.fetch = function (url, opts) {
const m = ((opts && opts.method) || 'GET').toUpperCase();
const u = String(url);
if ((m === 'POST' && /\\/api\\/(wps|sops)$/.test(u)) || (m === 'DELETE' && /\\/api\\/wps\\//.test(u))) {
window.__calls.push(u);
if (window.__never) return new Promise(() => {});
const st = window.__status;
return Promise.resolve(new Response(JSON.stringify(st >= 400 ? { detail: 'The project is archived. Ask an admin to unarchive it.' } : { ok: true }),
{ status: st, headers: { 'Content-Type': 'application/json' } }));
}
return window.__realFetch(url, opts);
};
localStorage.removeItem('wp_sync_outbox_v1');
return true;
})()"""
QUOTA = """(() => {
window.__setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function (k, v) {
if (k === 'wp_sync_outbox_v1') { const e = new Error('full'); e.name = 'QuotaExceededError'; throw e; }
return window.__setItem.call(this, k, v);
};
return true;
})()"""
BADGE = """(() => {
const b = document.getElementById('wp-sync-badge');
if (!b) return JSON.stringify({exists: false});
const cs = getComputedStyle(b);
return JSON.stringify({exists: true, shown: cs.display !== 'none', text: b.textContent,
role: b.getAttribute('role'), ctl: Array.from(b.querySelectorAll('.wp-sb-ctl')).map(e => e.tagName + ':' + e.textContent)});
})()"""
# Contrast of the badge text against its own background (alpha composited on the page).
CONTRAST = """(() => {
const b = document.getElementById('wp-sync-badge');
const parse = s => { const m = s.match(/rgba?\\(([^)]+)\\)/); if (!m) return null;
const p = m[1].split(',').map(x => parseFloat(x)); return {r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1}; };
const over = (f, back) => ({r: f.r * f.a + back.r * (1 - f.a), g: f.g * f.a + back.g * (1 - f.a), b: f.b * f.a + back.b * (1 - f.a), a: 1});
const lum = c => { const f = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b); };
let page = parse(getComputedStyle(document.body).backgroundColor) || {r: 255, g: 255, b: 255, a: 1};
if (page.a < 1) page = over(page, {r: 255, g: 255, b: 255});
const bg = over(parse(getComputedStyle(b).backgroundColor), page);
const fg = over(parse(getComputedStyle(b).color), bg);
const l1 = lum(fg), l2 = lum(bg);
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
})()"""
# How many visible interactive elements the badge covers.
COVER = """(() => {
const b = document.getElementById('wp-sync-badge');
const r = b.getBoundingClientRect(); const hits = [];
document.querySelectorAll('a[href],button,input,select,textarea,summary,[role="button"],[tabindex]:not([tabindex="-1"])').forEach(o => {
if (o === b || b.contains(o)) return;
const q = o.getBoundingClientRect();
if (!q.width || !q.height || !o.getClientRects().length) return;
const cs = getComputedStyle(o); if (cs.visibility === 'hidden' || cs.display === 'none') return;
if (q.left < r.right && q.right > r.left && q.top < r.bottom && q.bottom > r.top)
hits.push((o.id || o.className || o.tagName).toString().slice(0, 30) + ' ' + (o.textContent || '').trim().slice(0, 20));
});
// Is there ANY spot on this screen where a badge this size covers nothing? Scanned on
// a finer grid than the page code uses, so "the badge missed a free spot" can fail.
const rects = [];
document.querySelectorAll('a[href],button,input,select,textarea,summary,[role="button"],[tabindex]:not([tabindex="-1"])').forEach(o => {
if (o === b || b.contains(o)) return;
const q = o.getBoundingClientRect();
if (!q.width || !q.height || !o.getClientRects().length) return;
const cs = getComputedStyle(o); if (cs.visibility === 'hidden' || cs.display === 'none') return;
rects.push(q);
});
const w = r.width, h = r.height, vw = document.documentElement.clientWidth, vh = window.innerHeight;
let free = false;
for (let y = 0; y + h <= vh && !free; y += 4) {
for (let x = 0; x + w <= vw && !free; x += 4) {
if (!rects.some(q => q.left < x + w && q.right > x && q.top < y + h && q.bottom > y)) free = true;
}
}
return JSON.stringify({hits: hits, free: free, rect: [r.left, r.top, r.right, r.bottom].map(Math.round)});
})()"""
def info(page):
return json.loads(page.eval(BADGE))
def queue(page):
return json.loads(page.eval("localStorage.getItem(%r) || '[]'" % KEY))
def boot(page, base, tok, path="/field.html", user="root", width=1440):
page.viewport(width, 844 if width < 800 else 900, mobile=width < 800)
page.clear_cookies()
page.set_cookie("wp_session", tok[user])
page.goto(base + path)
for _ in range(40):
if page.eval("!!(window.WP_USER && window.ProjectData)"):
break
time.sleep(0.3)
time.sleep(0.6)
page.eval(STUB)
def push(page, wid="wp_b1"):
page.eval("ProjectData.pushWP({id:%r, name:%r}, 'projA'); true" % (wid, wid))
time.sleep(0.7)
def drive(page, state):
"""Put the page into one badge state by using the real outbox."""
if state == "sending":
page.eval("window.__never = true")
push(page)
elif state == "retrying":
page.eval("localStorage.setItem(%r, %s); window.__status = 500; true" % (
KEY, json.dumps(json.dumps([{"kind": "wp", "key": "wp_r", "opId": "wp:wp_r:1", "tries": 3,
"owner": "root", "body": {"id": "wp_r"}}]))))
page.eval("ProjectData.flushSync()")
time.sleep(0.5)
elif state == "held":
page.eval("window.__status = 401")
push(page)
elif state == "unsaved":
page.eval(QUOTA)
page.eval("window.__never = true")
push(page)
elif state == "rejected":
page.eval("window.__status = 409")
push(page)
elif state == "readqueue":
page.eval("window.WP_SESSION_MODE = 'readqueue'; document.dispatchEvent(new CustomEvent('wp-session-mode')); true")
time.sleep(0.4)
elif state == "sent":
push(page)
time.sleep(0.3)
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
tmpdir = tempfile.mkdtemp(prefix="wpsuite-badge-")
db_path = os.path.join(tmpdir, "check.db")
server = None
try:
tok = seed(db_path)
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
if server is None:
print("the test server would not start.")
return 2
print("\nThe sync badge - D26 and BL-061 / T14.3\nTarget: %s" % base)
browser = cdp.Browser(exe)
page = browser.page()
try:
page.ws.call("Emulation.setFocusEmulationEnabled", {"enabled": True})
print("\n1. every state shows, in words that name the project")
expect = {
"sending": "Sending",
"retrying": "Retrying",
"held": "Sign in again",
"unsaved": "not saved on this device",
"rejected": "rejected by the project",
"readqueue": "Working offline",
}
for state, words in expect.items():
boot(page, base, tok)
drive(page, state)
b = info(page)
chk("%-9s shows: %r" % (state, words), b.get("shown") and words in b.get("text", ""), b.get("text", "")[:100])
chk("%-9s names the project" % state, "project" in b.get("text", ""), b.get("text", "")[:100])
chk("%-9s is in a polite live region" % state, b.get("role") == "status")
ratio = page.eval(CONTRAST)
chk("%-9s contrast %.1f:1 is at least 4.5:1" % (state, ratio), ratio >= 4.5, "%.2f" % ratio)
print("\n2. Sign in and Dismiss are real, focusable, 44px controls")
for state in ("held", "readqueue"):
boot(page, base, tok)
drive(page, state)
r = json.loads(page.eval("""(() => {
const a = document.querySelector('#wp-sync-badge a.wp-sb-ctl');
if (!a) return JSON.stringify({none: true});
a.focus(); const q = a.getBoundingClientRect(); const cs = getComputedStyle(a);
return JSON.stringify({tag: a.tagName, href: a.getAttribute('href'), w: q.width, h: q.height,
focused: document.activeElement === a, ring: cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) >= 2,
pe: getComputedStyle(document.getElementById('wp-sync-badge')).pointerEvents});
})()"""))
chk("%-9s has a Sign in link" % state, r.get("tag") == "A", json.dumps(r))
chk("%-9s link goes to login.html?next=" % state,
(r.get("href") or "").startswith("login.html?next=%2F"), r.get("href"))
chk("%-9s link is at least 44px both ways" % state, r.get("w", 0) >= 44 and r.get("h", 0) >= 44,
"%sx%s" % (r.get("w"), r.get("h")))
chk("%-9s link takes focus and shows a ring" % state, r.get("focused") and r.get("ring"), json.dumps(r))
chk("%-9s the badge takes clicks (no pointer-events:none)" % state, r.get("pe") == "auto", r.get("pe"))
print("\n3. Dismiss removes only what the project refused")
boot(page, base, tok)
page.eval("window.__status = 200")
page.eval("localStorage.setItem(%r, %s); true" % (KEY, json.dumps(json.dumps([
{"kind": "wp", "key": "wp_dead", "opId": "wp:wp_dead:1", "tries": 0, "owner": "root", "dead": True,
"lastErr": "The project is archived. Ask an admin to unarchive it.", "body": {"id": "wp_dead"}},
{"kind": "wp", "key": "wp_live", "opId": "wp:wp_live:1", "tries": 0, "owner": "root", "body": {"id": "wp_live"}}]))))
page.eval("window.__never = true; ProjectData.flushSync(); true")
time.sleep(0.5)
b = info(page)
chk("the reason is shown", "archived" in b.get("text", ""), b.get("text", "")[:120])
r = json.loads(page.eval("""(() => {
const d = document.querySelector('#wp-sync-badge button.wp-sb-ctl');
if (!d) return JSON.stringify({none: true});
d.focus(); const q = d.getBoundingClientRect(); const cs = getComputedStyle(d);
return JSON.stringify({tag: d.tagName, type: d.type, w: q.width, h: q.height, focused: document.activeElement === d,
ring: cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) >= 2});
})()"""))
chk("Dismiss is a <button type=button>", r.get("tag") == "BUTTON" and r.get("type") == "button", json.dumps(r))
chk("Dismiss is at least 44px, takes focus, shows a ring",
r.get("w", 0) >= 44 and r.get("h", 0) >= 44 and r.get("focused") and r.get("ring"), json.dumps(r))
page.eval("document.querySelector('#wp-sync-badge button.wp-sb-ctl').click(); true")
time.sleep(0.4)
keys = [o["key"] for o in queue(page)]
chk("the refused change is gone", "wp_dead" not in keys, str(keys))
chk("the waiting change is kept", "wp_live" in keys, str(keys))
print("\n5. 'Everything sent' follows real work, then hides")
boot(page, base, tok)
time.sleep(2.5)
chk("a page with nothing to send shows no badge", not info(page).get("shown"))
drive(page, "sent")
seen = False
for _ in range(10):
if "Everything sent to the project" in info(page).get("text", "") and info(page).get("shown"):
seen = True
break
time.sleep(0.2)
chk("after real work it says everything was sent to the project", seen, info(page).get("text", ""))
time.sleep(2.6)
chk("and then hides", not info(page).get("shown"))
page.eval("ProjectData.flushSync(); true")
time.sleep(0.6)
chk("an idle flush does not flash it again", not info(page).get("shown"))
print("\n6. the console pages never show it")
for path in ("/admin.html", "/users.html"):
boot(page, base, tok, path)
has = page.eval("document.body.hasAttribute('data-wp-no-sync-badge')")
page.eval("window.__status = 401")
push(page, "wp_console")
b = info(page)
chk("%s opts out" % path, has is True)
chk("%s shows no badge even with a held queue" % path, not b.get("shown"), b.get("text", "")[:80])
print("\n7. the badge covers no control, at 390 and 1440")
pages = [("/field.html", "field"),
("/index.html", "launcher"),
("/work-package-suite.html?project=projA", "wizard"),
("/wp-creation-index.html?project=projA&wp=wpA1", "creator")]
for width in (390, 1440):
for path, label in pages:
for state in ("sending", "held", "rejected", "unsaved", "readqueue"):
boot(page, base, tok, path, width=width)
drive(page, state)
b = info(page)
if not b.get("shown"):
chk("%4d %-8s %-9s badge shows" % (width, label, state), False, "hidden")
continue
cov = json.loads(page.eval(COVER))
r = cov["rect"]
inside = r[0] >= 0 and r[2] <= width + 1
# The rule: the badge covers no control whenever the screen has
# room for it. A screen with no free gap of that size (BL-072)
# cannot satisfy it, and is reported as such, not hidden.
ok = (not cov["hits"]) or (not cov["free"])
note = "" if not cov["hits"] else " (no free gap on this screen, BL-072)"
chk("%4d %-8s %-9s covers no control, fits the screen%s" % (width, label, state, note),
ok and inside, "%s rect=%s free=%s" % (cov["hits"][:2], r, cov["free"]))
finally:
page.close()
browser.close()
finally:
if server is not None:
server.kill()
try:
server.wait(timeout=10)
except subprocess.TimeoutExpired:
pass
try:
from server.db import engine
engine.dispose()
except Exception:
pass
print("\n%d passed, %d failed" % (len(_PASS), len(_FAIL)))
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())