Compare commits

...
Author SHA1 Message Date
jared e4591f669b Merge pull request 'fix(status): status changes apply at once instead of waiting out the rate limit' (#469) from fix/status-save-speed into lotus
CI / Secret scan (gitleaks) (push) Successful in 19s
CI / Build & Quality Checks (push) Successful in 3m37s
CI / Docker image build & smoke test (push) Skipped
CI / Trigger Desktop Build (push) Successful in 1m7s
CI / Playwright smoke (e2e) (push) Successful in 29m10s
2026-10-25 21:20:59 -04:00
jared 185970bc5a Merge pull request 'chore(types): typed secret storage key cache; drop the cryptoCallbacks cast (#210)' (#468) from chore/typing-hygiene into lotus
CI / Secret scan (gitleaks) (push) Successful in 33s
CI / Build & Quality Checks (push) Successful in 4m1s
CI / Docker image build & smoke test (push) Skipped
CI / Trigger Desktop Build (push) Canceled after 0s
CI / Playwright smoke (e2e) (push) Canceled after 0s
2026-10-25 20:33:50 -04:00
Lotus CIandClaude Opus 5.5 8cdf192b56 fix(status): status changes apply at once instead of waiting out the rate limit
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Build & Quality Checks (pull_request) Successful in 3m55s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Secret scan (gitleaks) (pull_request) Successful in 27s
CI / Playwright smoke (e2e) (pull_request) Successful in 33m26s
Synapse allows one presence write per 10 s per user (shared by every
device). The heartbeat wrote presence at startup and on every tab
switch, so a status save right after usually got a 429 and waited 7-25 s,
with the whole status section (quick statuses, input, Clear) locked and
the Save spinner going.

- One shared presence queue (heartbeat + status save), newest write wins:
  changes made while a write waits out a 429 replace it, so only the latest
  is sent, as soon as the server allows.
- The status UI no longer waits on the server: the status applies locally,
  Save switches off (it compared with the server echo, so it stayed lit
  and invited a second, guaranteed-429 write), the controls stay usable,
  and a short note shows until the write lands.
- The heartbeat skips writes the server already reflects (e.g. "online"
  at startup), so it stops spending the budget for nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017PCb59uY3UKqDqt7B6hzd5
2026-10-25 20:14:12 -04:00
jared 222927b558 Merge pull request 'feat(settings): search across all settings (#453 phase 3)' (#467) from feat/settings-search into lotus
CI / Build & Quality Checks (push) Successful in 3m27s
CI / Docker image build & smoke test (push) Skipped
CI / Secret scan (gitleaks) (push) Successful in 11s
CI / Trigger Desktop Build (push) Successful in 18s
CI / Playwright smoke (e2e) (push) Successful in 21m37s
2026-10-25 19:38:10 -04:00
Lotus CIandClaude Opus 5.5 b944456ab5 chore(types): typed secret storage key cache; drop the cryptoCallbacks cast (#210)
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Build & Quality Checks (pull_request) Successful in 3m32s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Secret scan (gitleaks) (pull_request) Successful in 16s
CI / Playwright smoke (e2e) (pull_request) Successful in 24m32s
secretStorageKeys was untyped JS, passed to createClient behind `as any`,
which hid that getSecretStorageKey returned undefined where the SDK type
says null. Now TypeScript against the SDK's CryptoCallbacks, returns null,
and storePrivateKey keeps its own copy of the key. Unit test added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017PCb59uY3UKqDqt7B6hzd5
2026-10-25 19:38:10 -04:00
jared 3b3bf8abac Merge pull request 'feat(settings): new settings pages, collapsed pickers, privacy choice, grouped calls (#453 phase 2)' (#466) from feat/settings-pages into lotus
CI / Build & Quality Checks (push) Successful in 3m18s
CI / Docker image build & smoke test (push) Skipped
CI / Secret scan (gitleaks) (push) Successful in 17s
CI / Trigger Desktop Build (push) Successful in 8s
CI / Playwright smoke (e2e) (push) Successful in 19m55s
2026-10-25 12:45:40 -04:00
jared 826fc46229 Merge pull request 'chore(deps): sanitize-html 2.18.1, i18next-http-backend 4.0.3 [security]' (#465) from chore/security-deps into lotus
CI / Build & Quality Checks (push) Successful in 3m15s
CI / Docker image build & smoke test (push) Skipped
CI / Secret scan (gitleaks) (push) Successful in 10s
CI / Trigger Desktop Build (push) Canceled after 6s
CI / Playwright smoke (e2e) (push) Canceled after 0s
2026-10-25 12:18:50 -04:00
Lotus CIandClaude Opus 5.5 a7495fc509 chore(deps): sanitize-html 2.18.1, i18next-http-backend 4.0.3 [security]
CI / Build & Quality Checks (push) Skipped
CI / Secret scan (gitleaks) (push) Skipped
CI / Playwright smoke (e2e) (push) Skipped
CI / Build & Quality Checks (pull_request) Successful in 4m36s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Secret scan (gitleaks) (pull_request) Successful in 16s
CI / Playwright smoke (e2e) (pull_request) Successful in 18m10s
Matches upstream Cinny 4.12.8. npm audit flagged our sanitize-html
2.17.7 with three advisories, two of them XSS bypasses (SMIL animation
namespace-prefix javascript: URIs; meta refresh javascript:/data: URLs;
noscript content rendering after an implied close). sanitize-html cleans
formatted message HTML. After the bump: 0 production advisories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017PCb59uY3UKqDqt7B6hzd5
2026-10-25 11:55:28 -04:00
11 changed files with 306 additions and 85 deletions

No files matched your search

+58
View File
@@ -415,6 +415,64 @@ test.describe('local homeserver regression', () => {
.toBe(status); .toBe(status);
}); });
test('status: applies at once, quick changes fold into one write (slow-save report)', async ({
page,
}) => {
let lastOk = 0;
const sent: string[] = [];
await page.route(/\/presence\/[^/]+\/status/, (route) => {
if (route.request().method() !== 'PUT') return route.continue();
const now = Date.now();
if (now - lastOk < 10_000) {
return route.fulfill({
status: 429,
contentType: 'application/json',
body: JSON.stringify({
errcode: 'M_LIMIT_EXCEEDED',
retry_after_ms: 10_000 - (now - lastOk),
}),
});
}
lastOk = now;
sent.push(JSON.parse(route.request().postData() ?? '{}').status_msg ?? '');
return route.continue();
});
await loginUI(page, alice);
await page.getByRole('button', { name: 'User Settings' }).click();
await page.getByText('Account', { exact: true }).first().click();
const input = page.getByLabel('Status message');
const save = input.locator('xpath=ancestor::form[1]').getByRole('button', { name: 'Save' });
// Use up the 10 s budget, then pick three quick statuses in a row.
await input.fill(uniq('first '));
await save.click();
await expect(save).toBeDisabled(); // applied: nothing left to save, no spinner wait
const quick = page.getByRole('group', { name: 'Quick statuses' });
await quick.getByRole('button', { name: /Lunch/ }).click();
await quick.getByRole('button', { name: /Watching/ }).click();
await quick.getByRole('button', { name: /AFK/ }).click();
await expect(input).toHaveValue('😴 AFK');
await expect(save).toBeDisabled();
await expect(page.getByText(/Status set\. Sharing it with others/)).toBeVisible();
await expect
.poll(
async () =>
(
await api<{ status_msg?: string }>(
'GET',
`/_matrix/client/v3/presence/${enc(alice.userId)}/status`,
alice.token,
)
).status_msg,
{ timeout: 30_000 },
)
.toBe('😴 AFK');
// The middle choices were superseded while waiting, never sent.
expect(sent.filter((m) => /Lunch|Watching/.test(m))).toEqual([]);
await expect(page.getByText(/Status set\. Sharing it with others/)).toHaveCount(0);
});
test('touch: long-press opens the message action sheet (#166)', async ({ browser }) => { test('touch: long-press opens the message action sheet (#166)', async ({ browser }) => {
const ctx = await browser.newContext({ ...devices['Pixel 7'] }); const ctx = await browser.newContext({ ...devices['Pixel 7'] });
const page = await ctx.newPage(); const page = await ctx.newPage();
+26 -19
View File
@@ -45,7 +45,7 @@
"html-react-parser": "6.1.2", "html-react-parser": "6.1.2",
"i18next": "26.2.0", "i18next": "26.2.0",
"i18next-browser-languagedetector": "8.2.1", "i18next-browser-languagedetector": "8.2.1",
"i18next-http-backend": "4.0.2", "i18next-http-backend": "4.0.3",
"immer": "11.1.8", "immer": "11.1.8",
"is-hotkey": "0.2.0", "is-hotkey": "0.2.0",
"jotai": "2.20.0", "jotai": "2.20.0",
@@ -70,7 +70,7 @@
"react-i18next": "17.0.8", "react-i18next": "17.0.8",
"react-range": "1.10.0", "react-range": "1.10.0",
"react-router-dom": "7.18.3", "react-router-dom": "7.18.3",
"sanitize-html": "2.17.7", "sanitize-html": "2.18.1",
"slate": "0.124.1", "slate": "0.124.1",
"slate-dom": "0.124.1", "slate-dom": "0.124.1",
"slate-history": "0.113.1", "slate-history": "0.113.1",
@@ -6057,6 +6057,7 @@
"version": "4.3.1", "version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
"dev": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@@ -8168,9 +8169,9 @@
} }
}, },
"node_modules/i18next-http-backend": { "node_modules/i18next-http-backend": {
"version": "4.0.2", "version": "4.0.3",
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.0.2.tgz", "resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.0.3.tgz",
"integrity": "sha512-oay62dIB2kL7+WHzoUXBjWfL3+mwijD3pQkQkIEaRLhy6kjXxUhrRenV0gInwlCASAaJaDy94+XvYizK+cAGdA==", "integrity": "sha512-B5GJysCsJwqiDQRpUcikWsut82Vmekix58WIyiCpYtxaZ/wY8kwJCicMRvVcMoIa1x84siiRl5vBt6iCBVO6zg==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18" "node": ">=18"
@@ -8704,9 +8705,10 @@
} }
}, },
"node_modules/is-plain-object": { "node_modules/is-plain-object": {
"version": "5.0.0", "version": "5.1.0",
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz",
"integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", "integrity": "sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==",
"license": "MIT",
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@@ -9207,14 +9209,20 @@
} }
}, },
"node_modules/launder": { "node_modules/launder": {
"version": "1.7.1", "version": "1.7.2",
"resolved": "https://registry.npmjs.org/launder/-/launder-1.7.1.tgz", "resolved": "https://registry.npmjs.org/launder/-/launder-1.7.2.tgz",
"integrity": "sha512-mU6WRz5EusL9ZZuiZ5SO4Y6C0P9PAUR9iwdb6bzj4KDihm28DiHFw+/yk9DBH4f+Pv1wuzQ4e2jV3oQ7mkIqvw==", "integrity": "sha512-DLg3HPnHUfBi5/MxMLmJD12dmlMpFEC2HgMW6vkZ/9JR0RU00kXoRGvDxAvFmdO0o610OA77i4FgNTLucmhDVg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"dayjs": "^1.11.7" "dayjs": "^1.11.23"
} }
}, },
"node_modules/launder/node_modules/dayjs": {
"version": "1.11.23",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
"license": "MIT"
},
"node_modules/leven": { "node_modules/leven": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@@ -11706,18 +11714,17 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/sanitize-html": { "node_modules/sanitize-html": {
"version": "2.17.7", "version": "2.18.1",
"resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.17.7.tgz", "resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.18.1.tgz",
"integrity": "sha512-PGtEkc9cbnedU3s9TmzDbpsZ8w086g/0Q8k8/oIO1NLNU3i5k9yn835CrjJSajp1KMmkisbO1qPXxNKO3welAg==", "integrity": "sha512-2X5lC8fYla8YaT8g73Nj+HcLWXan5dLyCWLgVvaOmfw7JI78IRsyNtIDytTHdn7hBQbIkCah7Zbmd5jabzeDig==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"deepmerge": "^4.2.2",
"escape-string-regexp": "^4.0.0", "escape-string-regexp": "^4.0.0",
"htmlparser2": "^12.0.0", "htmlparser2": "^12.0.0",
"is-plain-object": "^5.0.0", "is-plain-object": "^5.1.0",
"launder": "^1.7.1", "launder": "^1.7.2",
"parse-srcset": "^1.0.2", "parse-srcset": "^1.0.2",
"postcss": "^8.3.11" "postcss": "^8.5.27"
}, },
"engines": { "engines": {
"node": ">=22.12.0" "node": ">=22.12.0"
+2 -2
View File
@@ -72,7 +72,7 @@
"html-react-parser": "6.1.2", "html-react-parser": "6.1.2",
"i18next": "26.2.0", "i18next": "26.2.0",
"i18next-browser-languagedetector": "8.2.1", "i18next-browser-languagedetector": "8.2.1",
"i18next-http-backend": "4.0.2", "i18next-http-backend": "4.0.3",
"immer": "11.1.8", "immer": "11.1.8",
"is-hotkey": "0.2.0", "is-hotkey": "0.2.0",
"jotai": "2.20.0", "jotai": "2.20.0",
@@ -97,7 +97,7 @@
"react-i18next": "17.0.8", "react-i18next": "17.0.8",
"react-range": "1.10.0", "react-range": "1.10.0",
"react-router-dom": "7.18.3", "react-router-dom": "7.18.3",
"sanitize-html": "2.17.7", "sanitize-html": "2.18.1",
"slate": "0.124.1", "slate": "0.124.1",
"slate-dom": "0.124.1", "slate-dom": "0.124.1",
"slate-history": "0.113.1", "slate-history": "0.113.1",
+24 -22
View File
@@ -38,11 +38,7 @@ import { SettingTile } from '../../../components/setting-tile';
import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getAccountData, setAccountData } from '../../../utils/accountData'; import { getAccountData, setAccountData } from '../../../utils/accountData';
import { presenceStateFromSetting } from '../../../hooks/usePresenceUpdater'; import { presenceStateFromSetting } from '../../../hooks/usePresenceUpdater';
import { import { describePresenceError, queuePresenceWrite } from '../../../utils/presenceWrite';
describePresenceError,
setPresenceWithRetry,
writePresence,
} from '../../../utils/presenceWrite';
import { useSetting } from '../../../state/hooks/settings'; import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings'; import { settingsAtom } from '../../../state/settings';
import { UserProfile, useUserProfile } from '../../../hooks/useUserProfile'; import { UserProfile, useUserProfile } from '../../../hooks/useUserProfile';
@@ -419,6 +415,10 @@ function ProfileStatus() {
// until our own echo lands or a short window elapses (bounded so a genuinely // until our own echo lands or a short window elapses (bounded so a genuinely
// dropped echo can't block real cross-device updates forever). // dropped echo can't block real cross-device updates forever).
const pendingAppliedRef = useRef<{ value: string; ts: number } | null>(null); const pendingAppliedRef = useRef<{ value: string; ts: number } | null>(null);
// The status as this device last applied or synced it. "Save" compares with
// this, not with the server echo, so it switches off the moment a status is
// applied instead of staying lit until the (rate-limited) write lands.
const [savedMsg, setSavedMsg] = useState<string>(initialStatus);
const [clearAfter, setClearAfter] = useState('0'); const [clearAfter, setClearAfter] = useState('0');
const [emojiAnchor, setEmojiAnchor] = useState<RectCords>(); const [emojiAnchor, setEmojiAnchor] = useState<RectCords>();
const { presets, addPreset, removePreset } = useStatusPresets(); const { presets, addPreset, removePreset } = useStatusPresets();
@@ -442,7 +442,7 @@ function ProfileStatus() {
if (pending) { if (pending) {
if (remoteStatus === pending.value) { if (remoteStatus === pending.value) {
pendingAppliedRef.current = null; // our own echo landed — accept it pendingAppliedRef.current = null; // our own echo landed — accept it
} else if (Date.now() - pending.ts < 15_000) { } else if (Date.now() - pending.ts < 30_000) {
return; // stale echo of the previous status; ignore within the window return; // stale echo of the previous status; ignore within the window
} else { } else {
pendingAppliedRef.current = null; // window elapsed — accept external changes pendingAppliedRef.current = null; // window elapsed — accept external changes
@@ -451,6 +451,7 @@ function ProfileStatus() {
// [Gitea #283] "dnd" is the Do Not Disturb sentinel, not something the user // [Gitea #283] "dnd" is the Do Not Disturb sentinel, not something the user
// typed: don't show it in the status field or keep it as their status. // typed: don't show it in the status field or keep it as their status.
if (remoteStatus === DND_STATUS_SENTINEL) return; if (remoteStatus === DND_STATUS_SENTINEL) return;
setSavedMsg(remoteStatus);
if (remoteStatus) { if (remoteStatus) {
setStatusMsg(remoteStatus); setStatusMsg(remoteStatus);
localStorage.setItem(STATUS_MSG_KEY(userId), remoteStatus); localStorage.setItem(STATUS_MSG_KEY(userId), remoteStatus);
@@ -467,9 +468,10 @@ function ProfileStatus() {
useCallback( useCallback(
(msg: string) => (msg: string) =>
// Synapse allows ONE presence write per 10 s per user (shared by all // Synapse allows ONE presence write per 10 s per user (shared by all
// devices) and our heartbeat spends that budget too — wait out a 429 // devices) and our heartbeat spends that budget too. The shared queue
// instead of failing the user's save. // waits out a 429 and folds quick successive changes into one write;
setPresenceWithRetry(mx, { // the UI doesn't wait on it (the status is applied locally at once).
queuePresenceWrite(mx, {
// Derive presence from the user's chosen setting so writing a status // Derive presence from the user's chosen setting so writing a status
// never overrides Invisible/DND/Idle (e.g. outing an Invisible user). // never overrides Invisible/DND/Idle (e.g. outing an Invisible user).
presence: presenceStateFromSetting(presenceStatus, hidePresence), presence: presenceStateFromSetting(presenceStatus, hidePresence),
@@ -498,6 +500,7 @@ function ProfileStatus() {
(rawMsg: string, clearAfterValue: string) => { (rawMsg: string, clearAfterValue: string) => {
statusDirtyRef.current = false; statusDirtyRef.current = false;
const msg = rawMsg.trim(); const msg = rawMsg.trim();
setSavedMsg(msg);
// Guard against a stale presence echo reverting this value (see the sync effect). // Guard against a stale presence echo reverting this value (see the sync effect).
pendingAppliedRef.current = { value: msg, ts: Date.now() }; pendingAppliedRef.current = { value: msg, ts: Date.now() };
noteLocalStatusWrite(); noteLocalStatusWrite();
@@ -527,19 +530,17 @@ function ProfileStatus() {
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => { const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
evt.preventDefault(); evt.preventDefault();
if (saving) return;
applyStatus(statusMsg, clearAfter); applyStatus(statusMsg, clearAfter);
}; };
// Preset click = one-click apply: reflect it in the inputs and save immediately. // Preset click = one-click apply: reflect it in the inputs and save immediately.
const applyPreset = useCallback( const applyPreset = useCallback(
(preset: StatusPreset) => { (preset: StatusPreset) => {
if (saving) return;
setStatusMsg(preset.label); setStatusMsg(preset.label);
setClearAfter(preset.clearAfter); setClearAfter(preset.clearAfter);
applyStatus(preset.label, preset.clearAfter); applyStatus(preset.label, preset.clearAfter);
}, },
[saving, applyStatus], [applyStatus],
); );
const handleSaveCurrent = useCallback(() => { const handleSaveCurrent = useCallback(() => {
@@ -560,17 +561,18 @@ function ProfileStatus() {
pendingAppliedRef.current = { value: '', ts: Date.now() }; pendingAppliedRef.current = { value: '', ts: Date.now() };
noteLocalStatusWrite(); noteLocalStatusWrite();
setStatusMsg(''); setStatusMsg('');
setSavedMsg('');
localStorage.removeItem(STATUS_MSG_KEY(userId)); localStorage.removeItem(STATUS_MSG_KEY(userId));
localStorage.removeItem(STATUS_EXPIRY_KEY(userId)); localStorage.removeItem(STATUS_EXPIRY_KEY(userId));
writeStatusExpiry(mx, '').catch(() => undefined); writeStatusExpiry(mx, '').catch(() => undefined);
// Preserve the user's chosen presence when clearing the status message. // Preserve the user's chosen presence when clearing the status message.
writePresence(mx, { queuePresenceWrite(mx, {
presence: presenceStateFromSetting(presenceStatus, hidePresence), presence: presenceStateFromSetting(presenceStatus, hidePresence),
status_msg: '', status_msg: '',
}).catch(() => undefined); }).catch(() => undefined);
}; };
const hasChanges = statusMsg !== (presence?.status ?? ''); const hasChanges = statusMsg.trim() !== savedMsg;
return ( return (
<SettingTile <SettingTile
@@ -599,7 +601,6 @@ function ProfileStatus() {
variant="Secondary" variant="Secondary"
fill="Soft" fill="Soft"
radii="Pill" radii="Pill"
disabled={saving}
onClick={() => applyPreset(preset)} onClick={() => applyPreset(preset)}
> >
<Text as="span" size="B300"> <Text as="span" size="B300">
@@ -625,7 +626,6 @@ function ProfileStatus() {
variant="Secondary" variant="Secondary"
fill="Soft" fill="Soft"
radii="Pill" radii="Pill"
disabled={saving}
onClick={() => applyPreset(preset)} onClick={() => applyPreset(preset)}
> >
<Text as="span" size="B300"> <Text as="span" size="B300">
@@ -651,7 +651,7 @@ function ProfileStatus() {
fill="Soft" fill="Soft"
radii="Pill" radii="Pill"
outlined outlined
disabled={saving || !statusMsg.trim()} disabled={!statusMsg.trim()}
onClick={handleSaveCurrent} onClick={handleSaveCurrent}
before={<Icon size="100" src={Icons.Plus} />} before={<Icon size="100" src={Icons.Plus} />}
> >
@@ -662,7 +662,7 @@ function ProfileStatus() {
</Box> </Box>
</Box> </Box>
<Box as="form" onSubmit={handleSubmit} gap="200" alignItems="Center" aria-disabled={saving}> <Box as="form" onSubmit={handleSubmit} gap="200" alignItems="Center">
<Box grow="Yes" direction="Column" gap="100"> <Box grow="Yes" direction="Column" gap="100">
<Input <Input
name="statusMsgInput" name="statusMsgInput"
@@ -672,7 +672,6 @@ function ProfileStatus() {
placeholder="What's on your mind?" placeholder="What's on your mind?"
variant="Secondary" variant="Secondary"
radii="300" radii="300"
readOnly={saving}
maxLength={64} maxLength={64}
/> />
<Text <Text
@@ -733,13 +732,17 @@ function ProfileStatus() {
fill={hasChanges ? 'Solid' : 'Soft'} fill={hasChanges ? 'Solid' : 'Soft'}
outlined outlined
radii="300" radii="300"
disabled={!hasChanges || saving} disabled={!hasChanges}
type="submit" type="submit"
> >
{saving && <Spinner variant="Success" fill="Solid" size="300" />}
<Text size="B400">Save</Text> <Text size="B400">Save</Text>
</Button> </Button>
</Box> </Box>
{saving && (
<Text size="T200" priority="300" role="status">
Status set. Sharing it with others, this can take a few seconds.
</Text>
)}
{saveState.status === AsyncStatus.Error && ( {saveState.status === AsyncStatus.Error && (
<Text size="T200" style={{ color: color.Critical.Main }}> <Text size="T200" style={{ color: color.Critical.Main }}>
{describePresenceError(saveState.error)} {describePresenceError(saveState.error)}
@@ -764,7 +767,6 @@ function ProfileStatus() {
radii="300" radii="300"
type="button" type="button"
onClick={handleClear} onClick={handleClear}
disabled={saving}
> >
<Text size="B300">Clear Status</Text> <Text size="B300">Clear Status</Text>
</Button> </Button>
+19 -2
View File
@@ -1,6 +1,6 @@
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { SetPresence } from 'matrix-js-sdk'; import { SetPresence } from 'matrix-js-sdk';
import { PresenceDeduper, PresenceWrite, writePresence } from '../utils/presenceWrite'; import { PresenceDeduper, PresenceWrite, queuePresenceWrite } from '../utils/presenceWrite';
import { useMatrixClient } from './useMatrixClient'; import { useMatrixClient } from './useMatrixClient';
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync'; import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
import { useSetting } from '../state/hooks/settings'; import { useSetting } from '../state/hooks/settings';
@@ -70,9 +70,25 @@ export function usePresenceUpdater() {
// by all devices) and /sync already keeps us online — only send when the // by all devices) and /sync already keeps us online — only send when the
// state or status actually changes, so a manual status save isn't 429'd // state or status actually changes, so a manual status save isn't 429'd
// by a heartbeat that changed nothing. // by a heartbeat that changed nothing.
// What the server reported in the last resolveStatus() (consumed by send).
let serverNow: { presence: string; status_msg?: string } | undefined;
const send = (write: PresenceWrite, label: string) => { const send = (write: PresenceWrite, label: string) => {
const server = serverNow;
serverNow = undefined;
if (!deduper.shouldSend(write)) return Promise.resolve(); if (!deduper.shouldSend(write)) return Promise.resolve();
return writePresence(mx, write) // The server already shows exactly this (e.g. /sync keeps us online and
// the status is unchanged): writing it again would only spend the
// 10-second budget a status save may need next.
if (
server &&
server.presence === write.presence &&
(server.status_msg ?? '') === (write.status_msg ?? '')
) {
deduper.sent(write);
return Promise.resolve();
}
// Shared queue with the status save: waits out a 429, newest write wins.
return queuePresenceWrite(mx, write)
.then(() => deduper.sent(write)) .then(() => deduper.sent(write))
.catch((err) => warnPresenceFailure(label, err)); .catch((err) => warnPresenceFailure(label, err));
}; };
@@ -84,6 +100,7 @@ export function usePresenceUpdater() {
const local = readStatus(); const local = readStatus();
if (!userId) return local; if (!userId) return local;
const server = await mx.getPresence(userId).catch(() => undefined); const server = await mx.getPresence(userId).catch(() => undefined);
serverNow = server;
const status = pickHeartbeatStatus({ const status = pickHeartbeatStatus({
local, local,
server, server,
+48 -2
View File
@@ -1,7 +1,13 @@
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { MatrixError } from 'matrix-js-sdk'; import { IPresenceOpts, MatrixError } from 'matrix-js-sdk';
import { PresenceDeduper, describePresenceError, setPresenceWithRetry } from './presenceWrite'; import {
PresenceDeduper,
describePresenceError,
isPresenceWritePending,
queuePresenceWrite,
setPresenceWithRetry,
} from './presenceWrite';
const limited = (retryMs = 3000) => const limited = (retryMs = 3000) =>
new MatrixError( new MatrixError(
@@ -79,3 +85,43 @@ test('error wording', () => {
); );
assert.match(describePresenceError(new TypeError('Failed to fetch')), /couldn't reach/); assert.match(describePresenceError(new TypeError('Failed to fetch')), /couldn't reach/);
}); });
test('[status save] queuePresenceWrite: newest wins, waits out 429 once, all callers settle', async () => {
const sent: string[] = [];
let calls = 0;
const sleeps: number[] = [];
const mx = {
setPresence: async (w: IPresenceOpts) => {
calls += 1;
if (calls === 1) {
sent.push(`429:${w.status_msg}`);
throw new MatrixError({ errcode: 'M_LIMIT_EXCEEDED', retry_after_ms: 7000 }, 429);
}
sent.push(`ok:${w.status_msg}`);
},
};
const sleepFn = async (ms: number) => {
sleeps.push(ms);
};
// 'a' goes out at once; 'b' and 'c' arrive while it waits out the limit.
const first = queuePresenceWrite(mx, { presence: 'online', status_msg: 'a' }, { sleepFn });
const second = queuePresenceWrite(mx, { presence: 'online', status_msg: 'b' }, { sleepFn });
const third = queuePresenceWrite(mx, { presence: 'online', status_msg: 'c' }, { sleepFn });
assert.equal(isPresenceWritePending(mx), true);
await Promise.all([first, second, third]);
// 'a' was 429'd; after the wait only the newest ('c') goes out — 'a' isn't
// retried and 'b' is never sent.
assert.deepEqual(sent, ['429:a', 'ok:c']);
assert.deepEqual(sleeps, [7000]);
assert.equal(isPresenceWritePending(mx), false);
});
test('[status save] queuePresenceWrite: a failure rejects the callers of that write', async () => {
const mx = {
setPresence: async () => {
throw new MatrixError({ errcode: 'M_FORBIDDEN' }, 403);
},
};
await assert.rejects(queuePresenceWrite(mx, { presence: 'online', status_msg: 'x' }));
assert.equal(isPresenceWritePending(mx), false);
});
+75
View File
@@ -94,3 +94,78 @@ export const describePresenceError = (e: unknown): string => {
} }
return "Failed to save status — couldn't reach the server. Try again."; return "Failed to save status — couldn't reach the server. Try again.";
}; };
type PresenceQueue = {
pending?: PresenceWrite;
waiters: { resolve: () => void; reject: (e: unknown) => void }[];
running: boolean;
};
const queues = new WeakMap<object, PresenceQueue>();
/**
* One presence writer per client, newest write wins. The status save and the
* heartbeat share Synapse's one-write-per-10-s budget, so instead of each
* waiting out 429s on its own (and racing), writes queue here: anything still
* waiting is replaced by the newer write, which goes out as soon as the server
* allows. Each caller's promise settles with the outcome of the write that
* finally carried (or superseded) theirs.
*/
export function queuePresenceWrite(
mx: Pick<MatrixClient, 'setPresence'>,
write: PresenceWrite,
opts: { maxWaitMs?: number; sleepFn?: (ms: number) => Promise<void> } = {},
): Promise<void> {
let q = queues.get(mx);
if (!q) {
q = { waiters: [], running: false };
queues.set(mx, q);
}
const queue = q;
queue.pending = write;
const settled = new Promise<void>((resolve, reject) => {
queue.waiters.push({ resolve, reject });
});
if (!queue.running) {
queue.running = true;
const maxWaitMs = opts.maxWaitMs ?? 25_000;
const sleepFn = opts.sleepFn ?? sleep;
(async () => {
let waited = 0;
while (queue.pending) {
const next = queue.pending;
queue.pending = undefined;
const waiters = queue.waiters.splice(0);
try {
// eslint-disable-next-line no-await-in-loop
await writePresence(mx, next);
waited = 0;
if (queue.pending) queue.waiters.unshift(...waiters);
else waiters.forEach((w) => w.resolve());
} catch (e) {
const wait =
e instanceof MatrixError && e.httpStatus === 429
? Math.min(e.getRetryAfterMs() ?? 10_500, 15_000)
: undefined;
if (wait !== undefined && waited + wait <= maxWaitMs) {
waited += wait;
// eslint-disable-next-line no-await-in-loop
await sleepFn(wait);
// After the wait, send whatever is newest: a change made meanwhile
// replaces this one rather than queueing behind it.
queue.pending ??= next;
queue.waiters.unshift(...waiters);
} else if (queue.pending) {
queue.waiters.unshift(...waiters);
} else {
waiters.forEach((w) => w.reject(e));
}
}
}
queue.running = false;
})();
}
return settled;
}
/** Whether a presence write is queued or in flight for this client. */
export const isPresenceWritePending = (mx: object): boolean => queues.get(mx)?.running ?? false;
+1 -1
View File
@@ -87,7 +87,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
// the user (KeyUploadBanner) instead of retrying silently forever. // the user (KeyUploadBanner) instead of retrying silently forever.
fetchFn: watchKeyUploads((input, init) => globalThis.fetch(input, init)), fetchFn: watchKeyUploads((input, init) => globalThis.fetch(input, init)),
timelineSupport: true, timelineSupport: true,
cryptoCallbacks: cryptoCallbacks as any, cryptoCallbacks,
// SAS (emoji) + QR-code verification (show/scan/reciprocate). // SAS (emoji) + QR-code verification (show/scan/reciprocate).
verificationMethods: ['m.sas.v1', 'm.qr_code.show.v1', 'm.qr_code.scan.v1', 'm.reciprocate.v1'], verificationMethods: ['m.sas.v1', 'm.qr_code.show.v1', 'm.qr_code.scan.v1', 'm.reciprocate.v1'],
oauthClientId: oidcIdentity?.oidc.clientId, oauthClientId: oidcIdentity?.oidc.clientId,
-37
View File
@@ -1,37 +0,0 @@
const secretStorageKeys = new Map();
export function storePrivateKey(keyId, privateKey) {
if (privateKey instanceof Uint8Array === false) {
throw new Error('Unable to store, privateKey is invalid.');
}
secretStorageKeys.set(keyId, privateKey);
}
function hasPrivateKey(keyId) {
return secretStorageKeys.get(keyId) instanceof Uint8Array;
}
function getPrivateKey(keyId) {
return secretStorageKeys.get(keyId);
}
export function clearSecretStorageKeys() {
secretStorageKeys.clear();
}
async function getSecretStorageKey({ keys }) {
const keyIds = Object.keys(keys);
const keyId = keyIds.find(hasPrivateKey);
if (!keyId) return undefined;
const privateKey = getPrivateKey(keyId);
return [keyId, privateKey];
}
function cacheSecretStorageKey(keyId, keyInfo, privateKey) {
secretStorageKeys.set(keyId, privateKey);
}
export const cryptoCallbacks = {
getSecretStorageKey,
cacheSecretStorageKey,
};
+26
View File
@@ -0,0 +1,26 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { clearSecretStorageKeys, cryptoCallbacks, storePrivateKey } from './secretStorageKeys';
const ask = (...ids: string[]) =>
cryptoCallbacks.getSecretStorageKey!(
{ keys: Object.fromEntries(ids.map((id) => [id, {} as never])) },
'm.cross_signing.master',
);
test('[#210] secret storage key cache: null when unknown, key when stored, copies input', async () => {
clearSecretStorageKeys();
assert.equal(await ask('k1'), null);
const key = new Uint8Array([1, 2, 3]);
storePrivateKey('k1', key);
key[0] = 9; // the cache keeps its own copy
assert.deepEqual(await ask('k0', 'k1'), ['k1', new Uint8Array([1, 2, 3])]);
cryptoCallbacks.cacheSecretStorageKey!('k2', {} as never, new Uint8Array([7]));
assert.deepEqual(await ask('k2'), ['k2', new Uint8Array([7])]);
clearSecretStorageKeys();
assert.equal(await ask('k1', 'k2'), null);
assert.throws(() => storePrivateKey('k3', 'nope' as never), /invalid/);
});
+27
View File
@@ -0,0 +1,27 @@
import type { CryptoCallbacks } from 'matrix-js-sdk/lib/crypto-api';
const secretStorageKeys = new Map<string, Uint8Array<ArrayBuffer>>();
export function storePrivateKey(keyId: string, privateKey: Uint8Array) {
if (privateKey instanceof Uint8Array === false) {
throw new Error('Unable to store, privateKey is invalid.');
}
// Our own copy, on a plain ArrayBuffer (what the SDK's callback type wants).
secretStorageKeys.set(keyId, new Uint8Array(privateKey));
}
export function clearSecretStorageKeys() {
secretStorageKeys.clear();
}
export const cryptoCallbacks: CryptoCallbacks = {
async getSecretStorageKey({ keys }) {
const keyId = Object.keys(keys).find((id) => secretStorageKeys.get(id) instanceof Uint8Array);
const privateKey = keyId ? secretStorageKeys.get(keyId) : undefined;
// The SDK expects null (not undefined) when no key is cached.
return keyId && privateKey ? [keyId, privateKey] : null;
},
cacheSecretStorageKey(keyId, keyInfo, privateKey) {
secretStorageKeys.set(keyId, privateKey);
},
};