From 9db91378c52f981b45586f73c1504a8c320e1d2c Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 17:52:10 +0000 Subject: [PATCH 001/177] Phone glyphs: icons inside IconButtons and the nav chevron draw larger on phones, box unchanged folds draws a glyph at 16-24 px; on a phone the 16/18/20 px ones read small in their buttons. One global rule per folds Icon size scales the glyph (22/24/24/26/28 px) at paint time inside an IconButton, so no button, PhoneHit area or row changes size and desktop is untouched. phoneGlyph.test.ts pins the folds class names, the px range and that the rule is a phone-only scale. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/room-nav/styles.css.ts | 8 ++++ src/app/phoneGlyph.test.ts | 53 +++++++++++++++++++++++++ src/index.tsx | 1 + src/phoneGlyph.css.ts | 28 +++++++++++++ 4 files changed, 90 insertions(+) create mode 100644 src/app/phoneGlyph.test.ts create mode 100644 src/phoneGlyph.css.ts diff --git a/src/app/features/room-nav/styles.css.ts b/src/app/features/room-nav/styles.css.ts index 1d46e596..afa0c1a0 100644 --- a/src/app/features/room-nav/styles.css.ts +++ b/src/app/features/room-nav/styles.css.ts @@ -3,6 +3,7 @@ import { config } from 'folds'; import { surfaceInk } from '../scene/sceneShell.css'; import { skyLabelInk } from '../scene/skyLabelInk'; import { NAV_ICON_REST_OPACITY } from '../../components/nav/styles.css'; +import { PHONE_GLYPHS } from '../../../phoneGlyph.css'; export const CategoryButton = style({ flexGrow: 1, @@ -32,4 +33,11 @@ export const CategoryButton = style({ }); export const CategoryButtonIcon = style({ opacity: NAV_ICON_REST_OPACITY, + // A phone draws the 16 px chevron as its IconButton neighbours are drawn (see phoneGlyph.css.ts): paint-time, so + // the gutter and the row keep their layout. + '@media': { + 'screen and (max-width: 750px)': { + scale: `${PHONE_GLYPHS['50'].phonePx / PHONE_GLYPHS['50'].px}`, + }, + }, }); diff --git a/src/app/phoneGlyph.test.ts b/src/app/phoneGlyph.test.ts new file mode 100644 index 00000000..0e54c22a --- /dev/null +++ b/src/app/phoneGlyph.test.ts @@ -0,0 +1,53 @@ +import { readFileSync } from 'fs'; +import { describe, expect, it } from 'vitest'; +import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; +import { emitted } from './phoneHitTestKit'; +import { ICON_BUTTON_CLASS, PHONE_GLYPHS } from '../phoneGlyph.css'; + +const foldsJs = readFileSync(`${process.cwd()}/node_modules/folds/dist/index.js`, 'utf8'); + +describe('phone glyphs inside IconButtons', () => { + it("name folds' own classes: the IconButton base class and one Icon class per size", () => { + expect(foldsJs).toContain( + `var IconButton$1 = createRuntimeFn({ defaultClassName: "${ICON_BUTTON_CLASS} ` + ); + const iconSizes = foldsJs.match( + /var Icon\$1 = createRuntimeFn\(\{[^\n]*variantClassNames: \{ size: \{([^}]*)\}/ + )?.[1]; + expect(iconSizes).toBeDefined(); + Object.entries(PHONE_GLYPHS).forEach(([size, { cls }]) => + expect(iconSizes).toContain(`"${size}": "${cls}"`) + ); + }); + + it('draw the folds Icon px (16 18 20 22 24) at 22..28 px, never smaller, never past the smallest button box', () => { + // folds IconButton padding is 4 px a side at the smallest size, so its box is the glyph plus 8. + Object.values(PHONE_GLYPHS).forEach(({ px, phonePx }) => { + expect(phonePx).toBeGreaterThanOrEqual(22); + expect(phonePx).toBeLessThanOrEqual(28); + expect(phonePx).toBeGreaterThan(px); + expect(phonePx).toBeLessThanOrEqual(px + 8); + }); + }); + + it('are a paint-time scale on phones only: no size, margin or padding, and no rule outside the phone query', async () => { + const css = await emitted('../phoneGlyph.css.ts'); + const phone = `@media screen and (max-width: ${MOBILE_BREAKPOINT}px)`; + expect( + css.replace(new RegExp(`${phone.replace(/[()]/g, '\\$&')} \\{\\n[\\s\\S]*?\\n\\}`, 'g'), '') + ).not.toMatch(/\.brs7ce5/); + Object.entries(PHONE_GLYPHS).forEach(([size, { cls, px, phonePx }]) => { + const rule = css.match( + new RegExp(`\\.${ICON_BUTTON_CLASS} > \\.${cls} \\{\\n([^}]*)\\}`) + )?.[1]; + expect(rule, `rule for Icon size ${size}`).toBeDefined(); + expect( + rule! + .trim() + .split('\n') + .map((l) => l.trim().split(':')[0]) + ).toEqual(['scale']); + expect(Number(rule!.match(/scale: ([\d.]+)/)![1])).toBeCloseTo(phonePx / px, 6); + }); + }); +}); diff --git a/src/index.tsx b/src/index.tsx index 51e9760f..eca2bc07 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -14,6 +14,7 @@ import '@fontsource/montserrat/200.css'; import '@fontsource/montserrat/300.css'; import '@fontsource/ibm-plex-mono/400.css'; import 'folds/dist/style.css'; +import './phoneGlyph.css'; import { configClass, varsClass } from 'folds'; enableMapSet(); diff --git a/src/phoneGlyph.css.ts b/src/phoneGlyph.css.ts new file mode 100644 index 00000000..14707f63 --- /dev/null +++ b/src/phoneGlyph.css.ts @@ -0,0 +1,28 @@ +import { globalStyle } from '@vanilla-extract/css'; +import { MOBILE_BREAKPOINT } from './app/hooks/useScreenSize'; + +// Phone glyph size. On a phone the glyph inside an IconButton is drawn larger, by `scale` (a paint-time transform: +// the button's box, its PhoneHit area and every row of buttons keep the layout they have, so nothing reflows at +// 320 px). folds draws a glyph at one of its Icon sizes and the IconButton's box is padding plus that glyph, so the +// factor is chosen per Icon size. Desktop is not touched. +// +// The class names are folds 2.7.2's own (the Icon size classes and the IconButton base class); phoneGlyph.test.ts +// reads them back from folds' dist, so a folds upgrade that renames them fails there instead of silently here. +export const ICON_BUTTON_CLASS = 'brs7ce5'; +/** folds Icon size -> [its class, its px, the px it is drawn at on a phone]. The 24 px glyph is the folds default and + * reads small in a 40 px button, so it grows too; 28 px and up are already large. */ +export const PHONE_GLYPHS = { + '50': { cls: 'cpipac7', px: 16, phonePx: 22 }, + '100': { cls: 'cpipac8', px: 18, phonePx: 24 }, + '200': { cls: 'cpipac9', px: 20, phonePx: 24 }, + '300': { cls: 'cpipaca', px: 22, phonePx: 26 }, + '400': { cls: 'cpipacb', px: 24, phonePx: 28 }, +} as const; + +const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; + +Object.values(PHONE_GLYPHS).forEach(({ cls, px, phonePx }) => + globalStyle(`.${ICON_BUTTON_CLASS} > .${cls}`, { + '@media': { [PHONE]: { scale: `${phonePx / px}` } }, + }) +); From 9d65a345079507d14df0f7416b43fd28fa145d74 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 18:20:12 +0000 Subject: [PATCH 002/177] phoneGlyph test: pin each Icon size's px to folds' own CSS Co-Authored-By: Claude Sonnet 5.5 --- src/app/phoneGlyph.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/app/phoneGlyph.test.ts b/src/app/phoneGlyph.test.ts index 0e54c22a..6969da0e 100644 --- a/src/app/phoneGlyph.test.ts +++ b/src/app/phoneGlyph.test.ts @@ -5,6 +5,14 @@ import { emitted } from './phoneHitTestKit'; import { ICON_BUTTON_CLASS, PHONE_GLYPHS } from '../phoneGlyph.css'; const foldsJs = readFileSync(`${process.cwd()}/node_modules/folds/dist/index.js`, 'utf8'); +const foldsCss = readFileSync(`${process.cwd()}/node_modules/folds/dist/style.css`, 'utf8'); + +/** The px folds draws an Icon class at: its width variable's rem value, at the 16 px root. */ +const foldsPx = (cls: string) => { + const v = foldsCss.match(new RegExp(`\\.${cls} \\{\\s*width: var\\((--[\\w-]+)\\)`))?.[1]; + const rem = v && foldsCss.match(new RegExp(`${v}: ([\\d.]+)rem`))?.[1]; + return rem ? Number(rem) * 16 : undefined; +}; describe('phone glyphs inside IconButtons', () => { it("name folds' own classes: the IconButton base class and one Icon class per size", () => { @@ -20,6 +28,9 @@ describe('phone glyphs inside IconButtons', () => { ); }); + it("start from the px folds draws each Icon size at (the scale's divisor is not a guess)", () => + Object.values(PHONE_GLYPHS).forEach(({ cls, px }) => expect(foldsPx(cls)).toBe(px))); + it('draw the folds Icon px (16 18 20 22 24) at 22..28 px, never smaller, never past the smallest button box', () => { // folds IconButton padding is 4 px a side at the smallest size, so its box is the glyph plus 8. Object.values(PHONE_GLYPHS).forEach(({ px, phonePx }) => { From 4fd83fb4c415f1be025e0fecbbb35d570fffcf38 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 18:36:51 +0000 Subject: [PATCH 003/177] Soft logout keeps local data and re-logs in on the same device; MAS front hides register and reset Soft (soft_logout === true) drops only the access token and records the device; sign-in is fixed to that user and sends device_id; same user and device keeps the stores, anything else wipes via the one wipeLocalData. Hard logout still wipes. When discovery advertises an msc2965 account or issuer, the register and forgot-password entries give way to a notice pointing at the account page. Co-Authored-By: Claude Sonnet 5.5 --- src/app/pages/auth/MasAccountNotice.tsx | 11 ++ src/app/pages/auth/login/Login.tsx | 13 +- .../pages/auth/login/PasswordLoginForm.tsx | 92 ++++++++------ src/app/pages/auth/login/SoftLogoutNotice.tsx | 20 +++ src/app/pages/auth/login/TokenLogin.tsx | 16 ++- src/app/pages/auth/login/loginUtil.ts | 16 ++- src/app/pages/auth/masAccount.test.ts | 74 +++++++++++ src/app/pages/auth/masAccount.ts | 32 +++++ .../auth/register/RegisterRoute.test.tsx | 39 ++++-- src/app/pages/auth/register/RegisterRoute.tsx | 18 ++- .../auth/reset-password/ResetPassword.tsx | 9 +- src/app/pages/client/ClientRoot.tsx | 14 +- src/app/state/softLogout.test.ts | 120 ++++++++++++++++++ src/app/state/softLogout.ts | 91 +++++++++++++ src/client/initMatrix.ts | 53 ++++++-- 15 files changed, 541 insertions(+), 77 deletions(-) create mode 100644 src/app/pages/auth/MasAccountNotice.tsx create mode 100644 src/app/pages/auth/login/SoftLogoutNotice.tsx create mode 100644 src/app/pages/auth/masAccount.test.ts create mode 100644 src/app/pages/auth/masAccount.ts create mode 100644 src/app/state/softLogout.test.ts create mode 100644 src/app/state/softLogout.ts diff --git a/src/app/pages/auth/MasAccountNotice.tsx b/src/app/pages/auth/MasAccountNotice.tsx new file mode 100644 index 00000000..b8f506b4 --- /dev/null +++ b/src/app/pages/auth/MasAccountNotice.tsx @@ -0,0 +1,11 @@ +import { Text } from 'folds'; +import React from 'react'; + +export function MasAccountNotice({ url }: { url: string }) { + return ( + + Accounts here are managed by your sign-in service. Create or recover an account on its{' '} + account page. + + ); +} diff --git a/src/app/pages/auth/login/Login.tsx b/src/app/pages/auth/login/Login.tsx index ea08e4f0..05204779 100644 --- a/src/app/pages/auth/login/Login.tsx +++ b/src/app/pages/auth/login/Login.tsx @@ -15,6 +15,10 @@ import { getLoginPath, getRegisterPath, withSearchParam } from '../../pathUtils' import { usePathWithOrigin } from '../../../hooks/usePathWithOrigin'; import { LoginPathSearchParams } from '../../paths'; import { useClientConfig } from '../../../hooks/useClientConfig'; +import { useMasAccountUrl } from '../masAccount'; +import { MasAccountNotice } from '../MasAccountNotice'; +import { SoftLogoutNotice } from './SoftLogoutNotice'; +import { useSoftLogout } from '../../../state/softLogout'; import { noSignInMethodMessage } from '../authMessages'; const getLoginTokenSearchParam = () => { @@ -57,12 +61,15 @@ export function Login() { } const parsedFlows = useParsedLoginFlows(loginFlows.flows); + const masUrl = useMasAccountUrl(); + const softLogout = useSoftLogout(); return ( Login + {softLogout && } {parsedFlows.token && loginSearchParams.loginToken && ( )} @@ -93,9 +100,9 @@ export function Login() { )} - {registrationEntry(config) ? ( - - ) : ( + {masUrl && } + {!masUrl && registrationEntry(config) && } + {!masUrl && !registrationEntry(config) && ( Do not have an account? Register diff --git a/src/app/pages/auth/login/PasswordLoginForm.tsx b/src/app/pages/auth/login/PasswordLoginForm.tsx index 6372684c..63c28577 100644 --- a/src/app/pages/auth/login/PasswordLoginForm.tsx +++ b/src/app/pages/auth/login/PasswordLoginForm.tsx @@ -19,7 +19,7 @@ import { } from 'folds'; import FocusTrap from 'focus-trap-react'; import { Link } from 'react-router-dom'; -import { MatrixError } from 'matrix-js-sdk'; +import { LoginRequest, MatrixError } from 'matrix-js-sdk'; import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../../utils/matrix'; import { EMAIL_REGEX } from '../../../utils/regex'; import { useAutoDiscoveryInfo } from '../../../hooks/useAutoDiscoveryInfo'; @@ -39,6 +39,8 @@ import { loginErrorMessage } from '../authMessages'; import { ForgotLink } from '../styles.css'; import { getResetPasswordPath } from '../../pathUtils'; import { stopPropagation } from '../../../utils/keyboard'; +import { useSoftLogout, withSoftLogoutDevice } from '../../../state/softLogout'; +import { useMasAccountUrl } from '../masAccount'; import { PhoneHit } from '../../../styles/PhoneHit.css'; function UsernameHint({ server }: { server: string }) { @@ -118,6 +120,10 @@ export function PasswordLoginForm({ defaultUsername, defaultEmail }: PasswordLog const server = useAuthServer(); const clientConfig = useClientConfig(); + const softLogout = useSoftLogout(); + const masUrl = useMasAccountUrl(); + const withDevice = (request: LoginRequest) => withSoftLogoutDevice(request, softLogout); + const serverDiscovery = useAutoDiscoveryInfo(); const baseUrl = serverDiscovery['m.homeserver'].base_url; @@ -130,15 +136,18 @@ export function PasswordLoginForm({ defaultUsername, defaultEmail }: PasswordLog useLoginComplete(loginState.status === AsyncStatus.Success ? loginState.data : undefined); const handleUsernameLogin = (username: string, password: string) => { - startLogin(baseUrl, { - type: 'm.login.password', - identifier: { - type: 'm.id.user', - user: username, - }, - password, - initial_device_display_name: 'Ratatoskr Web', - }); + startLogin( + baseUrl, + withDevice({ + type: 'm.login.password', + identifier: { + type: 'm.id.user', + user: username, + }, + password, + initial_device_display_name: 'Ratatoskr Web', + }) + ); }; const handleMxIdLogin = async (mxId: string, password: string) => { @@ -148,27 +157,33 @@ export function PasswordLoginForm({ defaultUsername, defaultEmail }: PasswordLog const getBaseUrl = factoryGetBaseUrl(clientConfig, mxIdServer); - startLogin(getBaseUrl, { - type: 'm.login.password', - identifier: { - type: 'm.id.user', - user: mxIdUsername, - }, - password, - initial_device_display_name: 'Ratatoskr Web', - }); + startLogin( + getBaseUrl, + withDevice({ + type: 'm.login.password', + identifier: { + type: 'm.id.user', + user: mxIdUsername, + }, + password, + initial_device_display_name: 'Ratatoskr Web', + }) + ); }; const handleEmailLogin = (email: string, password: string) => { - startLogin(baseUrl, { - type: 'm.login.password', - identifier: { - type: 'm.id.thirdparty', - medium: 'email', - address: email, - }, - password, - initial_device_display_name: 'Ratatoskr Web', - }); + startLogin( + baseUrl, + withDevice({ + type: 'm.login.password', + identifier: { + type: 'm.id.thirdparty', + medium: 'email', + address: email, + }, + password, + initial_device_display_name: 'Ratatoskr Web', + }) + ); }; const handleSubmit: FormEventHandler = (evt) => { @@ -207,7 +222,8 @@ export function PasswordLoginForm({ defaultUsername, defaultEmail }: PasswordLog Username )} - - - - Forget Password? - - - + {!masUrl && ( + + + + Forget Password? + + + + )} + + ); +} diff --git a/src/app/pages/auth/login/TokenLogin.tsx b/src/app/pages/auth/login/TokenLogin.tsx index 0541742d..51a4b46b 100644 --- a/src/app/pages/auth/login/TokenLogin.tsx +++ b/src/app/pages/auth/login/TokenLogin.tsx @@ -14,6 +14,7 @@ import React, { useCallback, useEffect } from 'react'; import { MatrixError } from 'matrix-js-sdk'; import { useAutoDiscoveryInfo } from '../../../hooks/useAutoDiscoveryInfo'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; +import { useSoftLogout, withSoftLogoutDevice } from '../../../state/softLogout'; import { CustomLoginResponse, LoginError, login, useLoginComplete } from './loginUtil'; function LoginTokenError({ message }: { message: string }) { @@ -46,6 +47,7 @@ type TokenLoginProps = { export function TokenLogin({ token }: TokenLoginProps) { const discovery = useAutoDiscoveryInfo(); const baseUrl = discovery['m.homeserver'].base_url; + const softLogout = useSoftLogout(); const [loginState, startLogin] = useAsyncCallback< CustomLoginResponse, @@ -54,12 +56,14 @@ export function TokenLogin({ token }: TokenLoginProps) { >(useCallback(login, [])); useEffect(() => { - startLogin(baseUrl, { - type: 'm.login.token', - token, - initial_device_display_name: 'Ratatoskr Web', - }); - }, [baseUrl, token, startLogin]); + startLogin( + baseUrl, + withSoftLogoutDevice( + { type: 'm.login.token', token, initial_device_display_name: 'Ratatoskr Web' }, + softLogout + ) + ); + }, [baseUrl, token, softLogout, startLogin]); useLoginComplete(loginState.status === AsyncStatus.Success ? loginState.data : undefined); diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts index ba5b0bc9..f4124db7 100644 --- a/src/app/pages/auth/login/loginUtil.ts +++ b/src/app/pages/auth/login/loginUtil.ts @@ -11,6 +11,8 @@ import { } from '../../afterLoginRedirectPath'; import { getHomePath } from '../../pathUtils'; import { setFallbackSession } from '../../../state/sessions'; +import { clearSoftLogout, decideLoginOutcome, getSoftLogout } from '../../../state/softLogout'; +import { wipeLocalData } from '../../../../client/initMatrix'; export enum GetBaseUrlError { NotAllow = 'NotAllow', @@ -112,12 +114,18 @@ export const useLoginComplete = (data?: CustomLoginResponse) => { const navigate = useNavigate(); useEffect(() => { - if (data) { - const { response: loginRes, baseUrl: loginBaseUrl } = data; - setFallbackSession(loginRes.access_token, loginRes.device_id, loginRes.user_id, loginBaseUrl); + if (!data) return; + const { response: loginRes, baseUrl: loginBaseUrl } = data; + const finish = async () => { const afterLoginRedirectUrl = getAfterLoginRedirectPath(); + // A soft logout left stores behind; they stay only for the same user on the same device. + const outcome = decideLoginOutcome(getSoftLogout(), loginRes); + if (outcome === 'wipe') await wipeLocalData(); + clearSoftLogout(); + setFallbackSession(loginRes.access_token, loginRes.device_id, loginRes.user_id, loginBaseUrl); deleteAfterLoginRedirectPath(); navigate(afterLoginRedirectUrl ?? getHomePath(), { replace: true }); - } + }; + finish(); }, [data, navigate]); }; diff --git a/src/app/pages/auth/masAccount.test.ts b/src/app/pages/auth/masAccount.test.ts new file mode 100644 index 00000000..c45497f3 --- /dev/null +++ b/src/app/pages/auth/masAccount.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'fs'; +import { masAccountUrl } from './masAccount'; +import type { AutoDiscoveryInfo } from '../../cs-api'; + +const info = (auth?: unknown): AutoDiscoveryInfo => + ({ + 'm.homeserver': { base_url: 'https://hs.example' }, + ...(auth === undefined ? {} : { 'org.matrix.msc2965.authentication': auth }), + } as AutoDiscoveryInfo); + +describe('masAccountUrl', () => { + it('prefers the account url, then the issuer', () => { + expect( + masAccountUrl(info({ account: 'https://a.example/acc', issuer: 'https://a.example/' })) + ).toBe('https://a.example/acc'); + expect(masAccountUrl(info({ issuer: 'https://a.example/' }))).toBe('https://a.example/'); + }); + it('is undefined when nothing is advertised', () => { + expect(masAccountUrl(info())).toBeUndefined(); + expect(masAccountUrl(info({}))).toBeUndefined(); + }); + it('accepts http only for localhost', () => { + expect(masAccountUrl(info({ account: 'http://a.example/acc' }))).toBeUndefined(); + expect(masAccountUrl(info({ account: 'http://localhost:8080/acc' }))).toBe( + 'http://localhost:8080/acc' + ); + }); + it('skips an unusable account url and falls to a usable issuer', () => { + expect(masAccountUrl(info({ account: 'not a url', issuer: 'https://a.example/' }))).toBe( + 'https://a.example/' + ); + }); + it('rejects non-strings and non-http schemes', () => { + expect(masAccountUrl(info({ account: 42, issuer: { x: 1 } }))).toBeUndefined(); + expect(masAccountUrl(info({ account: 'data:text/html,x' }))).toBeUndefined(); + expect(masAccountUrl(info({ account: 'ftp://a.example' }))).toBeUndefined(); + }); +}); + +const src = (p: string) => readFileSync(`${process.cwd()}/src/app/pages/auth/${p}`, 'utf8'); + +describe('MAS front guards', () => { + it('Login hides both register entries behind the MAS predicate', () => { + const s = src('login/Login.tsx'); + expect(s).toContain('useMasAccountUrl()'); + expect(s).toContain('{masUrl && }'); + expect(s).toContain('{!masUrl && !registrationEntry(config) && ('); + }); + it('PasswordLoginForm hides the forgot link behind the MAS predicate', () => { + const s = src('login/PasswordLoginForm.tsx'); + expect(s).toContain('useMasAccountUrl()'); + expect(s).toMatch(/\{!masUrl && \([\s\S]*getResetPasswordPath/); + }); + it('RegisterRoute and ResetPassword show the notice under MAS', () => { + ['register/RegisterRoute.tsx', 'reset-password/ResetPassword.tsx'].forEach((p) => { + const s = src(p); + expect(s).toContain('useMasAccountUrl()'); + expect(s).toContain(' { + expect(src('login/PasswordLoginForm.tsx').match(/withDevice\(\{/g)).toHaveLength(3); + expect(src('login/TokenLogin.tsx')).toContain('withSoftLogoutDevice('); + }); + it('the logout listener and login completion defer to the one wipe', () => { + const root = readFileSync(`${process.cwd()}/src/app/pages/client/ClientRoot.tsx`, 'utf8'); + expect(root).toContain('classifyLogout(err)'); + expect(root).toContain('wipeLocalData(mx)'); + expect(root).not.toContain('localStorage.clear'); + expect(src('login/loginUtil.ts')).toContain('wipeLocalData()'); + }); +}); diff --git a/src/app/pages/auth/masAccount.ts b/src/app/pages/auth/masAccount.ts new file mode 100644 index 00000000..b131a916 --- /dev/null +++ b/src/app/pages/auth/masAccount.ts @@ -0,0 +1,32 @@ +import { useAutoDiscoveryInfo } from '../../hooks/useAutoDiscoveryInfo'; +import type { AutoDiscoveryInfo } from '../../cs-api'; + +// Plain http is for a developer's own machine only. +const isLocalHost = (hostname: string): boolean => + hostname === 'localhost' || + hostname.endsWith('.localhost') || + hostname === '127.0.0.1' || + hostname === '[::1]'; + +const usable = (value: unknown): string | undefined => { + if (typeof value !== 'string') return undefined; + try { + const { protocol, hostname } = new URL(value); + if (protocol === 'https:' || (protocol === 'http:' && isLocalHost(hostname))) return value; + } catch { + // not a url + } + return undefined; +}; + +/** + * The account page of the sign-in service fronting this homeserver (MAS), when discovery + * advertises one: the account url, else the issuer, the same preference the devices page uses. + * Undefined means the homeserver manages its own accounts. + */ +export const masAccountUrl = (info: AutoDiscoveryInfo): string | undefined => { + const auth = info['org.matrix.msc2965.authentication']; + return usable(auth?.account) ?? usable(auth?.issuer); +}; + +export const useMasAccountUrl = (): string | undefined => masAccountUrl(useAutoDiscoveryInfo()); diff --git a/src/app/pages/auth/register/RegisterRoute.test.tsx b/src/app/pages/auth/register/RegisterRoute.test.tsx index 043c1174..1fde64cd 100644 --- a/src/app/pages/auth/register/RegisterRoute.test.tsx +++ b/src/app/pages/auth/register/RegisterRoute.test.tsx @@ -3,16 +3,26 @@ import { describe, expect, it, vi } from 'vitest'; import { renderToString } from 'react-dom/server'; import { ClientConfigProvider } from '../../../hooks/useClientConfig'; import type { ClientConfig } from '../../../hooks/useClientConfig'; +import { AutoDiscoveryInfoProvider } from '../../../hooks/useAutoDiscoveryInfo'; +import type { AutoDiscoveryInfo } from '../../../cs-api'; import { RegisterRoute } from './RegisterRoute'; // The in-client form needs a homeserver; the route test only needs to know whether it was asked for. vi.mock('./Register', () => ({ Register: () =>
in-client register form
})); -const render = (config: ClientConfig) => +const plain: AutoDiscoveryInfo = { 'm.homeserver': { base_url: 'https://hs.example' } }; +const mas: AutoDiscoveryInfo = { + ...plain, + 'org.matrix.msc2965.authentication': { account: 'https://auth.example/account' }, +}; + +const render = (config: ClientConfig, info: AutoDiscoveryInfo = plain) => renderToString( - - - + + + + + ); describe('the /register route', () => { @@ -23,15 +33,26 @@ describe('the /register route', () => { }); it('with the switch off shows the in-client form', () => { - expect(render({ registration: { enabled: false, url: 'https://accounts.example/join' } })).toContain( - 'in-client register form' - ); + expect( + render({ registration: { enabled: false, url: 'https://accounts.example/join' } }) + ).toContain('in-client register form'); expect(render({})).toContain('in-client register form'); }); it('with the switch on but an unusable url falls back to the form', () => { - expect(render({ registration: { enabled: true, url: 'ftp://accounts.example/join' } })).toContain( - 'in-client register form' + expect( + render({ registration: { enabled: true, url: 'ftp://accounts.example/join' } }) + ).toContain('in-client register form'); + }); + + it('under MAS shows the account page notice, not the form, with the switch on or off', () => { + [{}, { registration: { enabled: true, url: 'https://accounts.example/join' } }].forEach( + (config) => { + const html = render(config, mas); + expect(html).toContain('href="https://auth.example/account"'); + expect(html).not.toContain('in-client register form'); + expect(html).not.toContain('Continue to sign up'); + } ); }); }); diff --git a/src/app/pages/auth/register/RegisterRoute.tsx b/src/app/pages/auth/register/RegisterRoute.tsx index 094bc8fd..fa56527a 100644 --- a/src/app/pages/auth/register/RegisterRoute.tsx +++ b/src/app/pages/auth/register/RegisterRoute.tsx @@ -2,6 +2,8 @@ import { Box, Text } from 'folds'; import React, { useEffect } from 'react'; import { useClientConfig } from '../../../hooks/useClientConfig'; import { registrationEntry } from '../registrationEntry'; +import { useMasAccountUrl } from '../masAccount'; +import { MasAccountNotice } from '../MasAccountNotice'; import { Register } from './Register'; // With the Register switch on, a stranger gets one way to register: the account service's own @@ -9,9 +11,21 @@ import { Register } from './Register'; // the switch off, the in-client form is the way. export function RegisterRoute() { const entry = registrationEntry(useClientConfig()); + const masUrl = useMasAccountUrl(); useEffect(() => { - if (entry) window.location.replace(entry.url); - }, [entry]); + if (entry && !masUrl) window.location.replace(entry.url); + }, [entry, masUrl]); + // Under MAS the in-client sign-up (UIA) cannot work; the account page is the only way. + if (masUrl) { + return ( + + + Register + + + + ); + } if (!entry) return ; return ( diff --git a/src/app/pages/auth/reset-password/ResetPassword.tsx b/src/app/pages/auth/reset-password/ResetPassword.tsx index c5e1d2ad..b9c2e9a6 100644 --- a/src/app/pages/auth/reset-password/ResetPassword.tsx +++ b/src/app/pages/auth/reset-password/ResetPassword.tsx @@ -4,6 +4,8 @@ import { Link, useSearchParams } from 'react-router-dom'; import { getLoginPath } from '../../pathUtils'; import { useAuthServer } from '../../../hooks/useAuthServer'; import { PasswordResetForm } from './PasswordResetForm'; +import { useMasAccountUrl } from '../masAccount'; +import { MasAccountNotice } from '../MasAccountNotice'; import { ResetPasswordPathSearchParams } from '../../paths'; const useResetPasswordSearchParams = ( @@ -18,6 +20,7 @@ const useResetPasswordSearchParams = ( export function ResetPassword() { const server = useAuthServer(); + const masUrl = useMasAccountUrl(); const [searchParams] = useSearchParams(); const resetPasswordSearchParams = useResetPasswordSearchParams(searchParams); @@ -26,7 +29,11 @@ export function ResetPassword() { Reset Password - + {masUrl ? ( + + ) : ( + + )} diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 565ff058..dd63226a 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -19,6 +19,7 @@ import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useState } import { clearCacheAndReload, clearLoginData, + wipeLocalData, initClient, logoutClient, startClient, @@ -35,6 +36,8 @@ import { stopPropagation } from '../../utils/keyboard'; import { SyncStatus } from './SyncStatus'; import { AuthMetadataProvider } from '../../hooks/useAuthMetadata'; import { getFallbackSession } from '../../state/sessions'; +import { beginSoftLogout, classifyLogout } from '../../state/softLogout'; +import { pushSessionToSW } from '../../../sw-session'; import { AutoDiscovery } from './AutoDiscovery'; import { PhoneHit } from '../../styles/PhoneHit.css'; @@ -127,10 +130,15 @@ function ClientRootOptions({ mx }: { mx?: MatrixClient }) { const useLogoutListener = (mx?: MatrixClient) => { useEffect(() => { - const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { + const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async (err) => { mx?.stopClient(); - await mx?.clearStores(); - window.localStorage.clear(); + // Soft: the token is dead, the device is not. Keep the stores and ask for a sign-in. + if (classifyLogout(err) === 'soft' && beginSoftLogout()) { + pushSessionToSW(); + window.location.reload(); + return; + } + await wipeLocalData(mx); window.location.reload(); }; diff --git a/src/app/state/softLogout.test.ts b/src/app/state/softLogout.test.ts new file mode 100644 index 00000000..e529288d --- /dev/null +++ b/src/app/state/softLogout.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest'; +import { MatrixError } from 'matrix-js-sdk'; +import { setFallbackSession, getFallbackSession } from './sessions'; +import { + beginSoftLogout, + classifyLogout, + clearSoftLogout, + decideLoginOutcome, + getSoftLogout, + setSoftLogout, + withSoftLogoutDevice, +} from './softLogout'; + +const memoryStorage = (): Storage => { + const m = new Map(); + return { + get length() { + return m.size; + }, + clear: () => m.clear(), + getItem: (k) => m.get(k) ?? null, + key: (i) => [...m.keys()][i] ?? null, + removeItem: (k) => { + m.delete(k); + }, + setItem: (k, v) => { + m.set(k, String(v)); + }, + }; +}; + +const record = { userId: '@a:hs', deviceId: 'DEV', baseUrl: 'https://hs.example' }; + +describe('classifyLogout', () => { + it('is soft only for soft_logout === true', () => { + expect(classifyLogout(new MatrixError({ errcode: 'M_UNKNOWN_TOKEN', soft_logout: true }))).toBe( + 'soft' + ); + expect(classifyLogout({ data: { soft_logout: true } })).toBe('soft'); + }); + it('is hard for false, absent, string-ish, and non-MatrixError values', () => { + expect( + classifyLogout(new MatrixError({ errcode: 'M_UNKNOWN_TOKEN', soft_logout: false })) + ).toBe('hard'); + expect(classifyLogout(new MatrixError({ errcode: 'M_UNKNOWN_TOKEN' }))).toBe('hard'); + expect(classifyLogout({ data: { soft_logout: 'true' } })).toBe('hard'); + expect(classifyLogout(undefined)).toBe('hard'); + expect(classifyLogout(null)).toBe('hard'); + expect(classifyLogout('boom')).toBe('hard'); + expect(classifyLogout(new Error('x'))).toBe('hard'); + }); +}); + +describe('the soft logout record', () => { + it('round-trips and clears', () => { + const s = memoryStorage(); + expect(getSoftLogout(s)).toBeUndefined(); + setSoftLogout(record, s); + expect(getSoftLogout(s)).toEqual(record); + clearSoftLogout(s); + expect(getSoftLogout(s)).toBeUndefined(); + }); + it('treats garbage and partial records as absent', () => { + const s = memoryStorage(); + s.setItem('ratatoskr_soft_logout', 'not json'); + expect(getSoftLogout(s)).toBeUndefined(); + s.setItem('ratatoskr_soft_logout', JSON.stringify({ userId: '@a:hs', deviceId: '' })); + expect(getSoftLogout(s)).toBeUndefined(); + }); +}); + +describe('beginSoftLogout', () => { + it('keeps the device keys and the record, drops only the access token', () => { + const s = memoryStorage(); + const real = globalThis.localStorage; + Object.defineProperty(globalThis, 'localStorage', { value: s, configurable: true }); + try { + setFallbackSession('tok', 'DEV', '@a:hs', 'https://hs.example'); + s.setItem('other_key', 'kept'); + } finally { + Object.defineProperty(globalThis, 'localStorage', { value: real, configurable: true }); + } + expect(beginSoftLogout(s)).toBe(true); + expect(getFallbackSession(s)).toBeUndefined(); + expect(s.getItem('cinny_access_token')).toBeNull(); + expect(s.getItem('cinny_device_id')).toBe('DEV'); + expect(s.getItem('other_key')).toBe('kept'); + expect(getSoftLogout(s)).toEqual(record); + }); + it('does nothing without a session', () => { + const s = memoryStorage(); + expect(beginSoftLogout(s)).toBe(false); + expect(getSoftLogout(s)).toBeUndefined(); + }); +}); + +describe('withSoftLogoutDevice', () => { + const req = { type: 'm.login.password', password: 'p' } as const; + it('asks for the recorded device on password and token requests alike', () => { + expect(withSoftLogoutDevice(req, record)).toEqual({ ...req, device_id: 'DEV' }); + const tok = { type: 'm.login.token', token: 't' }; + expect(withSoftLogoutDevice(tok, record)).toEqual({ ...tok, device_id: 'DEV' }); + }); + it('leaves the request alone without a record', () => { + expect(withSoftLogoutDevice(req, undefined)).toBe(req); + }); +}); + +describe('decideLoginOutcome', () => { + it('is plain without a record', () => { + expect(decideLoginOutcome(undefined, { user_id: '@a:hs', device_id: 'DEV' })).toBe('plain'); + }); + it('keeps for the same user and device', () => { + expect(decideLoginOutcome(record, { user_id: '@a:hs', device_id: 'DEV' })).toBe('keep'); + }); + it('wipes for another user or another device', () => { + expect(decideLoginOutcome(record, { user_id: '@b:hs', device_id: 'DEV' })).toBe('wipe'); + expect(decideLoginOutcome(record, { user_id: '@a:hs', device_id: 'NEW' })).toBe('wipe'); + }); +}); diff --git a/src/app/state/softLogout.ts b/src/app/state/softLogout.ts new file mode 100644 index 00000000..d7ea1180 --- /dev/null +++ b/src/app/state/softLogout.ts @@ -0,0 +1,91 @@ +import { useState } from 'react'; +import type { LoginRequest } from 'matrix-js-sdk'; +import { getFallbackSession } from './sessions'; + +// A soft logout is the server saying "this token is dead, the device is not": the local stores +// stay, only the access token goes, and this record says whose device to sign back in as. +const SOFT_LOGOUT_KEY = 'ratatoskr_soft_logout'; +const ACCESS_TOKEN_KEY = 'cinny_access_token'; + +export type SoftLogoutRecord = { + userId: string; + deviceId: string; + baseUrl: string; +}; + +export const getSoftLogout = (storage: Storage = localStorage): SoftLogoutRecord | undefined => { + const raw = storage.getItem(SOFT_LOGOUT_KEY); + if (!raw) return undefined; + try { + const { userId, deviceId, baseUrl } = JSON.parse(raw) as Partial; + if ( + typeof userId === 'string' && + typeof deviceId === 'string' && + typeof baseUrl === 'string' && + userId && + deviceId && + baseUrl + ) { + return { userId, deviceId, baseUrl }; + } + } catch { + // an unreadable record is no record + } + return undefined; +}; + +export const setSoftLogout = (record: SoftLogoutRecord, storage: Storage = localStorage) => { + storage.setItem(SOFT_LOGOUT_KEY, JSON.stringify(record)); +}; + +export const clearSoftLogout = (storage: Storage = localStorage) => { + storage.removeItem(SOFT_LOGOUT_KEY); +}; + +export type LogoutKind = 'soft' | 'hard'; + +/** Soft only when the server said so: soft_logout === true. Anything else is hard. */ +export const classifyLogout = (err: unknown): LogoutKind => { + const data = (err as { data?: { soft_logout?: unknown } } | null | undefined)?.data; + return data?.soft_logout === true ? 'soft' : 'hard'; +}; + +/** + * Enter the soft-logout state: remember the device, drop only the access token. Returns false + * (and changes nothing) when there is no session to remember, which the caller treats as hard. + */ +export const beginSoftLogout = (storage: Storage = localStorage): boolean => { + const session = getFallbackSession(storage); + if (!session) return false; + setSoftLogout( + { userId: session.userId, deviceId: session.deviceId, baseUrl: session.baseUrl }, + storage + ); + storage.removeItem(ACCESS_TOKEN_KEY); + return true; +}; + +/** Every login request while a record stands asks for the same device back. */ +export const withSoftLogoutDevice = ( + request: LoginRequest, + record: SoftLogoutRecord | undefined +): LoginRequest => (record ? { ...request, device_id: record.deviceId } : request); + +export type LoginOutcome = 'plain' | 'keep' | 'wipe'; + +/** + * What a finished login does to local data. No record: a plain login, as ever. A record that + * names this very user and device: keep the stores. Any other answer: the stores belong to + * someone else, wipe them first. + */ +export const decideLoginOutcome = ( + record: SoftLogoutRecord | undefined, + response: { user_id: string; device_id: string } +): LoginOutcome => { + if (!record) return 'plain'; + return record.userId === response.user_id && record.deviceId === response.device_id + ? 'keep' + : 'wipe'; +}; + +export const useSoftLogout = (): SoftLogoutRecord | undefined => useState(() => getSoftLogout())[0]; diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 871c186a..b6d22597 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -111,6 +111,45 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { window.location.reload(); }; +// The rust crypto databases the SDK names, for browsers without indexedDB.databases(). +const KNOWN_DATABASES = [ + 'web-sync-store', + 'crypto-store', + 'matrix-js-sdk::matrix-sdk-crypto', + 'matrix-js-sdk::matrix-sdk-crypto-meta', +]; + +const deleteDatabase = (name: string) => + new Promise((resolve) => { + const req = window.indexedDB.deleteDatabase(name); + req.onsuccess = () => resolve(); + req.onerror = () => resolve(); + req.onblocked = () => resolve(); + }); + +/** + * The one wipe of everything this browser holds for the account: client stores, every IndexedDB + * database, localStorage. Hard logout, a soft logout answered by another user or device, and + * "sign in as someone else" all end here. Callers reload afterwards. + */ +export const wipeLocalData = async (mx?: MatrixClient) => { + try { + await mx?.clearStores(); + } catch { + // the databases go below regardless + } + let names: string[]; + try { + names = (await window.indexedDB.databases()) + .map((db) => db.name) + .filter((name): name is string => !!name); + } catch { + names = KNOWN_DATABASES; + } + await Promise.all(names.map(deleteDatabase)); + window.localStorage.clear(); +}; + export const logoutClient = async (mx: MatrixClient) => { pushSessionToSW(); mx.stopClient(); @@ -119,21 +158,11 @@ export const logoutClient = async (mx: MatrixClient) => { } catch { // ignore if failed to logout } - await mx.clearStores(); - window.localStorage.clear(); + await wipeLocalData(mx); window.location.reload(); }; export const clearLoginData = async () => { - const dbs = await window.indexedDB.databases(); - - dbs.forEach((idbInfo) => { - const { name } = idbInfo; - if (name) { - window.indexedDB.deleteDatabase(name); - } - }); - - window.localStorage.clear(); + await wipeLocalData(); window.location.reload(); }; From 3a5258c3ef7344a9211f3ef9dddd5450d7e5cb09 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 18:40:59 +0000 Subject: [PATCH 004/177] Soul fixes: idempotent logout handler, keep register consent entry under MAS, settle stores on register First SessionLoggedOut decides; later events are ignored so a second soft event cannot fall into the wipe. Under MAS a configured registrationEntry (with its training notice) is kept; the MAS notice replaces only the in-client form and bare link. Registration goes through the same keep-or-wipe settle as login. Soft record drops its unused baseUrl. One shared https-or-localhost predicate. Co-Authored-By: Claude Sonnet 5.5 --- src/app/pages/auth/login/Login.tsx | 7 +- src/app/pages/auth/login/loginUtil.ts | 6 +- src/app/pages/auth/masAccount.test.ts | 13 +-- src/app/pages/auth/masAccount.ts | 20 +--- .../auth/register/RegisterRoute.test.tsx | 21 ++-- src/app/pages/auth/register/RegisterRoute.tsx | 9 +- src/app/pages/auth/register/registerUtil.ts | 13 ++- src/app/pages/auth/registrationEntry.ts | 15 +-- src/app/pages/client/ClientRoot.tsx | 20 ++-- src/app/state/softLogout.test.ts | 96 ++++++++++++++++++- src/app/state/softLogout.ts | 63 +++++++++--- src/app/utils/secureUrl.ts | 16 ++++ 12 files changed, 214 insertions(+), 85 deletions(-) create mode 100644 src/app/utils/secureUrl.ts diff --git a/src/app/pages/auth/login/Login.tsx b/src/app/pages/auth/login/Login.tsx index 05204779..3606a9a4 100644 --- a/src/app/pages/auth/login/Login.tsx +++ b/src/app/pages/auth/login/Login.tsx @@ -62,6 +62,7 @@ export function Login() { const parsedFlows = useParsedLoginFlows(loginFlows.flows); const masUrl = useMasAccountUrl(); + const registerEntry = registrationEntry(config); const softLogout = useSoftLogout(); return ( @@ -100,9 +101,9 @@ export function Login() { )} - {masUrl && } - {!masUrl && registrationEntry(config) && } - {!masUrl && !registrationEntry(config) && ( + {registerEntry && } + {!registerEntry && masUrl && } + {!registerEntry && !masUrl && ( Do not have an account? Register diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts index f4124db7..7a9cfb38 100644 --- a/src/app/pages/auth/login/loginUtil.ts +++ b/src/app/pages/auth/login/loginUtil.ts @@ -11,7 +11,7 @@ import { } from '../../afterLoginRedirectPath'; import { getHomePath } from '../../pathUtils'; import { setFallbackSession } from '../../../state/sessions'; -import { clearSoftLogout, decideLoginOutcome, getSoftLogout } from '../../../state/softLogout'; +import { settleLocalData } from '../../../state/softLogout'; import { wipeLocalData } from '../../../../client/initMatrix'; export enum GetBaseUrlError { @@ -119,9 +119,7 @@ export const useLoginComplete = (data?: CustomLoginResponse) => { const finish = async () => { const afterLoginRedirectUrl = getAfterLoginRedirectPath(); // A soft logout left stores behind; they stay only for the same user on the same device. - const outcome = decideLoginOutcome(getSoftLogout(), loginRes); - if (outcome === 'wipe') await wipeLocalData(); - clearSoftLogout(); + await settleLocalData(loginRes, () => wipeLocalData()); setFallbackSession(loginRes.access_token, loginRes.device_id, loginRes.user_id, loginBaseUrl); deleteAfterLoginRedirectPath(); navigate(afterLoginRedirectUrl ?? getHomePath(), { replace: true }); diff --git a/src/app/pages/auth/masAccount.test.ts b/src/app/pages/auth/masAccount.test.ts index c45497f3..f2331365 100644 --- a/src/app/pages/auth/masAccount.test.ts +++ b/src/app/pages/auth/masAccount.test.ts @@ -41,12 +41,12 @@ describe('masAccountUrl', () => { const src = (p: string) => readFileSync(`${process.cwd()}/src/app/pages/auth/${p}`, 'utf8'); describe('MAS front guards', () => { - it('Login hides both register entries behind the MAS predicate', () => { + it('Login keeps a configured register entry, else MAS notice, else the bare link', () => { const s = src('login/Login.tsx'); expect(s).toContain('useMasAccountUrl()'); - expect(s).toContain('{masUrl && }'); - expect(s).toContain('{!masUrl && !registrationEntry(config) && ('); + expect(s).toContain('{registerEntry && }'); + expect(s).toContain('{!registerEntry && masUrl && { const s = src('login/PasswordLoginForm.tsx'); @@ -66,9 +66,10 @@ describe('MAS front guards', () => { }); it('the logout listener and login completion defer to the one wipe', () => { const root = readFileSync(`${process.cwd()}/src/app/pages/client/ClientRoot.tsx`, 'utf8'); - expect(root).toContain('classifyLogout(err)'); + expect(root).toContain('createLogoutHandler('); expect(root).toContain('wipeLocalData(mx)'); expect(root).not.toContain('localStorage.clear'); - expect(src('login/loginUtil.ts')).toContain('wipeLocalData()'); + expect(src('login/loginUtil.ts')).toContain('settleLocalData(loginRes'); + expect(src('register/registerUtil.ts')).toContain('settleLocalData('); }); }); diff --git a/src/app/pages/auth/masAccount.ts b/src/app/pages/auth/masAccount.ts index b131a916..6e65b2a4 100644 --- a/src/app/pages/auth/masAccount.ts +++ b/src/app/pages/auth/masAccount.ts @@ -1,23 +1,9 @@ import { useAutoDiscoveryInfo } from '../../hooks/useAutoDiscoveryInfo'; +import { isSecureOrLocalUrl } from '../../utils/secureUrl'; import type { AutoDiscoveryInfo } from '../../cs-api'; -// Plain http is for a developer's own machine only. -const isLocalHost = (hostname: string): boolean => - hostname === 'localhost' || - hostname.endsWith('.localhost') || - hostname === '127.0.0.1' || - hostname === '[::1]'; - -const usable = (value: unknown): string | undefined => { - if (typeof value !== 'string') return undefined; - try { - const { protocol, hostname } = new URL(value); - if (protocol === 'https:' || (protocol === 'http:' && isLocalHost(hostname))) return value; - } catch { - // not a url - } - return undefined; -}; +const usable = (value: unknown): string | undefined => + typeof value === 'string' && isSecureOrLocalUrl(value) ? value : undefined; /** * The account page of the sign-in service fronting this homeserver (MAS), when discovery diff --git a/src/app/pages/auth/register/RegisterRoute.test.tsx b/src/app/pages/auth/register/RegisterRoute.test.tsx index 1fde64cd..47ea7179 100644 --- a/src/app/pages/auth/register/RegisterRoute.test.tsx +++ b/src/app/pages/auth/register/RegisterRoute.test.tsx @@ -45,14 +45,19 @@ describe('the /register route', () => { ).toContain('in-client register form'); }); - it('under MAS shows the account page notice, not the form, with the switch on or off', () => { - [{}, { registration: { enabled: true, url: 'https://accounts.example/join' } }].forEach( - (config) => { - const html = render(config, mas); - expect(html).toContain('href="https://auth.example/account"'); - expect(html).not.toContain('in-client register form'); - expect(html).not.toContain('Continue to sign up'); - } + it('under MAS with no configured entry shows the account page notice, not the form', () => { + const html = render({}, mas); + expect(html).toContain('href="https://auth.example/account"'); + expect(html).not.toContain('in-client register form'); + }); + + it('under MAS a configured entry keeps its own page, not the notice or the form', () => { + const html = render( + { registration: { enabled: true, url: 'https://accounts.example/join' } }, + mas ); + expect(html).toContain('href="https://accounts.example/join"'); + expect(html).not.toContain('auth.example/account'); + expect(html).not.toContain('in-client register form'); }); }); diff --git a/src/app/pages/auth/register/RegisterRoute.tsx b/src/app/pages/auth/register/RegisterRoute.tsx index fa56527a..ee68dd45 100644 --- a/src/app/pages/auth/register/RegisterRoute.tsx +++ b/src/app/pages/auth/register/RegisterRoute.tsx @@ -13,10 +13,11 @@ export function RegisterRoute() { const entry = registrationEntry(useClientConfig()); const masUrl = useMasAccountUrl(); useEffect(() => { - if (entry && !masUrl) window.location.replace(entry.url); - }, [entry, masUrl]); - // Under MAS the in-client sign-up (UIA) cannot work; the account page is the only way. - if (masUrl) { + if (entry) window.location.replace(entry.url); + }, [entry]); + // Under MAS the in-client sign-up (UIA) cannot work; with no configured entry the account page + // is the only way. A configured entry keeps its own page and its training notice. + if (!entry && masUrl) { return ( diff --git a/src/app/pages/auth/register/registerUtil.ts b/src/app/pages/auth/register/registerUtil.ts index 02f530fb..9d5afa87 100644 --- a/src/app/pages/auth/register/registerUtil.ts +++ b/src/app/pages/auth/register/registerUtil.ts @@ -17,6 +17,8 @@ import { import { getHomePath, getLoginPath, withSearchParam } from '../../pathUtils'; import { getMxIdLocalPart, getMxIdServer } from '../../../utils/matrix'; import { setFallbackSession } from '../../../state/sessions'; +import { settleLocalData } from '../../../state/softLogout'; +import { wipeLocalData } from '../../../../client/initMatrix'; import type { RegisterTrouble } from '../authMessages'; export enum RegisterError { @@ -141,10 +143,15 @@ export const useRegisterComplete = (data?: CustomRegisterResponse) => { const deviceId = response.device_id; if (accessToken && deviceId) { - setFallbackSession(accessToken, deviceId, userId, baseUrl); const afterLoginRedirectPath = getAfterLoginRedirectPath(); - deleteAfterLoginRedirectPath(); - navigate(afterLoginRedirectPath ?? getHomePath(), { replace: true }); + // A new account never boots on a soft-logged-out user's stores. + settleLocalData({ user_id: userId, device_id: deviceId }, () => wipeLocalData()).then( + () => { + setFallbackSession(accessToken, deviceId, userId, baseUrl); + deleteAfterLoginRedirectPath(); + navigate(afterLoginRedirectPath ?? getHomePath(), { replace: true }); + } + ); } else { const username = getMxIdLocalPart(userId); const userServer = getMxIdServer(userId); diff --git a/src/app/pages/auth/registrationEntry.ts b/src/app/pages/auth/registrationEntry.ts index 6c65732e..2aa0e34d 100644 --- a/src/app/pages/auth/registrationEntry.ts +++ b/src/app/pages/auth/registrationEntry.ts @@ -1,15 +1,9 @@ import type { ClientConfig } from '../../hooks/useClientConfig'; +import { isSecureOrLocalUrl } from '../../utils/secureUrl'; import { TRAINING_NOTICE_VERSION, trainingNoticeText } from '../../utils/trainingNotice'; export type RegistrationEntry = { url: string; notice: string; noticeVersion: number }; -// Plain http is for a developer's own machine only; a stranger's sign-up page is https. -const isLocalHost = (hostname: string): boolean => - hostname === 'localhost' || - hostname.endsWith('.localhost') || - hostname === '127.0.0.1' || - hostname === '[::1]'; - /** * The sign-up entry the sign-in page may show: the account service's registration page, when the * switch is on and the configured url is an https address (http only for localhost). Anything else is no entry. The @@ -18,12 +12,7 @@ const isLocalHost = (hostname: string): boolean => export const registrationEntry = (config: ClientConfig): RegistrationEntry | undefined => { const { enabled, url } = config.registration ?? {}; if (enabled !== true || typeof url !== 'string') return undefined; - try { - const { protocol, hostname } = new URL(url); - if (protocol !== 'https:' && !(protocol === 'http:' && isLocalHost(hostname))) return undefined; - } catch { - return undefined; - } + if (!isSecureOrLocalUrl(url)) return undefined; return { url, notice: trainingNoticeText(config.previewDemo), diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index dd63226a..2cb69ed5 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -36,7 +36,7 @@ import { stopPropagation } from '../../utils/keyboard'; import { SyncStatus } from './SyncStatus'; import { AuthMetadataProvider } from '../../hooks/useAuthMetadata'; import { getFallbackSession } from '../../state/sessions'; -import { beginSoftLogout, classifyLogout } from '../../state/softLogout'; +import { createLogoutHandler } from '../../state/softLogout'; import { pushSessionToSW } from '../../../sw-session'; import { AutoDiscovery } from './AutoDiscovery'; import { PhoneHit } from '../../styles/PhoneHit.css'; @@ -130,17 +130,15 @@ function ClientRootOptions({ mx }: { mx?: MatrixClient }) { const useLogoutListener = (mx?: MatrixClient) => { useEffect(() => { - const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async (err) => { - mx?.stopClient(); - // Soft: the token is dead, the device is not. Keep the stores and ask for a sign-in. - if (classifyLogout(err) === 'soft' && beginSoftLogout()) { - pushSessionToSW(); - window.location.reload(); - return; + const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = createLogoutHandler( + { + storage: window.localStorage, + stop: () => mx?.stopClient(), + wipe: () => wipeLocalData(mx), + reload: () => window.location.reload(), + forgetSessionInWorker: () => pushSessionToSW(), } - await wipeLocalData(mx); - window.location.reload(); - }; + ); mx?.on(HttpApiEvent.SessionLoggedOut, handleLogout); return () => { diff --git a/src/app/state/softLogout.test.ts b/src/app/state/softLogout.test.ts index e529288d..8df1a8f8 100644 --- a/src/app/state/softLogout.test.ts +++ b/src/app/state/softLogout.test.ts @@ -5,6 +5,8 @@ import { beginSoftLogout, classifyLogout, clearSoftLogout, + createLogoutHandler, + settleLocalData, decideLoginOutcome, getSoftLogout, setSoftLogout, @@ -29,7 +31,7 @@ const memoryStorage = (): Storage => { }; }; -const record = { userId: '@a:hs', deviceId: 'DEV', baseUrl: 'https://hs.example' }; +const record = { userId: '@a:hs', deviceId: 'DEV' }; describe('classifyLogout', () => { it('is soft only for soft_logout === true', () => { @@ -118,3 +120,95 @@ describe('decideLoginOutcome', () => { expect(decideLoginOutcome(record, { user_id: '@a:hs', device_id: 'NEW' })).toBe('wipe'); }); }); + +describe('the logout handler', () => { + const rig = (soft: boolean) => { + const storage = memoryStorage(); + storage.setItem('cinny_access_token', 'tok'); + storage.setItem('cinny_device_id', 'DEV'); + storage.setItem('cinny_user_id', '@a:hs'); + storage.setItem('cinny_hs_base_url', 'https://hs.example'); + const calls = { stop: 0, wipe: 0, reload: 0, worker: 0 }; + const handler = createLogoutHandler({ + storage, + stop: () => { + calls.stop += 1; + }, + wipe: async () => { + calls.wipe += 1; + }, + reload: () => { + calls.reload += 1; + }, + forgetSessionInWorker: () => { + calls.worker += 1; + }, + }); + const err = { data: { soft_logout: soft } }; + return { storage, calls, handler, err }; + }; + + it('soft twice: one begin, no wipe, record kept', async () => { + const { storage, calls, handler, err } = rig(true); + await handler(err); + await handler(err); + expect(calls).toEqual({ stop: 1, wipe: 0, reload: 1, worker: 1 }); + expect(getSoftLogout(storage)).toEqual(record); + expect(storage.getItem('cinny_device_id')).toBe('DEV'); + }); + it('soft then hard: the later event does not wipe', async () => { + const { calls, handler } = rig(true); + await handler({ data: { soft_logout: true } }); + await handler({ data: {} }); + expect(calls.wipe).toBe(0); + }); + it('a record already standing swallows a fresh handler too', async () => { + const { storage, calls, handler } = rig(false); + setSoftLogout(record, storage); + await handler({ data: {} }); + expect(calls).toEqual({ stop: 0, wipe: 0, reload: 0, worker: 0 }); + }); + it('hard twice: one wipe', async () => { + const { calls, handler, err } = rig(false); + await handler(err); + await handler(err); + expect(calls).toEqual({ stop: 1, wipe: 1, reload: 1, worker: 0 }); + }); +}); + +describe('settleLocalData', () => { + const run = async ( + rec: typeof record | undefined, + res: { user_id: string; device_id: string } + ) => { + const s = memoryStorage(); + if (rec) setSoftLogout(rec, s); + let wipes = 0; + const outcome = await settleLocalData( + res, + async () => { + wipes += 1; + }, + s + ); + return { outcome, wipes, left: getSoftLogout(s) }; + }; + it('same user and device: keep stores, retire the record', async () => { + expect(await run(record, { user_id: '@a:hs', device_id: 'DEV' })).toEqual({ + outcome: 'keep', + wipes: 0, + left: undefined, + }); + }); + it('another user or device (a new account too): wipe once, retire the record', async () => { + expect(await run(record, { user_id: '@new:hs', device_id: 'X' })).toEqual({ + outcome: 'wipe', + wipes: 1, + left: undefined, + }); + expect((await run(record, { user_id: '@a:hs', device_id: 'OTHER' })).wipes).toBe(1); + }); + it('no record: plain, no wipe', async () => { + expect((await run(undefined, { user_id: '@a:hs', device_id: 'D' })).wipes).toBe(0); + }); +}); diff --git a/src/app/state/softLogout.ts b/src/app/state/softLogout.ts index d7ea1180..645d0cc3 100644 --- a/src/app/state/softLogout.ts +++ b/src/app/state/softLogout.ts @@ -10,23 +10,15 @@ const ACCESS_TOKEN_KEY = 'cinny_access_token'; export type SoftLogoutRecord = { userId: string; deviceId: string; - baseUrl: string; }; export const getSoftLogout = (storage: Storage = localStorage): SoftLogoutRecord | undefined => { const raw = storage.getItem(SOFT_LOGOUT_KEY); if (!raw) return undefined; try { - const { userId, deviceId, baseUrl } = JSON.parse(raw) as Partial; - if ( - typeof userId === 'string' && - typeof deviceId === 'string' && - typeof baseUrl === 'string' && - userId && - deviceId && - baseUrl - ) { - return { userId, deviceId, baseUrl }; + const { userId, deviceId } = JSON.parse(raw) as Partial; + if (typeof userId === 'string' && typeof deviceId === 'string' && userId && deviceId) { + return { userId, deviceId }; } } catch { // an unreadable record is no record @@ -57,10 +49,7 @@ export const classifyLogout = (err: unknown): LogoutKind => { export const beginSoftLogout = (storage: Storage = localStorage): boolean => { const session = getFallbackSession(storage); if (!session) return false; - setSoftLogout( - { userId: session.userId, deviceId: session.deviceId, baseUrl: session.baseUrl }, - storage - ); + setSoftLogout({ userId: session.userId, deviceId: session.deviceId }, storage); storage.removeItem(ACCESS_TOKEN_KEY); return true; }; @@ -89,3 +78,47 @@ export const decideLoginOutcome = ( }; export const useSoftLogout = (): SoftLogoutRecord | undefined => useState(() => getSoftLogout())[0]; + +export type LogoutHandlerPorts = { + storage: Storage; + stop: () => void; + wipe: () => Promise; + reload: () => void; + forgetSessionInWorker: () => void; +}; + +/** + * The SessionLoggedOut handler. The SDK emits once per failing request and in-flight requests + * outlive stopClient, so the first event decides and every later one is ignored: a second soft + * event must never find the token already gone and fall into the wipe. + */ +export const createLogoutHandler = (ports: LogoutHandlerPorts) => { + let fired = false; + return async (err: unknown): Promise => { + if (fired || getSoftLogout(ports.storage)) return; + fired = true; + ports.stop(); + if (classifyLogout(err) === 'soft') { + if (beginSoftLogout(ports.storage)) ports.forgetSessionInWorker(); + ports.reload(); + return; + } + await ports.wipe(); + ports.reload(); + }; +}; + +/** + * Settle local data when a login or registration hands back a session: wipe first when a soft + * logout left stores that belong to someone else, then retire the record. + */ +export const settleLocalData = async ( + response: { user_id: string; device_id: string }, + wipe: () => Promise, + storage: Storage = localStorage +): Promise => { + const outcome = decideLoginOutcome(getSoftLogout(storage), response); + if (outcome === 'wipe') await wipe(); + clearSoftLogout(storage); + return outcome; +}; diff --git a/src/app/utils/secureUrl.ts b/src/app/utils/secureUrl.ts new file mode 100644 index 00000000..f1dacd9c --- /dev/null +++ b/src/app/utils/secureUrl.ts @@ -0,0 +1,16 @@ +// Plain http is for a developer's own machine only; a stranger's page is https. +const isLocalHost = (hostname: string): boolean => + hostname === 'localhost' || + hostname.endsWith('.localhost') || + hostname === '127.0.0.1' || + hostname === '[::1]'; + +/** True for an https url, or an http url on localhost. Anything else, including non-urls, is false. */ +export const isSecureOrLocalUrl = (value: string): boolean => { + try { + const { protocol, hostname } = new URL(value); + return protocol === 'https:' || (protocol === 'http:' && isLocalHost(hostname)); + } catch { + return false; + } +}; From 31d58075db819a1b3c562829a464ac4d33cc2b9a Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 18:56:08 +0000 Subject: [PATCH 005/177] Second Soul pass: soft event without a session wipes, wipe never rejects, rendered MAS tests wipeLocalData moves to its own module with injectable ports: per-database failures are contained and localStorage clears in a finally. A soft logout with no session to remember is treated as hard. Login/PasswordLoginForm/ResetPassword MAS behavior is now tested by rendering. Login and register completion settle once per response. Co-Authored-By: Claude Sonnet 5.5 --- src/app/pages/auth/authFront.test.tsx | 113 ++++++++++++++++++++ src/app/pages/auth/login/loginUtil.ts | 8 +- src/app/pages/auth/masAccount.test.ts | 37 ------- src/app/pages/auth/register/registerUtil.ts | 8 +- src/app/pages/client/ClientRoot.tsx | 2 +- src/app/state/softLogout.test.ts | 7 ++ src/app/state/softLogout.ts | 5 +- src/client/initMatrix.ts | 40 +------ src/client/wipeLocalData.test.ts | 78 ++++++++++++++ src/client/wipeLocalData.ts | 58 ++++++++++ 10 files changed, 271 insertions(+), 85 deletions(-) create mode 100644 src/app/pages/auth/authFront.test.tsx create mode 100644 src/client/wipeLocalData.test.ts create mode 100644 src/client/wipeLocalData.ts diff --git a/src/app/pages/auth/authFront.test.tsx b/src/app/pages/auth/authFront.test.tsx new file mode 100644 index 00000000..3e6abfd7 --- /dev/null +++ b/src/app/pages/auth/authFront.test.tsx @@ -0,0 +1,113 @@ +import React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { renderToString } from 'react-dom/server'; +import { MemoryRouter } from 'react-router-dom'; +import { AutoDiscoveryInfoProvider } from '../../hooks/useAutoDiscoveryInfo'; +import { AuthServerProvider } from '../../hooks/useAuthServer'; +import { AuthFlowsProvider } from '../../hooks/useAuthFlows'; +import { ClientConfigProvider } from '../../hooks/useClientConfig'; +import type { ClientConfig } from '../../hooks/useClientConfig'; +import type { AutoDiscoveryInfo } from '../../cs-api'; +import { setSoftLogout } from '../../state/softLogout'; +import { Login } from './login/Login'; +import { ResetPassword } from './reset-password/ResetPassword'; + +vi.mock('../../../client/initMatrix', () => ({ clearLoginData: vi.fn() })); +// folds' Overlay portals into document, which the server renderer has none of. +vi.mock('folds', async (importOriginal) => ({ + ...(await importOriginal()), + Overlay: () => null, +})); +vi.mock('./reset-password/PasswordResetForm', () => ({ + PasswordResetForm: () =>
in-client reset form
, +})); + +const plain: AutoDiscoveryInfo = { 'm.homeserver': { base_url: 'https://hs.example' } }; +const mas: AutoDiscoveryInfo = { + ...plain, + 'org.matrix.msc2965.authentication': { account: 'https://auth.example/account' }, +}; +const entryConfig: ClientConfig = { + registration: { enabled: true, url: 'https://accounts.example/join' }, +}; +const flows = { + loginFlows: { flows: [{ type: 'm.login.password' }] }, + registerFlows: { status: 400 }, +} as never; + +const render = (ui: React.ReactElement, info: AutoDiscoveryInfo, config: ClientConfig = {}) => + renderToString( + + + + + {ui} + + + + + ); + +const store = new Map(); +beforeEach(() => { + store.clear(); + vi.stubGlobal('window', { location: { origin: 'https://app.example', search: '' } }); + vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => store.set(k, v), + removeItem: (k: string) => store.delete(k), + }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Login register entries', () => { + it('non-MAS without an entry: the bare Register link, no notice', () => { + const html = render(, plain); + expect(html).toContain('Register'); + expect(html).not.toContain('managed by your sign-in service'); + }); + it('non-MAS with an entry: the entry and its notice', () => { + const html = render(, plain, entryConfig); + expect(html).toContain('href="https://accounts.example/join"'); + }); + it('MAS without an entry: the account page notice, no bare Register link', () => { + const html = render(, mas); + expect(html).toContain('managed by your sign-in service'); + expect(html).toContain('href="https://auth.example/account"'); + expect(html).not.toContain('Register'); + }); + it('MAS with an entry: the entry stays, no MAS notice', () => { + const html = render(, mas, entryConfig); + expect(html).toContain('href="https://accounts.example/join"'); + expect(html).not.toContain('managed by your sign-in service'); + }); +}); + +describe('PasswordLoginForm through Login', () => { + it('shows Forgot Password only without MAS', () => { + expect(render(, plain)).toContain('Forget Password?'); + expect(render(, mas)).not.toContain('Forget Password?'); + }); + it('fixes the username and offers someone else only with a soft record', () => { + expect(render(, plain)).not.toContain('readOnly'); + expect(render(, plain)).not.toContain('Sign in as someone else'); + setSoftLogout({ userId: '@a:hs.example', deviceId: 'DEV' }); + const html = render(, plain); + expect(html).toContain('value="@a:hs.example"'); + expect(html).toMatch(/readonly/i); + expect(html).toContain('Sign in as someone else'); + }); +}); + +describe('ResetPassword', () => { + it('shows the notice under MAS and the form otherwise', () => { + const under = render(, mas); + expect(under).toContain('href="https://auth.example/account"'); + expect(under).not.toContain('in-client reset form'); + const plainHtml = render(, plain); + expect(plainHtml).toContain('in-client reset form'); + expect(plainHtml).not.toContain('managed by your sign-in service'); + }); +}); diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts index 7a9cfb38..d1cfea82 100644 --- a/src/app/pages/auth/login/loginUtil.ts +++ b/src/app/pages/auth/login/loginUtil.ts @@ -1,6 +1,6 @@ import to from 'await-to-js'; import { LoginRequest, LoginResponse, MatrixError, createClient } from 'matrix-js-sdk'; -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { ClientConfig, clientAllowedServer } from '../../../hooks/useClientConfig'; import { autoDiscovery, specVersions } from '../../../cs-api'; @@ -12,7 +12,7 @@ import { import { getHomePath } from '../../pathUtils'; import { setFallbackSession } from '../../../state/sessions'; import { settleLocalData } from '../../../state/softLogout'; -import { wipeLocalData } from '../../../../client/initMatrix'; +import { wipeLocalData } from '../../../../client/wipeLocalData'; export enum GetBaseUrlError { NotAllow = 'NotAllow', @@ -112,9 +112,11 @@ export const login = async ( export const useLoginComplete = (data?: CustomLoginResponse) => { const navigate = useNavigate(); + const settled = useRef(); useEffect(() => { - if (!data) return; + if (!data || settled.current === data) return; + settled.current = data; const { response: loginRes, baseUrl: loginBaseUrl } = data; const finish = async () => { const afterLoginRedirectUrl = getAfterLoginRedirectPath(); diff --git a/src/app/pages/auth/masAccount.test.ts b/src/app/pages/auth/masAccount.test.ts index f2331365..04bd6340 100644 --- a/src/app/pages/auth/masAccount.test.ts +++ b/src/app/pages/auth/masAccount.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest'; -import { readFileSync } from 'fs'; import { masAccountUrl } from './masAccount'; import type { AutoDiscoveryInfo } from '../../cs-api'; @@ -37,39 +36,3 @@ describe('masAccountUrl', () => { expect(masAccountUrl(info({ account: 'ftp://a.example' }))).toBeUndefined(); }); }); - -const src = (p: string) => readFileSync(`${process.cwd()}/src/app/pages/auth/${p}`, 'utf8'); - -describe('MAS front guards', () => { - it('Login keeps a configured register entry, else MAS notice, else the bare link', () => { - const s = src('login/Login.tsx'); - expect(s).toContain('useMasAccountUrl()'); - expect(s).toContain('{registerEntry && }'); - expect(s).toContain('{!registerEntry && masUrl && { - const s = src('login/PasswordLoginForm.tsx'); - expect(s).toContain('useMasAccountUrl()'); - expect(s).toMatch(/\{!masUrl && \([\s\S]*getResetPasswordPath/); - }); - it('RegisterRoute and ResetPassword show the notice under MAS', () => { - ['register/RegisterRoute.tsx', 'reset-password/ResetPassword.tsx'].forEach((p) => { - const s = src(p); - expect(s).toContain('useMasAccountUrl()'); - expect(s).toContain(' { - expect(src('login/PasswordLoginForm.tsx').match(/withDevice\(\{/g)).toHaveLength(3); - expect(src('login/TokenLogin.tsx')).toContain('withSoftLogoutDevice('); - }); - it('the logout listener and login completion defer to the one wipe', () => { - const root = readFileSync(`${process.cwd()}/src/app/pages/client/ClientRoot.tsx`, 'utf8'); - expect(root).toContain('createLogoutHandler('); - expect(root).toContain('wipeLocalData(mx)'); - expect(root).not.toContain('localStorage.clear'); - expect(src('login/loginUtil.ts')).toContain('settleLocalData(loginRes'); - expect(src('register/registerUtil.ts')).toContain('settleLocalData('); - }); -}); diff --git a/src/app/pages/auth/register/registerUtil.ts b/src/app/pages/auth/register/registerUtil.ts index 9d5afa87..dca4dd17 100644 --- a/src/app/pages/auth/register/registerUtil.ts +++ b/src/app/pages/auth/register/registerUtil.ts @@ -6,7 +6,7 @@ import { RegisterRequest, RegisterResponse, } from 'matrix-js-sdk'; -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { LoginPathSearchParams } from '../../paths'; import { ErrorCode } from '../../../cs-errorcode'; @@ -18,7 +18,7 @@ import { getHomePath, getLoginPath, withSearchParam } from '../../pathUtils'; import { getMxIdLocalPart, getMxIdServer } from '../../../utils/matrix'; import { setFallbackSession } from '../../../state/sessions'; import { settleLocalData } from '../../../state/softLogout'; -import { wipeLocalData } from '../../../../client/initMatrix'; +import { wipeLocalData } from '../../../../client/wipeLocalData'; import type { RegisterTrouble } from '../authMessages'; export enum RegisterError { @@ -133,9 +133,11 @@ export const register = async ( export const useRegisterComplete = (data?: CustomRegisterResponse) => { const navigate = useNavigate(); + const settled = useRef(); useEffect(() => { - if (data) { + if (data && settled.current !== data) { + settled.current = data; const { response, baseUrl } = data; const userId = response.user_id; diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 2cb69ed5..ba1876ce 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -19,11 +19,11 @@ import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useState } import { clearCacheAndReload, clearLoginData, - wipeLocalData, initClient, logoutClient, startClient, } from '../../../client/initMatrix'; +import { wipeLocalData } from '../../../client/wipeLocalData'; import { SplashScreen } from '../../components/splash-screen'; import { ServerConfigsLoader } from '../../components/ServerConfigsLoader'; import { CapabilitiesProvider } from '../../hooks/useCapabilities'; diff --git a/src/app/state/softLogout.test.ts b/src/app/state/softLogout.test.ts index 8df1a8f8..2f113dd4 100644 --- a/src/app/state/softLogout.test.ts +++ b/src/app/state/softLogout.test.ts @@ -168,6 +168,13 @@ describe('the logout handler', () => { await handler({ data: {} }); expect(calls).toEqual({ stop: 0, wipe: 0, reload: 0, worker: 0 }); }); + it('soft with no session in storage: one wipe, no record', async () => { + const { storage, calls, handler } = rig(true); + storage.removeItem('cinny_access_token'); + await handler({ data: { soft_logout: true } }); + expect(calls).toEqual({ stop: 1, wipe: 1, reload: 1, worker: 0 }); + expect(getSoftLogout(storage)).toBeUndefined(); + }); it('hard twice: one wipe', async () => { const { calls, handler, err } = rig(false); await handler(err); diff --git a/src/app/state/softLogout.ts b/src/app/state/softLogout.ts index 645d0cc3..bf0c3fd1 100644 --- a/src/app/state/softLogout.ts +++ b/src/app/state/softLogout.ts @@ -98,8 +98,9 @@ export const createLogoutHandler = (ports: LogoutHandlerPorts) => { if (fired || getSoftLogout(ports.storage)) return; fired = true; ports.stop(); - if (classifyLogout(err) === 'soft') { - if (beginSoftLogout(ports.storage)) ports.forgetSessionInWorker(); + // Soft needs a session to remember; without one nothing can vouch for the stores, so wipe. + if (classifyLogout(err) === 'soft' && beginSoftLogout(ports.storage)) { + ports.forgetSessionInWorker(); ports.reload(); return; } diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index b6d22597..a5cc2b35 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -7,6 +7,7 @@ import { SyncState, } from 'matrix-js-sdk'; +import { wipeLocalData } from './wipeLocalData'; import { cryptoCallbacks } from './secretStorageKeys'; import { clearNavToActivePathStore } from '../app/state/navToActivePath'; import { pushSessionToSW } from '../sw-session'; @@ -111,45 +112,6 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { window.location.reload(); }; -// The rust crypto databases the SDK names, for browsers without indexedDB.databases(). -const KNOWN_DATABASES = [ - 'web-sync-store', - 'crypto-store', - 'matrix-js-sdk::matrix-sdk-crypto', - 'matrix-js-sdk::matrix-sdk-crypto-meta', -]; - -const deleteDatabase = (name: string) => - new Promise((resolve) => { - const req = window.indexedDB.deleteDatabase(name); - req.onsuccess = () => resolve(); - req.onerror = () => resolve(); - req.onblocked = () => resolve(); - }); - -/** - * The one wipe of everything this browser holds for the account: client stores, every IndexedDB - * database, localStorage. Hard logout, a soft logout answered by another user or device, and - * "sign in as someone else" all end here. Callers reload afterwards. - */ -export const wipeLocalData = async (mx?: MatrixClient) => { - try { - await mx?.clearStores(); - } catch { - // the databases go below regardless - } - let names: string[]; - try { - names = (await window.indexedDB.databases()) - .map((db) => db.name) - .filter((name): name is string => !!name); - } catch { - names = KNOWN_DATABASES; - } - await Promise.all(names.map(deleteDatabase)); - window.localStorage.clear(); -}; - export const logoutClient = async (mx: MatrixClient) => { pushSessionToSW(); mx.stopClient(); diff --git a/src/client/wipeLocalData.test.ts b/src/client/wipeLocalData.test.ts new file mode 100644 index 00000000..2d3faa0a --- /dev/null +++ b/src/client/wipeLocalData.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; +import { KNOWN_DATABASES, wipeLocalData } from './wipeLocalData'; + +type Mode = 'success' | 'blocked' | 'error' | 'throws'; + +const rig = (opts: { databases?: () => Promise<{ name?: string }[]>; mode?: Mode }) => { + const deleted: string[] = []; + let cleared = 0; + const indexedDB = { + databases: opts.databases, + deleteDatabase: (name: string) => { + deleted.push(name); + if (opts.mode === 'throws') throw new Error('sync boom'); + const req: Record void) | undefined> = {}; + setTimeout(() => { + if (opts.mode === 'blocked') req.onblocked?.(); + else if (opts.mode === 'error') req.onerror?.(); + else req.onsuccess?.(); + }, 0); + return req as unknown as IDBOpenDBRequest; + }, + }; + const storage = { + clear: () => { + cleared += 1; + }, + }; + return { deleted, cleared: () => cleared, ports: { indexedDB, storage } }; +}; + +describe('wipeLocalData', () => { + it('deletes every listed database and clears storage', async () => { + const r = rig({ databases: async () => [{ name: 'a' }, { name: 'b' }, {}] }); + await wipeLocalData(undefined, r.ports); + expect(r.deleted).toEqual(['a', 'b']); + expect(r.cleared()).toBe(1); + }); + it('falls back to the known names when databases() is absent or throws', async () => { + const absent = rig({}); + await wipeLocalData(undefined, absent.ports); + expect(absent.deleted).toEqual(KNOWN_DATABASES); + expect(absent.cleared()).toBe(1); + const throws = rig({ + databases: async () => { + throw new Error('nope'); + }, + }); + await wipeLocalData(undefined, throws.ports); + expect(throws.deleted).toEqual(KNOWN_DATABASES); + expect(throws.cleared()).toBe(1); + }); + it('a synchronous deleteDatabase throw does not abort the rest or the storage clear', async () => { + const r = rig({ databases: async () => [{ name: 'a' }, { name: 'b' }], mode: 'throws' }); + await expect(wipeLocalData(undefined, r.ports)).resolves.toBeUndefined(); + expect(r.deleted).toEqual(['a', 'b']); + expect(r.cleared()).toBe(1); + }); + it('blocked and errored deletions settle and still clear storage', async () => { + await Promise.all( + (['blocked', 'error'] as const).map(async (mode) => { + const r = rig({ databases: async () => [{ name: 'a' }], mode }); + await wipeLocalData(undefined, r.ports); + expect(r.cleared()).toBe(1); + }) + ); + }); + it('a throwing clearStores does not stop the wipe', async () => { + const r = rig({ databases: async () => [{ name: 'a' }] }); + const mx = { + clearStores: async () => { + throw new Error('x'); + }, + }; + await wipeLocalData(mx as never, r.ports); + expect(r.deleted).toEqual(['a']); + expect(r.cleared()).toBe(1); + }); +}); diff --git a/src/client/wipeLocalData.ts b/src/client/wipeLocalData.ts new file mode 100644 index 00000000..dc24951c --- /dev/null +++ b/src/client/wipeLocalData.ts @@ -0,0 +1,58 @@ +import type { MatrixClient } from 'matrix-js-sdk'; + +// The rust crypto databases the SDK names, for browsers without indexedDB.databases(). +export const KNOWN_DATABASES = [ + 'web-sync-store', + 'crypto-store', + 'matrix-js-sdk::matrix-sdk-crypto', + 'matrix-js-sdk::matrix-sdk-crypto-meta', +]; + +export type WipePorts = { + indexedDB: Pick & { + databases?: () => Promise<{ name?: string }[]>; + }; + storage: Pick; +}; + +const deleteDatabase = (idb: WipePorts['indexedDB'], name: string) => + new Promise((resolve) => { + try { + const req = idb.deleteDatabase(name); + req.onsuccess = () => resolve(); + req.onerror = () => resolve(); + req.onblocked = () => resolve(); + } catch { + // one database failing must not stop the rest + resolve(); + } + }); + +/** + * The one wipe of everything this browser holds for the account: client stores, every IndexedDB + * database, localStorage. Hard logout, a soft logout answered by another user or device, and + * "sign in as someone else" all end here. It never rejects, and localStorage (the access token + * with it) is cleared whatever the databases do. Callers reload afterwards. + */ +export const wipeLocalData = async ( + mx?: MatrixClient, + ports: WipePorts = { indexedDB: window.indexedDB, storage: window.localStorage } +): Promise => { + try { + try { + await mx?.clearStores(); + } catch { + // the databases go below regardless + } + let names = KNOWN_DATABASES; + try { + const listed = await ports.indexedDB.databases?.(); + if (listed) names = listed.map((db) => db.name).filter((n): n is string => !!n); + } catch { + // keep the known names + } + await Promise.all(names.map((name) => deleteDatabase(ports.indexedDB, name))); + } finally { + ports.storage.clear(); + } +}; From 8fb95402f59a87b60176e66e395e279b4b1a2994 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 19:13:04 +0000 Subject: [PATCH 006/177] wipeLocalData: bounded clearStores, storage clear that cannot reject; tests that bite Co-Authored-By: Claude Sonnet 5.5 --- src/app/pages/auth/authFront.test.tsx | 2 +- src/client/wipeLocalData.test.ts | 25 +++++++++++++++++++++++++ src/client/wipeLocalData.ts | 20 +++++++++++++++++--- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/app/pages/auth/authFront.test.tsx b/src/app/pages/auth/authFront.test.tsx index 3e6abfd7..df15bbd5 100644 --- a/src/app/pages/auth/authFront.test.tsx +++ b/src/app/pages/auth/authFront.test.tsx @@ -91,7 +91,7 @@ describe('PasswordLoginForm through Login', () => { expect(render(, mas)).not.toContain('Forget Password?'); }); it('fixes the username and offers someone else only with a soft record', () => { - expect(render(, plain)).not.toContain('readOnly'); + expect(render(, plain)).not.toMatch(/readonly/i); expect(render(, plain)).not.toContain('Sign in as someone else'); setSoftLogout({ userId: '@a:hs.example', deviceId: 'DEV' }); const html = render(, plain); diff --git a/src/client/wipeLocalData.test.ts b/src/client/wipeLocalData.test.ts index 2d3faa0a..1cff5f16 100644 --- a/src/client/wipeLocalData.test.ts +++ b/src/client/wipeLocalData.test.ts @@ -39,6 +39,12 @@ describe('wipeLocalData', () => { const absent = rig({}); await wipeLocalData(undefined, absent.ports); expect(absent.deleted).toEqual(KNOWN_DATABASES); + expect(KNOWN_DATABASES).toEqual([ + 'web-sync-store', + 'crypto-store', + 'matrix-js-sdk::matrix-sdk-crypto', + 'matrix-js-sdk::matrix-sdk-crypto-meta', + ]); expect(absent.cleared()).toBe(1); const throws = rig({ databases: async () => { @@ -75,4 +81,23 @@ describe('wipeLocalData', () => { expect(r.deleted).toEqual(['a']); expect(r.cleared()).toBe(1); }); + it('a storage that refuses to clear does not make the wipe reject', async () => { + const r = rig({ databases: async () => [] }); + const ports = { + ...r.ports, + storage: { + clear: () => { + throw new Error('SecurityError'); + }, + }, + }; + await expect(wipeLocalData(undefined, ports)).resolves.toBeUndefined(); + }); + it('a client store that never closes holds the wipe only for the timeout, then storage is cleared', async () => { + const r = rig({ databases: async () => [{ name: 'a' }] }); + const mx = { clearStores: () => new Promise(() => undefined) } as never; + await wipeLocalData(mx, { ...r.ports, clearStoresTimeoutMs: 10 }); + expect(r.deleted).toEqual(['a']); + expect(r.cleared()).toBe(1); + }); }); diff --git a/src/client/wipeLocalData.ts b/src/client/wipeLocalData.ts index dc24951c..d0a2da86 100644 --- a/src/client/wipeLocalData.ts +++ b/src/client/wipeLocalData.ts @@ -13,8 +13,12 @@ export type WipePorts = { databases?: () => Promise<{ name?: string }[]>; }; storage: Pick; + /** How long a client store that will not close may hold the wipe up. */ + clearStoresTimeoutMs?: number; }; +const CLEAR_STORES_TIMEOUT_MS = 5000; + const deleteDatabase = (idb: WipePorts['indexedDB'], name: string) => new Promise((resolve) => { try { @@ -32,7 +36,8 @@ const deleteDatabase = (idb: WipePorts['indexedDB'], name: string) => * The one wipe of everything this browser holds for the account: client stores, every IndexedDB * database, localStorage. Hard logout, a soft logout answered by another user or device, and * "sign in as someone else" all end here. It never rejects, and localStorage (the access token - * with it) is cleared whatever the databases do. Callers reload afterwards. + * with it) is cleared whatever the databases do; a client store that hangs is given + * `clearStoresTimeoutMs`, then the wipe goes on. Callers reload afterwards. */ export const wipeLocalData = async ( mx?: MatrixClient, @@ -40,7 +45,12 @@ export const wipeLocalData = async ( ): Promise => { try { try { - await mx?.clearStores(); + await Promise.race([ + mx?.clearStores(), + new Promise((resolve) => { + setTimeout(resolve, ports.clearStoresTimeoutMs ?? CLEAR_STORES_TIMEOUT_MS); + }), + ]); } catch { // the databases go below regardless } @@ -53,6 +63,10 @@ export const wipeLocalData = async ( } await Promise.all(names.map((name) => deleteDatabase(ports.indexedDB, name))); } finally { - ports.storage.clear(); + try { + ports.storage.clear(); + } catch { + // storage that refuses to clear cannot be helped; the reload still has to follow + } } }; From cd30c3dc40e6bc56616297a63ef2a13fc93504ad Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 19:13:14 +0000 Subject: [PATCH 007/177] wipeLocalData test: lint-clean never-settling store Co-Authored-By: Claude Sonnet 5.5 --- src/client/wipeLocalData.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/client/wipeLocalData.test.ts b/src/client/wipeLocalData.test.ts index 1cff5f16..82c835de 100644 --- a/src/client/wipeLocalData.test.ts +++ b/src/client/wipeLocalData.test.ts @@ -95,7 +95,12 @@ describe('wipeLocalData', () => { }); it('a client store that never closes holds the wipe only for the timeout, then storage is cleared', async () => { const r = rig({ databases: async () => [{ name: 'a' }] }); - const mx = { clearStores: () => new Promise(() => undefined) } as never; + const mx = { + clearStores: () => + new Promise(() => { + // never settles + }), + } as never; await wipeLocalData(mx, { ...r.ports, clearStoresTimeoutMs: 10 }); expect(r.deleted).toEqual(['a']); expect(r.cleared()).toBe(1); From 53a724ae27278c628a428a85cb7dfa98a6db8a2c Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 21:45:00 +0000 Subject: [PATCH 008/177] Files desk cut 1 under Matrix authority: folders by album title path, share into the current folder Albums titled a/b/c group into folders in AlbumView; ShareSet prefixes the current folder onto the album title it sends. No wire change. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/albums/AlbumView.tsx | 60 +++++++-- src/app/features/albums/ShareSet.tsx | 10 +- src/app/features/albums/albumFolders.test.ts | 129 +++++++++++++++++++ src/app/features/albums/albumFolders.ts | 73 +++++++++++ 4 files changed, 257 insertions(+), 15 deletions(-) create mode 100644 src/app/features/albums/albumFolders.test.ts create mode 100644 src/app/features/albums/albumFolders.ts diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx index b670ee2b..20c1e27c 100644 --- a/src/app/features/albums/AlbumView.tsx +++ b/src/app/features/albums/AlbumView.tsx @@ -15,6 +15,7 @@ import { getBlobSafeMimeType } from '../../utils/mimeTypes'; import { timeDayMonYear } from '../../utils/time'; import { getMemberDisplayName } from '../../utils/room'; import { Album, AlbumFile } from './buildAlbums'; +import { folderOf, listFolder, pathLabel } from './albumFolders'; import { FileReadBy } from './FileReadBy'; import { ShareSet, useShareEnabled } from './ShareSet'; import { useAlbums } from './useAlbums'; @@ -91,6 +92,7 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { const { loading, error, albums } = useAlbums(room); const [dateFormat] = useSetting(settingsAtom, 'dateFormatString'); const [openId, setOpenId] = useState(); + const [path, setPath] = useState([]); const open: Album | undefined = albums.find((a) => a.id === openId); const authorOf = (a: Album) => getMemberDisplayName(room, a.author) ?? a.author; const encrypted = room.hasEncryptionStateEvent(); @@ -103,8 +105,17 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { const images = open.files.length > 0 && open.files.every((f) => f.kind === 'image'); body = ( <> - {open.title} @@ -122,14 +133,41 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { body = This zone is encrypted, so its albums cannot be listed here.; else if (albums.length === 0) body = No albums yet.; else { - body = albums.map((a) => ( - - )); + const here = listFolder(albums, path); + body = ( + <> + {path.length > 0 && ( + + )} + {path.length > 0 && {pathLabel(path)}} + {here.folders.map((f) => ( + + ))} + {here.albums.map(({ album: a, leaf }) => ( + + ))} + {here.folders.length === 0 && here.albums.length === 0 && Nothing here.} + + ); } return ( @@ -139,7 +177,7 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { {/* Stays mounted while an album is open, so a running send keeps its progress. */} {canShare && ( )} ))} {here.folders.length === 0 && here.albums.length === 0 && Nothing here.} + {truncated && ( + + The list is cut short: older albums are not loaded. + + )} ); } diff --git a/src/app/features/albums/ShareSet.folder.test.tsx b/src/app/features/albums/ShareSet.folder.test.tsx new file mode 100644 index 00000000..7f23fd63 --- /dev/null +++ b/src/app/features/albums/ShareSet.folder.test.tsx @@ -0,0 +1,85 @@ +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { MatrixClientProvider } from '../../hooks/useMatrixClient'; + +// ShareSet hands its folder to the title the send lands under. The controller is held still and its +// `run` captured, and sendShareSet records the title it was given, so the path from the `folder` +// prop to the album root's title is read without a homeserver or a DOM. +const captured = vi.hoisted(() => ({ + run: undefined as undefined | ((files: unknown[], title: string, onFile: () => void) => unknown), + titles: [] as string[], +})); + +vi.mock('./shareController', () => ({ + createShareController: (deps: { run: NonNullable }) => { + captured.run = deps.run; + return { + subscribe: () => () => undefined, + getState: () => ({ files: [], title: '', phase: { kind: 'idle' }, epoch: 0 }), + pick: () => undefined, + setTitle: () => undefined, + send: () => undefined, + cancel: () => undefined, + }; + }, +})); +vi.mock('./shareSet', async (importOriginal) => ({ + ...(await importOriginal()), + sendShareSet: async (_port: unknown, title: string) => { + captured.titles.push(title); + return { albumId: '$a', sent: 0, failed: [], failedAt: [] }; + }, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + // The server renderer has no snapshot for an external store; read the client one. + const useSyncExternalStore = (_sub: unknown, get: () => unknown) => get(); + return { ...actual, default: { ...actual, useSyncExternalStore }, useSyncExternalStore }; +}); + +// eslint-disable-next-line import/first +import { ShareSet } from './ShareSet'; + +const mount = (folder?: string[]) => { + const room = { roomId: '!r:x', hasEncryptionStateEvent: () => false } as never; + renderToStaticMarkup( + + ({ event_id: '$e' }) } as never}> + + + + ); +}; +const send = async (typed: string) => { + await captured.run?.([], typed, () => undefined); + return captured.titles.at(-1); +}; + +describe('ShareSet: the folder reaches the album title', () => { + beforeEach(() => { + captured.run = undefined; + captured.titles.length = 0; + }); + + it('at the top, the typed title goes as typed', async () => { + mount(); + expect(await send('Poses')).toBe('Poses'); + }); + + it('inside a folder, the path prefixes the typed title', async () => { + mount(['cast-art', 'poses']); + expect(await send('Set 2')).toBe('cast-art/poses/Set 2'); + }); + + it('an empty typed title falls back to the default, still under the folder', async () => { + mount(['handoff']); + expect(await send(' ')).toBe('handoff/Shared files'); + }); + + it('a typed title containing a slash goes deeper', async () => { + mount(['a']); + expect(await send('b/c')).toBe('a/b/c'); + }); +}); diff --git a/src/app/features/albums/readPages.test.ts b/src/app/features/albums/readPages.test.ts new file mode 100644 index 00000000..124a32a6 --- /dev/null +++ b/src/app/features/albums/readPages.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import { Page, readPages } from './readPages'; + +const pager = (pages: Page[]) => { + const froms: (string | undefined)[] = []; + return { + froms, + fetchPage: async (from: string | undefined) => { + froms.push(from); + return pages[froms.length - 1] ?? {}; + }, + }; +}; + +describe('readPages', () => { + it('one page without a token is the whole read', async () => { + const p = pager([{ chunk: [1, 2] }]); + expect(await readPages(p.fetchPage)).toEqual({ items: [1, 2], truncated: false }); + expect(p.froms).toEqual([undefined]); + }); + + it('follows next_batch in order, passing each token back', async () => { + const p = pager([ + { chunk: [1], next_batch: 'a' }, + { chunk: [2], next_batch: 'b' }, + { chunk: [3] }, + ]); + expect(await readPages(p.fetchPage)).toEqual({ items: [1, 2, 3], truncated: false }); + expect(p.froms).toEqual([undefined, 'a', 'b']); + }); + + it('a missing chunk reads as empty', async () => { + expect(await readPages(async () => ({}))).toEqual({ items: [], truncated: false }); + }); + + it('an empty page ends the read even when it carries a token', async () => { + const p = pager([ + { chunk: [1], next_batch: 'a' }, + { chunk: [], next_batch: 'b' }, + ]); + expect(await readPages(p.fetchPage)).toEqual({ items: [1], truncated: false }); + expect(p.froms).toHaveLength(2); + }); + + it('the cap stops the read and says it was cut short', async () => { + const p = pager(Array.from({ length: 10 }, (_, i) => ({ chunk: [i], next_batch: `t${i}` }))); + expect(await readPages(p.fetchPage, 3)).toEqual({ items: [0, 1, 2], truncated: true }); + expect(p.froms).toHaveLength(3); + }); + + it('a last page exactly at the cap is not truncated', async () => { + const p = pager([{ chunk: [1], next_batch: 'a' }, { chunk: [2] }]); + expect((await readPages(p.fetchPage, 2)).truncated).toBe(false); + }); +}); diff --git a/src/app/features/albums/readPages.ts b/src/app/features/albums/readPages.ts new file mode 100644 index 00000000..a2b888e5 --- /dev/null +++ b/src/app/features/albums/readPages.ts @@ -0,0 +1,27 @@ +/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */ +export type Page = { chunk?: T[]; next_batch?: string }; + +/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */ +export const MAX_PAGES = 20; + +/** + * Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true + * when the cap stopped the read with more still to come, so a caller can say the list is partial. + */ +export const readPages = async ( + fetchPage: (from: string | undefined) => Promise>, + maxPages = MAX_PAGES +): Promise<{ items: T[]; truncated: boolean }> => { + const items: T[] = []; + let from: string | undefined; + for (let n = 0; n < maxPages; n += 1) { + // eslint-disable-next-line no-await-in-loop + const page = await fetchPage(from); + items.push(...(page.chunk ?? [])); + // An empty page ends the read even if a token is returned: a server that keeps handing out + // tokens with nothing behind them would otherwise spend every page of the cap. + if (!page.next_batch || !page.chunk?.length) return { items, truncated: false }; + from = page.next_batch; + } + return { items, truncated: true }; +}; diff --git a/src/app/features/albums/useAlbums.ts b/src/app/features/albums/useAlbums.ts index 7c1d5a57..13c199ec 100644 --- a/src/app/features/albums/useAlbums.ts +++ b/src/app/features/albums/useAlbums.ts @@ -7,12 +7,11 @@ import { useClientConfig } from '../../hooks/useClientConfig'; import { Album, ZoneEvent, buildAlbums } from './buildAlbums'; import { isFileZone } from './isFileZone'; import { mapLimit } from './mapLimit'; +import { Page, readPages } from './readPages'; const REPLY_FETCHES_IN_FLIGHT = 6; const REFRESH_MS = 30_000; -type Chunk = { chunk?: ZoneEvent[] }; - /** True when the room is the file zone: by its create type, or listed in the client config. */ export const useIsFileZone = (room: Room): boolean => { const config = useClientConfig(); @@ -29,37 +28,49 @@ export const useIsFileZone = (room: Room): boolean => { ); }; -export type AlbumsState = { loading: boolean; error: Error | null; albums: Album[] }; +export type AlbumsState = { + loading: boolean; + error: Error | null; + albums: Album[]; + /** A read hit the page cap (readPages), so older albums or files are not in the list. */ + truncated: boolean; +}; + +const PAGE_LIMIT = '100'; /** - * Slice 1 reads ONE page of each endpoint (threads: 100 roots; replies per root: 100). A zone with - * more albums or files than that is truncated; pagination is a later slice. Reads are made with - * the logged-in client, so the room must be unencrypted: encrypted events carry no msgtype and - * are skipped. + * Reads every page of the zone's threads, then every page of each thread's replies, each capped at + * MAX_PAGES (readPages). Reads are made with the logged-in client, so the room must be + * unencrypted: encrypted events carry no msgtype and are skipped. */ export const useAlbums = (room: Room): AlbumsState => { const mx = useMatrixClient(); const { roomId } = room; const query = useQuery({ queryKey: ['albums', roomId], - queryFn: async (): Promise => { + queryFn: async (): Promise<{ albums: Album[]; truncated: boolean }> => { const get = (path: string, params: Record) => - mx.http.authedRequest(Method.Get, path, params, undefined, { + mx.http.authedRequest>(Method.Get, path, params, undefined, { prefix: ClientPrefix.V1, }); + const paged = (path: string, params: Record) => + readPages((from) => get(path, from ? { ...params, from } : params)); const room_ = encodeURIComponent(roomId); - const roots = (await get(`/rooms/${room_}/threads`, { limit: '100' })).chunk ?? []; - const inputs = await mapLimit(roots, REPLY_FETCHES_IN_FLIGHT, async (root: ZoneEvent) => ({ - root, - replies: - ( - await get( - `/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`, - { limit: '100', dir: 'f' } - ) - ).chunk ?? [], - })); - return buildAlbums(inputs, mx.getDomain() ?? ''); + const roots = await paged(`/rooms/${room_}/threads`, { limit: PAGE_LIMIT }); + let { truncated } = roots; + const inputs = await mapLimit( + roots.items, + REPLY_FETCHES_IN_FLIGHT, + async (root: ZoneEvent) => { + const replies = await paged( + `/rooms/${room_}/relations/${encodeURIComponent(root.event_id ?? '')}/m.thread`, + { limit: PAGE_LIMIT, dir: 'f' } + ); + truncated = truncated || replies.truncated; + return { root, replies: replies.items }; + } + ); + return { albums: buildAlbums(inputs, mx.getDomain() ?? ''), truncated }; }, retry: 1, refetchInterval: REFRESH_MS, @@ -68,6 +79,7 @@ export const useAlbums = (room: Room): AlbumsState => { loading: query.isLoading, // A failed refetch keeps the albums already loaded; the error shows only when there are none. error: query.data ? null : (query.error as Error | null), - albums: query.data ?? [], + albums: query.data?.albums ?? [], + truncated: query.data?.truncated ?? false, }; }; From 6aaee8badd8dc40a6801775ccb48bc86653652f0 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 22:59:33 +0000 Subject: [PATCH 011/177] Cut 2: doc names the page cap; truncation note says albums or files Co-Authored-By: Claude Sonnet 5.5 --- docs/commons-files-desk.md | 6 +++--- src/app/features/albums/AlbumView.tsx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index 0018a432..98696766 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -21,7 +21,7 @@ Read from this repo at dev `8ba407cd`: - **Zone = a room** whose `m.room.create` type is `org.gamecult.file_zone` (`isFileZone.ts`), or one listed in config `fileZoneRooms`. One per Mind, `#-files:`, found by alias or by the carried id in the root Space's `org.gamecult.stewardships` (`mediaRoom.ts`, `MediaRow.tsx`); rendered as the Media row of each Mind's group. - **Album = a thread root** (a text event; its `body`, or its latest `m.replace` edit, is the title); **file = a thread reply** with `msgtype` `m.audio|m.image|m.video|m.file` (`buildAlbums.ts`). A redacted event or an `m.replace` is never a file. Loose room messages are not shown. -- **Read** = `GET /rooms/{id}/threads` and `/relations/{root}/m.thread`, one page of 100 each (`useAlbums.ts`; pagination is a known gap). Unencrypted rooms only. +- **Read** = `GET /rooms/{id}/threads` and `/relations/{root}/m.thread`, every page, 100 per request, at most 20 pages per endpoint (`useAlbums.ts`, `readPages.ts`; a capped read shows a note in the list). Unencrypted rooms only. - **Write** = `sendShareSet` (`shareSet.ts`, behind `fileZoneShare.enabled`): a root, then one thread reply per file, content from `getMsgContent` with `info.sha256`. - **Media** = authenticated Matrix media fetched to a blob (`downloadMedia` in `FileContent.tsx`): so the "media element cannot send a header" problem that Option B needed a ticket for is already solved this way, at the cost that a file is fully downloaded before it plays. - **Receipts** = `org.gamecult.file_received` from a Mind's mouth after it fetches and verifies the sha256 (`docs/file-zone-mind-contract.md`); the mouth enforces the Mind's membership in the room. @@ -103,7 +103,7 @@ What A adds to `ShareSet`: sharing into an existing album ("add files", listed a Under both, the phone design is the same shape (one column, rows 56 px or more, hidden controls, in-place preview; see the Option B sections below, which are written against the host but whose layout applies). -- **A, new cost:** the Commons room is one more room in sync and it must be muted; albums and files are one page of 100 each until pagination exists (a Commons of hundreds of documents needs it first); a folder tree is a title-path grouping, so a deep tree is a long list of albums with breadcrumbs, not true directories; a file plays after a full download (small audio and images are fine; a 40 MB clip is not). +- **A, new cost:** the Commons room is one more room in sync and it must be muted; albums and files are read to a cap of 20 pages of 100 per endpoint (a Commons past that shows a truncation note); a folder tree is a title-path grouping, so a deep tree is a long list of albums with breadcrumbs, not true directories; a file plays after a full download (small audio and images are fine; a 40 MB clip is not). - **A, no cost:** no second sign-in, no ticket, no CORS, no new fetch layer, no host-unreachable state beyond the homeserver's own. The album list, album view, share panel and receipts exist and are tested; the view is their extension. - **B, new cost:** every screen is a second client against a second service with its own errors, token refresh and unreachable state; media needs the ticket or the blob; the tree and preview are new UI. - **B, benefit:** a tree that is live and complete, ranges, and no Matrix size limit. @@ -121,7 +121,7 @@ Under A the paused service is not built, and most of its list disappears: Status 2026-11-13: cut 1 merged to dev as bb615570 (PR #147); cuts 2-5 follow. Cut 1's shape was: a pure `albumFolders` view (folders from `/`-separated album titles, leaf name, counts), folder navigation and breadcrumb in `AlbumView` through a presentational list component tested by static render, `ShareSet` sending into the current folder by prefixing the album title, and a quiet `Commons` row (alias `#commons:gamecult.org` or the carried `media.commons` id, through `lookupMediaRoom`, hidden while unset or looking, behind a dark `filesDesk.enabled` flag, and filtered out of the tiers so it is not listed twice). Muting is provisioning's (Q-E3), not the client's. 1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias or carried id), opening the room's album view. Flagged, no new data layer. -2. **Pagination** of albums and files in `useAlbums` (a prerequisite for a Commons of any size). +2. **Pagination** of albums and files in `useAlbums` (done, PR #148). 3. **Folders by title path** and the album list grouped by it. 4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it. 5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx index dbb9f8e0..73e63e7c 100644 --- a/src/app/features/albums/AlbumView.tsx +++ b/src/app/features/albums/AlbumView.tsx @@ -168,7 +168,7 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { {here.folders.length === 0 && here.albums.length === 0 && Nothing here.} {truncated && ( - The list is cut short: older albums are not loaded. + The list is cut short: some albums or files are not loaded. )} From ac6018b57cc635c9ef203f32d1d39723c15802fc Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 22:59:10 +0000 Subject: [PATCH 012/177] Files desk cut 3: show the latest version of a file chain, earlier versions folded under it A file event naming org.gamecult.publish.replaces supersedes the event it names. foldVersions reads the chain from the events alone; buildAlbums lists heads (count too) and AlbumView unfolds 'N earlier versions'. Both events stay ordinary files for other clients. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/albums/AlbumView.tsx | 22 ++++++- src/app/features/albums/buildAlbums.test.ts | 14 +++++ src/app/features/albums/buildAlbums.ts | 11 +++- src/app/features/albums/versions.test.ts | 65 +++++++++++++++++++++ src/app/features/albums/versions.ts | 46 +++++++++++++++ 5 files changed, 154 insertions(+), 4 deletions(-) create mode 100644 src/app/features/albums/versions.test.ts create mode 100644 src/app/features/albums/versions.ts diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx index 73e63e7c..944cc761 100644 --- a/src/app/features/albums/AlbumView.tsx +++ b/src/app/features/albums/AlbumView.tsx @@ -68,6 +68,26 @@ function FileRow({ room, file, author }: FileRowProps) { ); } +/** A file, and under it a row that unfolds the versions it supersedes. */ +function VersionedFileRow({ room, file, author }: FileRowProps) { + const [shown, setShown] = useState(false); + const n = file.earlier.length; + return ( + <> + + {n > 0 && ( + + )} + {shown && + file.earlier.map((e) => )} + + ); +} + const countLabel = (n: number) => `${n} ${n === 1 ? 'file' : 'files'}`; /** The zone never mounts RoomTimeline, so it sends the read receipt the timeline would. */ @@ -124,7 +144,7 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { {open.count === 0 && This album has no files.}
{open.files.map((f) => ( - + ))}
diff --git a/src/app/features/albums/buildAlbums.test.ts b/src/app/features/albums/buildAlbums.test.ts index e98e4f51..d8d8ed9f 100644 --- a/src/app/features/albums/buildAlbums.test.ts +++ b/src/app/features/albums/buildAlbums.test.ts @@ -215,6 +215,20 @@ describe('buildAlbums', () => { }); }); +describe('versions', () => { + const v = (id: string, ts: number, replaces?: string) => + reply(id, ts, 'm.file', id, replaces ? { 'org.gamecult.publish': { replaces } } : {}); + + it('lists the latest of a chain and folds the earlier versions under it', () => { + const a = one(root('$r', 1), [v('$v1', 10), v('$v2', 20, '$v1'), reply('$x', 30, 'm.file')]); + expect(a.files.map((f) => [f.id, f.earlier.map((e) => e.id)])).toEqual([ + ['$v2', ['$v1']], + ['$x', []], + ]); + expect(a.count).toBe(2); + }); +}); + describe('Mind receipts', () => { const HASH = 'a'.repeat(64); const file = (id: string, sha?: string) => diff --git a/src/app/features/albums/buildAlbums.ts b/src/app/features/albums/buildAlbums.ts index 6fe8a452..69fe82b4 100644 --- a/src/app/features/albums/buildAlbums.ts +++ b/src/app/features/albums/buildAlbums.ts @@ -3,6 +3,7 @@ // into albums. See docs/file-zone.md for the rulings this encodes. import { readersOf } from './fileReceipt'; import type { FileReader } from './fileReceipt'; +import { foldVersions } from './versions'; /** The slice of a Matrix event this module reads. Every field may be missing. */ export type ZoneEvent = { @@ -27,6 +28,8 @@ export type AlbumFile = { content: Record; /** Receipts in this album that name this file, one per sender (the latest), oldest first. */ readBy: FileReader[]; + /** The versions this file supersedes, nearest first (`org.gamecult.publish.replaces`). */ + earlier: AlbumFile[]; }; export type Album = { @@ -75,6 +78,7 @@ const toFile = (e: ZoneEvent): AlbumFile | undefined => { ts: tsOf(e.origin_server_ts), content: e.content, readBy: [], + earlier: [], }; }; @@ -103,14 +107,15 @@ const toAlbum = (input: AlbumInput, server: string): Album | undefined => { }) .sort((a, b) => a.ts - b.ts) .map((f) => ({ ...f, readBy: readersOf(list, f.id, f.content, server) })); + const heads = foldVersions(files); return { id: root.event_id, title: titleOf(root), author: root.sender ?? '', ts: tsOf(root.origin_server_ts), - cover: files.find((f) => f.kind === 'image'), - files, - count: files.length, + cover: heads.find((f) => f.kind === 'image'), + files: heads, + count: heads.length, }; }; diff --git a/src/app/features/albums/versions.test.ts b/src/app/features/albums/versions.test.ts new file mode 100644 index 00000000..645f409d --- /dev/null +++ b/src/app/features/albums/versions.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest'; +import { PUBLISH_KEY, foldVersions, replacesOf } from './versions'; + +type F = { id: string; content: Record; earlier: F[] }; +const f = (id: string, replaces?: string): F => ({ + id, + content: replaces ? { [PUBLISH_KEY]: { replaces } } : {}, + earlier: [], +}); +const shape = (files: F[]): unknown => files.map((x) => [x.id, x.earlier.map((e) => e.id)]); + +describe('replacesOf', () => { + it('reads the id the publisher key names', () => { + expect(replacesOf({ [PUBLISH_KEY]: { replaces: '$a' } })).toBe('$a'); + }); + it('anything else says nothing', () => { + expect(replacesOf({})).toBeUndefined(); + expect(replacesOf({ [PUBLISH_KEY]: {} })).toBeUndefined(); + expect(replacesOf({ [PUBLISH_KEY]: { replaces: 3 } })).toBeUndefined(); + expect(replacesOf({ [PUBLISH_KEY]: { replaces: '' } })).toBeUndefined(); + expect(replacesOf({ [PUBLISH_KEY]: 'x' })).toBeUndefined(); + }); +}); + +describe('foldVersions', () => { + it('files that replace nothing pass through in order, with nothing folded', () => { + expect(shape(foldVersions([f('$a'), f('$b')]))).toEqual([ + ['$a', []], + ['$b', []], + ]); + }); + + it('shows the latest of a chain with earlier versions nearest first', () => { + expect(shape(foldVersions([f('$a'), f('$b', '$a'), f('$c', '$b')]))).toEqual([ + ['$c', ['$b', '$a']], + ]); + }); + + it('keeps unrelated files beside a chain, in order', () => { + expect(shape(foldVersions([f('$a'), f('$x'), f('$b', '$a')]))).toEqual([ + ['$x', []], + ['$b', ['$a']], + ]); + }); + + it('a replacement whose target is not in the list stands alone', () => { + expect(shape(foldVersions([f('$b', '$gone')]))).toEqual([['$b', []]]); + }); + + it('a file two others replace sits under both', () => { + expect(shape(foldVersions([f('$a'), f('$b', '$a'), f('$c', '$a')]))).toEqual([ + ['$b', ['$a']], + ['$c', ['$a']], + ]); + }); + + it('a malformed loop shows no head and does not hang', () => { + const out = foldVersions([f('$a', '$b'), f('$b', '$a'), f('$s', '$s')]); + expect(out.map((x) => x.id)).toEqual(['$s']); + }); + + it('an empty list is empty', () => { + expect(foldVersions([])).toEqual([]); + }); +}); diff --git a/src/app/features/albums/versions.ts b/src/app/features/albums/versions.ts new file mode 100644 index 00000000..f38af62b --- /dev/null +++ b/src/app/features/albums/versions.ts @@ -0,0 +1,46 @@ +// Pure: a file event may name the event it supersedes in `org.gamecult.publish.replaces` (the +// publisher writes it on a later final version; docs/commons-files-desk.md, "replaces, not +// m.replace"). Both events stay ordinary files for every other client; this view shows the latest +// of a chain with the earlier ones folded under it. A chain is read from the events alone. + +/** Key the publisher writes its provenance under. */ +export const PUBLISH_KEY = 'org.gamecult.publish'; + +/** The event id a file says it replaces, if it says one. */ +export const replacesOf = (content: Record): string | undefined => { + const id = (content[PUBLISH_KEY] as { replaces?: unknown } | undefined)?.replaces; + return typeof id === 'string' && id ? id : undefined; +}; + +type Versioned = F & { earlier: F[] }; + +/** + * Files not replaced by another file in the list, oldest first as given, each carrying the files it + * supersedes (nearest first) in `earlier`. A replacement whose target is missing from the list (a + * redacted event, another thread) replaces nothing and stands as a head. A file two others claim to + * replace sits under both. The walk refuses to revisit a file, so a malformed chain cannot loop (an event id hashes its content, so a real one cannot cycle). + */ +export const foldVersions = }>( + files: Versioned[] +): Versioned[] => { + const byId = new Map(files.map((f) => [f.id, f])); + const target = (f: F): F | undefined => { + const id = replacesOf(f.content); + return id && id !== f.id ? byId.get(id) : undefined; + }; + const replaced = new Set(); + files.forEach((f) => { + const t = target(f); + if (t) replaced.add(t.id); + }); + const chainOf = (head: Versioned): Versioned[] => { + const out: Versioned[] = []; + const seen = new Set([head.id]); + for (let t = target(head); t && !seen.has(t.id); t = target(t)) { + seen.add(t.id); + out.push({ ...t, earlier: [] }); + } + return out; + }; + return files.filter((f) => !replaced.has(f.id)).map((h) => ({ ...h, earlier: chainOf(h) })); +}; From 796bc161a9bfae6fd133ad38475cdf45feda9546 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 23:00:10 +0000 Subject: [PATCH 013/177] Cut 3: doc marks versions done Co-Authored-By: Claude Sonnet 5.5 --- docs/commons-files-desk.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index 98696766..836af638 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -123,7 +123,7 @@ Status 2026-11-13: cut 1 merged to dev as bb615570 (PR #147); cuts 2-5 follow. C 1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias or carried id), opening the room's album view. Flagged, no new data layer. 2. **Pagination** of albums and files in `useAlbums` (done, PR #148). 3. **Folders by title path** and the album list grouped by it. -4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it. +4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149). 5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). PR #143 (Option B cut 1: contract types, host client, fake host) is **held**; under A it is not needed and would be closed. Its Soul pass found, and a revived B would have to close, an unvalidated `host` that could send the bearer to the wrong origin, hostile-looking entry names beyond separators, loose numeric checks and missing CSP and `Content-Disposition` headers in the fake. From 5835e565cd1fcb9b11b7b0b4633466ce417cb10b Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 23:03:33 +0000 Subject: [PATCH 014/177] Cut 3 Soul fixes: replaces counts only from the same sender; tests for the loop guard and the cover Co-Authored-By: Claude Sonnet 5.5 --- docs/commons-files-desk.md | 2 +- src/app/features/albums/buildAlbums.test.ts | 10 ++++++++++ src/app/features/albums/buildAlbums.ts | 2 ++ src/app/features/albums/versions.test.ts | 18 ++++++++++++++++-- src/app/features/albums/versions.ts | 10 +++++++--- 5 files changed, 36 insertions(+), 6 deletions(-) diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index 836af638..361624bd 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -82,7 +82,7 @@ What it buys: one identity, one audience, one audit trail, immutable files, exis - **When it posts.** Handoff documents are edited in place, so mirroring every save would spam the room with drafts. The rule (Eureka's lean, adopted): **post once, when the document is marked final**; a later final version posts again with a `replaces` relation to the earlier event. "Final" is a sibling `NAME.final` holding the document's sha256 (answered Q-E2); the client must not know. - **Allowlist.** Lives on the publisher: a list of source roots and patterns, read by the publisher only. `handoff-private` is not on it and the publisher never lists, reads or posts from it. The client holds no path to anything on disk. - **The event.** A file event in the thread of the folder's album, built the way `getMsgContent` builds them (`msgtype`, `body`, `filename`, `url` from the media repo, `info.mimetype|size|sha256`), plus one extra key `org.gamecult.publish`: `{ source, sha256, replaces? }` where `source` is a path relative to the allowlisted root, never absolute, and `replaces` is the event id of the version it supersedes. -- **`replaces`, not `m.replace`.** `m.replace` is the stock edit relation, but Ratatoskr's `buildAlbums` deliberately never treats an edit as a file, several clients do not render an edited file, and an edit hides the earlier version. A custom key keeps both events as files; the view shows the latest of a chain and a "N earlier versions" row under it, and other Matrix clients see two ordinary file posts. A chain is read from the events themselves (each carries its `replaces`), not from a table. +- **`replaces`, not `m.replace`.** `m.replace` is the stock edit relation, but Ratatoskr's `buildAlbums` deliberately never treats an edit as a file, several clients do not render an edited file, and an edit hides the earlier version. A custom key keeps both events as files; the view shows the latest of a chain and a "N earlier versions" row under it, and other Matrix clients see two ordinary file posts. A chain is read from the events themselves (each carries its `replaces`), not from a table, and a `replaces` counts only when its event has the same sender as the event it names, so nobody else in the thread can fold a file away. - **Idempotence.** The publisher's own state (a typed CultCache document of `source`, `sha256`, `event_id`) says what it posted; if that is lost, it rebuilds by reading its own events back from the room (`org.gamecult.publish.source` plus `sha256`) rather than guessing. The same `sha256` never posts twice. - **Receipts and fetch** work unchanged: the event is an ordinary file event in a file-zone room, so a Mind's mouth can fetch it by room id and event id (5 MiB cap there) and tick `fetched for`. diff --git a/src/app/features/albums/buildAlbums.test.ts b/src/app/features/albums/buildAlbums.test.ts index d8d8ed9f..3053a493 100644 --- a/src/app/features/albums/buildAlbums.test.ts +++ b/src/app/features/albums/buildAlbums.test.ts @@ -229,6 +229,16 @@ describe('versions', () => { }); }); +describe('versions: cover and sender', () => { + it('the cover comes from the shown version, not a folded image', () => { + const img = (id: string, ts: number, type: string, replaces?: string) => + reply(id, ts, type, id, replaces ? { 'org.gamecult.publish': { replaces } } : {}); + const a = one(root('$r', 1), [img('$v1', 10, 'm.image'), img('$v2', 20, 'm.file', '$v1')]); + expect(a.files.map((f) => f.id)).toEqual(['$v2']); + expect(a.cover).toBeUndefined(); + }); +}); + describe('Mind receipts', () => { const HASH = 'a'.repeat(64); const file = (id: string, sha?: string) => diff --git a/src/app/features/albums/buildAlbums.ts b/src/app/features/albums/buildAlbums.ts index 69fe82b4..636ede38 100644 --- a/src/app/features/albums/buildAlbums.ts +++ b/src/app/features/albums/buildAlbums.ts @@ -23,6 +23,7 @@ export type AlbumFile = { id: string; kind: FileKind; name: string; + sender: string; ts: number; /** The event content, as RenderMessageContent reads it. */ content: Record; @@ -75,6 +76,7 @@ const toFile = (e: ZoneEvent): AlbumFile | undefined => { id: e.event_id, kind, name: asString(e.content.filename) || asString(e.content.body), + sender: e.sender ?? '', ts: tsOf(e.origin_server_ts), content: e.content, readBy: [], diff --git a/src/app/features/albums/versions.test.ts b/src/app/features/albums/versions.test.ts index 645f409d..e8ae64b8 100644 --- a/src/app/features/albums/versions.test.ts +++ b/src/app/features/albums/versions.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it } from 'vitest'; import { PUBLISH_KEY, foldVersions, replacesOf } from './versions'; -type F = { id: string; content: Record; earlier: F[] }; -const f = (id: string, replaces?: string): F => ({ +type F = { id: string; sender: string; content: Record; earlier: F[] }; +const f = (id: string, replaces?: string, sender = '@m:x'): F => ({ id, + sender, content: replaces ? { [PUBLISH_KEY]: { replaces } } : {}, earlier: [], }); @@ -59,6 +60,19 @@ describe('foldVersions', () => { expect(out.map((x) => x.id)).toEqual(['$s']); }); + it('a loop reached from a head is walked once and ends', () => { + const out = foldVersions([f('$a', '$b'), f('$b', '$a'), f('$h', '$a')]); + expect(shape(out)).toEqual([['$h', ['$a', '$b']]]); + }); + + it('a replacement by another sender folds nothing', () => { + const out = foldVersions([f('$victim', undefined, '@m:x'), f('$evil', '$victim', '@e:x')]); + expect(shape(out)).toEqual([ + ['$victim', []], + ['$evil', []], + ]); + }); + it('an empty list is empty', () => { expect(foldVersions([])).toEqual([]); }); diff --git a/src/app/features/albums/versions.ts b/src/app/features/albums/versions.ts index f38af62b..8c7055db 100644 --- a/src/app/features/albums/versions.ts +++ b/src/app/features/albums/versions.ts @@ -17,16 +17,20 @@ type Versioned = F & { earlier: F[] }; /** * Files not replaced by another file in the list, oldest first as given, each carrying the files it * supersedes (nearest first) in `earlier`. A replacement whose target is missing from the list (a - * redacted event, another thread) replaces nothing and stands as a head. A file two others claim to + * redacted event, another thread) replaces nothing and stands as a head. A replacement by another sender is ignored. A file two others claim to * replace sits under both. The walk refuses to revisit a file, so a malformed chain cannot loop (an event id hashes its content, so a real one cannot cycle). */ -export const foldVersions = }>( +export const foldVersions = < + F extends { id: string; sender: string; content: Record } +>( files: Versioned[] ): Versioned[] => { const byId = new Map(files.map((f) => [f.id, f])); const target = (f: F): F | undefined => { const id = replacesOf(f.content); - return id && id !== f.id ? byId.get(id) : undefined; + const t = id && id !== f.id ? byId.get(id) : undefined; + // Only the sender of a file can supersede it, so no one else in the thread can fold it away. + return t && t.sender === f.sender ? t : undefined; }; const replaced = new Set(); files.forEach((f) => { From 0622d7d65dfa92f2f82b7d7bff70eca1b7d29a05 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 23:05:37 +0000 Subject: [PATCH 015/177] Files desk cut 4: add files to an open album; name the upload refusals sendShareSet takes a title or an existing album (no new root; the first file threads after the album's newest event). Failed files carry the refusal for M_TOO_LARGE, M_FORBIDDEN and M_LIMIT_EXCEEDED in the result note. AlbumView mounts an Add files panel inside an open album. Co-Authored-By: Claude Sonnet 5.5 --- docs/commons-files-desk.md | 2 +- docs/file-zone.md | 2 +- src/app/features/albums/AlbumView.tsx | 9 +++- src/app/features/albums/ShareSet.test.tsx | 15 +++++- src/app/features/albums/ShareSet.tsx | 42 +++++++++------ src/app/features/albums/buildAlbums.test.ts | 13 ++++- src/app/features/albums/buildAlbums.ts | 7 +++ src/app/features/albums/shareSet.test.ts | 58 ++++++++++++++++++++- src/app/features/albums/shareSet.ts | 42 ++++++++++++--- 9 files changed, 161 insertions(+), 29 deletions(-) diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index 361624bd..511b0dbc 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -124,7 +124,7 @@ Status 2026-11-13: cut 1 merged to dev as bb615570 (PR #147); cuts 2-5 follow. C 2. **Pagination** of albums and files in `useAlbums` (done, PR #148). 3. **Folders by title path** and the album list grouped by it. 4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149). -5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). +5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). Done: adding to an open album and the three refusal messages (PR #150); cancel of a send in flight is not, and needs an abort path through `uploadContent`. PR #143 (Option B cut 1: contract types, host client, fake host) is **held**; under A it is not needed and would be closed. Its Soul pass found, and a revived B would have to close, an unvalidated `host` that could send the bearer to the wrong origin, hostile-looking entry names beyond separators, loose numeric checks and missing CSP and `Content-Disposition` headers in the fake. diff --git a/docs/file-zone.md b/docs/file-zone.md index 7990485d..0a895226 100644 --- a/docs/file-zone.md +++ b/docs/file-zone.md @@ -120,4 +120,4 @@ Client, `src/app/features/albums`: Flag: `fileZoneShare.enabled` in `config.json`, default `false`. With it off nothing mounts. -Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; sharing into an existing album ("add files"); upload cancel; pagination beyond 100 albums/files. +Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; cancel of a send in flight (a pick can be cancelled before it goes). Built since: pagination to 20 pages of 100 per endpoint (PR #148), adding files to an open album with named refusals (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`). diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx index 944cc761..fc76744a 100644 --- a/src/app/features/albums/AlbumView.tsx +++ b/src/app/features/albums/AlbumView.tsx @@ -14,7 +14,7 @@ import { markAsRead } from '../../utils/notifications'; import { getBlobSafeMimeType } from '../../utils/mimeTypes'; import { timeDayMonYear } from '../../utils/time'; import { getMemberDisplayName } from '../../utils/room'; -import { Album, AlbumFile } from './buildAlbums'; +import { Album, AlbumFile, lastEventId } from './buildAlbums'; import { folderOf, listFolder, pathLabel } from './albumFolders'; import { FileReadBy } from './FileReadBy'; import { ShareSet, useShareEnabled } from './ShareSet'; @@ -142,6 +142,13 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { {authorOf(open)} · {countLabel(open.count)} · {timeDayMonYear(open.ts, dateFormat)}
{open.count === 0 && This album has no files.} + {canShare && ( + + )}
{open.files.map((f) => ( diff --git a/src/app/features/albums/ShareSet.test.tsx b/src/app/features/albums/ShareSet.test.tsx index bfa9a619..6ae47613 100644 --- a/src/app/features/albums/ShareSet.test.tsx +++ b/src/app/features/albums/ShareSet.test.tsx @@ -14,7 +14,7 @@ const text = (html: string) => const noop = () => undefined; const file = (name: string) => ({ name, type: 'audio/ogg' } as File); -const view = (over: Partial> = {}) => +const view = (over: Partial> = {}, adding = false) => renderToStaticMarkup( > = {}) => onTitle={noop} onSend={noop} onCancel={noop} + adding={adding} /> ); @@ -76,6 +77,18 @@ describe('the share panel, drawn', () => { }); }); +describe('adding to an existing album', () => { + it('the idle row says Add files', () => { + expect(text(view({}, true))).toBe('Add files ›'); + }); + + it('picked: no title field, the names, Send and Cancel', () => { + const html = view({ files: [file('a.ogg')] }, true); + expect(html).not.toContain('aria-label="Album title"'); + expect(text(html)).toBe('a.ogg Send 1 file Cancel'); + }); +}); + describe('the flag', () => { it('off, missing or empty offers no share', () => { expect(shareEnabled({}, false)).toBe(false); diff --git a/src/app/features/albums/ShareSet.tsx b/src/app/features/albums/ShareSet.tsx index 1d76753a..a8e65b4f 100644 --- a/src/app/features/albums/ShareSet.tsx +++ b/src/app/features/albums/ShareSet.tsx @@ -10,7 +10,7 @@ import { getMsgContent } from '../room/msgContent'; import { FILE_HASH_KEY, hashForSend } from './fileReceipt'; import { ShareController, ShareState, createShareController } from './shareController'; import { titleIn } from './albumFolders'; -import { DEFAULT_TITLE, sendShareSet } from './shareSet'; +import { DEFAULT_TITLE, ExistingAlbum, sendShareSet } from './shareSet'; import * as css from './AlbumView.css'; /** Off unless `fileZoneShare.enabled` is true. An encrypted zone is never offered the share. */ @@ -29,6 +29,8 @@ type ShareViewProps = { onTitle: (title: string) => void; onSend: () => void; onCancel: () => void; + /** Adding to an existing album: the files join it, so there is no title to ask for. */ + adding?: boolean; inputRef?: React.Ref; }; @@ -43,6 +45,7 @@ export function ShareSetView({ onTitle, onSend, onCancel, + adding, inputRef, }: ShareViewProps) { const { files, title, phase, epoch } = state; @@ -58,7 +61,7 @@ export function ShareSetView({ /> {files.length === 0 && phase.kind !== 'sending' && ( )} {phase.kind === 'done' && ( @@ -68,14 +71,16 @@ export function ShareSetView({ )} {files.length > 0 && ( <> - onTitle(e.target.value)} - /> + {!adding && ( + onTitle(e.target.value)} + /> + )} {files.map((f) => f.name).join(' · ')} @@ -101,15 +106,21 @@ export function ShareSetView({ ); } -/** `folder` is the path the share lands in: its albums are titled under it (docs/commons-files-desk.md). */ -export function ShareSet({ room, folder = [] }: { room: Room; folder?: string[] }) { +type ShareSetProps = { + room: Room; + /** The path a new album lands in: its title is prefixed by it (docs/commons-files-desk.md). */ + folder?: string[]; + /** Add the files to this album instead of making one. */ + into?: ExistingAlbum; +}; +export function ShareSet({ room, folder = [], into }: ShareSetProps) { const mx = useMatrixClient(); const queryClient = useQueryClient(); const input = useRef(null); // Built once per mount (AlbumView keys the panel by room): the pick lives in the controller, so a // rerender with a new client or Room object must not build another. Live values go through `live`. - const live = useRef({ mx, room, queryClient, folder }); - live.current = { mx, room, queryClient, folder }; + const live = useRef({ mx, room, queryClient, folder, into }); + live.current = { mx, room, queryClient, folder, into }; const [controller]: [ShareController, unknown] = useState(() => createShareController({ roomId: room.roomId, @@ -142,7 +153,7 @@ export function ShareSet({ room, folder = [] }: { room: Room; folder?: string[] }, onFile, }, - titleIn(live.current.folder, title, DEFAULT_TITLE), + live.current.into ?? titleIn(live.current.folder, title, DEFAULT_TITLE), files.map((file) => ({ name: file.name, mimeType: file.type, file })) ), }) @@ -157,6 +168,7 @@ export function ShareSet({ room, folder = [] }: { room: Room; folder?: string[] onTitle={controller.setTitle} onSend={controller.send} onCancel={controller.cancel} + adding={!!into} /> ); } diff --git a/src/app/features/albums/buildAlbums.test.ts b/src/app/features/albums/buildAlbums.test.ts index 3053a493..4bf72d0e 100644 --- a/src/app/features/albums/buildAlbums.test.ts +++ b/src/app/features/albums/buildAlbums.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { AlbumInput, ZoneEvent, buildAlbums } from './buildAlbums'; +import { AlbumInput, ZoneEvent, buildAlbums, lastEventId } from './buildAlbums'; const root = (id: string, ts: number, over: Partial = {}): ZoneEvent => ({ event_id: id, @@ -239,6 +239,17 @@ describe('versions: cover and sender', () => { }); }); +describe('lastEventId', () => { + it('is the newest event of the thread, a folded version included; the root when empty', () => { + const v = (id: string, ts: number, replaces?: string) => + reply(id, ts, 'm.file', id, replaces ? { 'org.gamecult.publish': { replaces } } : {}); + expect(lastEventId(one(root('$r', 1), [v('$a', 10), v('$b', 20, '$a'), v('$c', 15)]))).toBe( + '$b' + ); + expect(lastEventId(one(root('$r', 1), []))).toBe('$r'); + }); +}); + describe('Mind receipts', () => { const HASH = 'a'.repeat(64); const file = (id: string, sha?: string) => diff --git a/src/app/features/albums/buildAlbums.ts b/src/app/features/albums/buildAlbums.ts index 636ede38..0fe2d113 100644 --- a/src/app/features/albums/buildAlbums.ts +++ b/src/app/features/albums/buildAlbums.ts @@ -134,3 +134,10 @@ export const buildAlbums = (inputs: AlbumInput[], server = ''): Album[] => { }) .sort((a, b) => b.ts - a.ts); }; + +/** The newest event in an album's thread (shown or folded), else its root: where a new file threads after. */ +export const lastEventId = (album: Album): string => + album.files + .flatMap((f) => [f, ...f.earlier]) + .reduce((a, f) => (!a || f.ts >= a.ts ? f : a), undefined)?.id ?? + album.id; diff --git a/src/app/features/albums/shareSet.test.ts b/src/app/features/albums/shareSet.test.ts index f43e5a35..d1db0b2e 100644 --- a/src/app/features/albums/shareSet.test.ts +++ b/src/app/features/albums/shareSet.test.ts @@ -5,6 +5,7 @@ import { DEFAULT_TITLE, ShareFile, SharePort, + refusalOf, remainingAfter, resultNote, sendShareSet, @@ -56,7 +57,7 @@ describe('sendShareSet', () => { it('reads back as one album of the files in pick order', async () => { const r = room(); const res = await sendShareSet(r.port, 'Take 4', clips); - expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [] }); + expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] }); const album = r.album(); expect(album.title).toBe('Take 4'); expect(album.files.map((f) => [f.name, f.kind])).toEqual([ @@ -158,3 +159,58 @@ describe('after a send', () => { expect(resultNote(res)).toBe('Shared 3 files.'); }); }); + +describe('adding to an existing album', () => { + it('sends no root; each file threads under the album, the first after `lastId`', async () => { + const r = room(); + const sent: Record[] = []; + const port = { + ...r.port, + send: async (c: Record) => { + sent.push(c); + return `$n${sent.length}`; + }, + }; + const res = await sendShareSet(port, { albumId: '$root', lastId: '$last' }, clips.slice(0, 2)); + expect(res.albumId).toBe('$root'); + expect(res.sent).toBe(2); + expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']); + expect(sent.map((c) => c['m.relates_to'])).toEqual([ + threadRelation('$root', '$last'), + threadRelation('$root', '$n1'), + ]); + }); +}); + +describe('refusals', () => { + const refuse = (errcode: string): SharePort => ({ + send: async () => '$e', + contentOf: async () => { + throw Object.assign(new Error('raw server text'), { errcode }); + }, + }); + + it('names the three upload refusals and nothing else', () => { + expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server'); + expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here'); + expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe( + 'uploading too fast, try again shortly' + ); + expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined(); + expect(refusalOf({ errcode: 'constructor' })).toBeUndefined(); + expect(refusalOf(new Error('x'))).toBeUndefined(); + expect(refusalOf(null)).toBeUndefined(); + }); + + it('the note carries the reason beside each refused file', async () => { + const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2)); + expect(resultNote(res)).toBe( + 'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)' + ); + }); + + it('an unnamed failure lists the bare name', async () => { + const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1)); + expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg'); + }); +}); diff --git a/src/app/features/albums/shareSet.ts b/src/app/features/albums/shareSet.ts index 3e572595..c3652f62 100644 --- a/src/app/features/albums/shareSet.ts +++ b/src/app/features/albums/shareSet.ts @@ -22,6 +22,23 @@ export type ShareResult = { failed: string[]; /** Positions in the files array of those that failed; names can repeat, positions cannot. */ failedAt: number[]; + /** Why each failed file failed, parallel to `failed`, when the homeserver's refusal is one we name. */ + reasons?: (string | undefined)[]; +}; + +/** An album that already exists: new files join its thread after `lastId`, with no new root. */ +export type ExistingAlbum = { albumId: string; lastId: string }; + +const REFUSALS: Record = { + M_TOO_LARGE: 'too large for this server', + M_FORBIDDEN: 'not allowed to upload here', + M_LIMIT_EXCEEDED: 'uploading too fast, try again shortly', +}; + +/** The sentence for a homeserver refusal we know, from the error's Matrix errcode. */ +export const refusalOf = (e: unknown): string | undefined => { + const code = (e as { errcode?: unknown } | null)?.errcode; + return typeof code === 'string' && Object.hasOwn(REFUSALS, code) ? REFUSALS[code] : undefined; }; /** The reply relation Matrix clients expect for a thread message: root, with the last event as fallback reply. */ @@ -44,12 +61,15 @@ export const titleOrDefault = (title: string): string => title.trim() || DEFAULT */ export const sendShareSet = async ( port: SharePort, - title: string, + into: string | ExistingAlbum, files: F[] ): Promise => { - const albumId = await port.send({ msgtype: 'm.text', body: titleOrDefault(title) }); - const result: ShareResult = { albumId, sent: 0, failed: [], failedAt: [] }; - let lastId = albumId; + const albumId = + typeof into === 'string' + ? await port.send({ msgtype: 'm.text', body: titleOrDefault(into) }) + : into.albumId; + const result: ShareResult = { albumId, sent: 0, failed: [], failedAt: [], reasons: [] }; + let lastId = typeof into === 'string' ? albumId : into.lastId; for (let i = 0; i < files.length; i += 1) { try { // eslint-disable-next-line no-await-in-loop @@ -58,8 +78,9 @@ export const sendShareSet = async ( lastId = await port.send({ ...content, 'm.relates_to': threadRelation(albumId, lastId) }); result.sent += 1; port.onFile?.(i, 'sent'); - } catch { + } catch (e) { result.failed.push(files[i].name); + result.reasons?.push(refusalOf(e)); result.failedAt.push(i); port.onFile?.(i, 'failed'); } @@ -69,15 +90,20 @@ export const sendShareSet = async ( /** * What stays picked after a send: only the files that did not go, so a retry is one tap. A retry - * makes a second album (adding to an existing one is not built), and a share where nothing went + * of a new album makes a second album, and a share where nothing went * leaves its root as a lone message the album list does not show (it lists threads with replies). */ export const remainingAfter = (files: T[], result: ShareResult): T[] => files.filter((_, i) => result.failedAt.includes(i)); +const failedList = (result: ShareResult): string => + result.failed + .map((name, i) => (result.reasons?.[i] ? `${name} (${result.reasons[i]})` : name)) + .join(', '); + export const resultNote = (result: ShareResult): string => { if (result.failed.length === 0) return `Shared ${result.sent} ${result.sent === 1 ? 'file' : 'files'}.`; - if (result.sent === 0) return `Nothing was shared. Not sent: ${result.failed.join(', ')}`; - return `Shared ${result.sent}. Not sent: ${result.failed.join(', ')}`; + if (result.sent === 0) return `Nothing was shared. Not sent: ${failedList(result)}`; + return `Shared ${result.sent}. Not sent: ${failedList(result)}`; }; From 90c6d5e2788071ec0dfeea4b28fb1e7675040d20 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 23:11:33 +0000 Subject: [PATCH 016/177] Cut 4: pin that ShareSet sends into an existing album Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/albums/ShareSet.folder.test.tsx | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/app/features/albums/ShareSet.folder.test.tsx b/src/app/features/albums/ShareSet.folder.test.tsx index 7f23fd63..a19f6e16 100644 --- a/src/app/features/albums/ShareSet.folder.test.tsx +++ b/src/app/features/albums/ShareSet.folder.test.tsx @@ -27,8 +27,8 @@ vi.mock('./shareController', () => ({ })); vi.mock('./shareSet', async (importOriginal) => ({ ...(await importOriginal()), - sendShareSet: async (_port: unknown, title: string) => { - captured.titles.push(title); + sendShareSet: async (_port: unknown, into: string | { albumId: string }) => { + captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}`); return { albumId: '$a', sent: 0, failed: [], failedAt: [] }; }, })); @@ -42,12 +42,12 @@ vi.mock('react', async (importOriginal) => { // eslint-disable-next-line import/first import { ShareSet } from './ShareSet'; -const mount = (folder?: string[]) => { +const mount = (folder?: string[], into?: { albumId: string; lastId: string }) => { const room = { roomId: '!r:x', hasEncryptionStateEvent: () => false } as never; renderToStaticMarkup( ({ event_id: '$e' }) } as never}> - + ); @@ -82,4 +82,9 @@ describe('ShareSet: the folder reaches the album title', () => { mount(['a']); expect(await send('b/c')).toBe('a/b/c'); }); + + it('an existing album takes the files instead of a title, whatever the folder', async () => { + mount(['a'], { albumId: '$alb', lastId: '$last' }); + expect(await send('ignored')).toBe('into:$alb'); + }); }); From e406ec7dc4b011be47794806f9166ed9abfdddc5 Mon Sep 17 00:00:00 2001 From: Void Date: Fri, 13 Nov 2026 23:14:42 +0000 Subject: [PATCH 017/177] Files desk: Stop a send in flight; files in a replaces loop all show; Add files threads after the freshest event Stop aborts the running upload (onPromise + mx.cancelUpload) and leaves it and the rest picked as 'stopped'. foldVersions shows files caught in a replaces loop with no head instead of hiding them. An add reads the room timeline at send time for the newest event in the thread. Co-Authored-By: Claude Sonnet 5.5 --- docs/commons-files-desk.md | 2 +- docs/file-zone.md | 2 +- src/app/features/albums/AlbumView.tsx | 4 +- .../features/albums/ShareSet.folder.test.tsx | 34 +++++-- src/app/features/albums/ShareSet.test.tsx | 2 + src/app/features/albums/ShareSet.tsx | 44 +++++++-- src/app/features/albums/buildAlbums.test.ts | 13 +-- src/app/features/albums/buildAlbums.ts | 8 +- .../features/albums/shareController.test.ts | 26 +++++- src/app/features/albums/shareController.ts | 21 +++-- src/app/features/albums/shareSet.test.ts | 89 ++++++++++++++++++- src/app/features/albums/shareSet.ts | 40 ++++++++- src/app/features/albums/versions.test.ts | 8 +- src/app/features/albums/versions.ts | 10 ++- 14 files changed, 262 insertions(+), 41 deletions(-) diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index 511b0dbc..7b06bb9d 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -124,7 +124,7 @@ Status 2026-11-13: cut 1 merged to dev as bb615570 (PR #147); cuts 2-5 follow. C 2. **Pagination** of albums and files in `useAlbums` (done, PR #148). 3. **Folders by title path** and the album list grouped by it. 4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149). -5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). Done: adding to an open album and the three refusal messages (PR #150); cancel of a send in flight is not, and needs an abort path through `uploadContent`. +5. **Add files to an existing album**, with per-file progress, cancel and the refusal messages above (the upload flow). Done: adding to an open album and the three refusal messages (PR #150); Stop for a send in flight is in too (PR for follow-up `files-desk-release-146-and-send-cancel`): it cancels the running upload through `onPromise` and `mx.cancelUpload`. PR #143 (Option B cut 1: contract types, host client, fake host) is **held**; under A it is not needed and would be closed. Its Soul pass found, and a revived B would have to close, an unvalidated `host` that could send the bearer to the wrong origin, hostile-looking entry names beyond separators, loose numeric checks and missing CSP and `Content-Disposition` headers in the fake. diff --git a/docs/file-zone.md b/docs/file-zone.md index 0a895226..420f7016 100644 --- a/docs/file-zone.md +++ b/docs/file-zone.md @@ -120,4 +120,4 @@ Client, `src/app/features/albums`: Flag: `fileZoneShare.enabled` in `config.json`, default `false`. With it off nothing mounts. -Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; cancel of a send in flight (a pick can be cancelled before it goes). Built since: pagination to 20 pages of 100 per endpoint (PR #148), adding files to an open album with named refusals (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`). +Not built: a Mind's own path into the zone (outbox, Persona decision, mouth post) belongs to gamecult-ops / Huginn / the mouth, not this client; Built since: Stop for a send in flight (aborts the running upload, leaves it and the rest picked as "stopped"), pagination to 20 pages of 100 per endpoint (PR #148), adding files to an open album with named refusals (`M_TOO_LARGE`, `M_FORBIDDEN`, `M_LIMIT_EXCEEDED`). diff --git a/src/app/features/albums/AlbumView.tsx b/src/app/features/albums/AlbumView.tsx index fc76744a..d6ee37c9 100644 --- a/src/app/features/albums/AlbumView.tsx +++ b/src/app/features/albums/AlbumView.tsx @@ -14,7 +14,7 @@ import { markAsRead } from '../../utils/notifications'; import { getBlobSafeMimeType } from '../../utils/mimeTypes'; import { timeDayMonYear } from '../../utils/time'; import { getMemberDisplayName } from '../../utils/room'; -import { Album, AlbumFile, lastEventId } from './buildAlbums'; +import { Album, AlbumFile, lastEvent } from './buildAlbums'; import { folderOf, listFolder, pathLabel } from './albumFolders'; import { FileReadBy } from './FileReadBy'; import { ShareSet, useShareEnabled } from './ShareSet'; @@ -146,7 +146,7 @@ export function AlbumView({ room, onTimeline }: AlbumViewProps) { )}
diff --git a/src/app/features/albums/ShareSet.folder.test.tsx b/src/app/features/albums/ShareSet.folder.test.tsx index a19f6e16..109d538c 100644 --- a/src/app/features/albums/ShareSet.folder.test.tsx +++ b/src/app/features/albums/ShareSet.folder.test.tsx @@ -27,8 +27,8 @@ vi.mock('./shareController', () => ({ })); vi.mock('./shareSet', async (importOriginal) => ({ ...(await importOriginal()), - sendShareSet: async (_port: unknown, into: string | { albumId: string }) => { - captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}`); + sendShareSet: async (_port: unknown, into: string | { albumId: string; lastId: string }) => { + captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}@${into.lastId}`); return { albumId: '$a', sent: 0, failed: [], failedAt: [] }; }, })); @@ -42,8 +42,19 @@ vi.mock('react', async (importOriginal) => { // eslint-disable-next-line import/first import { ShareSet } from './ShareSet'; -const mount = (folder?: string[], into?: { albumId: string; lastId: string }) => { - const room = { roomId: '!r:x', hasEncryptionStateEvent: () => false } as never; +const timeline: unknown[] = []; +const ev = (id: string, ts: number, threadRootId?: string, status: string | null = null) => ({ + getId: () => id, + getTs: () => ts, + threadRootId, + status, +}); +const mount = (folder?: string[], into?: { albumId: string; lastId: string; lastTs: number }) => { + const room = { + roomId: '!r:x', + hasEncryptionStateEvent: () => false, + getLiveTimeline: () => ({ getEvents: () => timeline }), + } as never; renderToStaticMarkup( ({ event_id: '$e' }) } as never}> @@ -61,6 +72,7 @@ describe('ShareSet: the folder reaches the album title', () => { beforeEach(() => { captured.run = undefined; captured.titles.length = 0; + timeline.length = 0; }); it('at the top, the typed title goes as typed', async () => { @@ -84,7 +96,17 @@ describe('ShareSet: the folder reaches the album title', () => { }); it('an existing album takes the files instead of a title, whatever the folder', async () => { - mount(['a'], { albumId: '$alb', lastId: '$last' }); - expect(await send('ignored')).toBe('into:$alb'); + mount(['a'], { albumId: '$alb', lastId: '$last', lastTs: 5 }); + expect(await send('ignored')).toBe('into:$alb@$last'); + }); + + it('the freshest sent event of that thread in the room timeline is where the files thread after', async () => { + timeline.push( + ev('$other', 99, '$else'), + ev('$local', 98, '$alb', 'sending'), + ev('$new', 50, '$alb') + ); + mount(['a'], { albumId: '$alb', lastId: '$last', lastTs: 5 }); + expect(await send('x')).toBe('into:$alb@$new'); }); }); diff --git a/src/app/features/albums/ShareSet.test.tsx b/src/app/features/albums/ShareSet.test.tsx index 6ae47613..b3da7a3d 100644 --- a/src/app/features/albums/ShareSet.test.tsx +++ b/src/app/features/albums/ShareSet.test.tsx @@ -23,6 +23,7 @@ const view = (over: Partial> = {}, adding = false) => onTitle={noop} onSend={noop} onCancel={noop} + onStop={noop} adding={adding} /> ); @@ -55,6 +56,7 @@ describe('the share panel, drawn', () => { phase: { kind: 'sending', done: 2 }, }); expect(text(html)).toContain('Sending 2 of 3…'); + expect(text(html)).toContain('Stop'); expect(text(html)).not.toContain('Send 3 files'); expect(text(html)).not.toContain('Cancel'); expect(html).toMatch( diff --git a/src/app/features/albums/ShareSet.tsx b/src/app/features/albums/ShareSet.tsx index a8e65b4f..6bce53c7 100644 --- a/src/app/features/albums/ShareSet.tsx +++ b/src/app/features/albums/ShareSet.tsx @@ -10,7 +10,7 @@ import { getMsgContent } from '../room/msgContent'; import { FILE_HASH_KEY, hashForSend } from './fileReceipt'; import { ShareController, ShareState, createShareController } from './shareController'; import { titleIn } from './albumFolders'; -import { DEFAULT_TITLE, ExistingAlbum, sendShareSet } from './shareSet'; +import { DEFAULT_TITLE, ExistingAlbum, freshest, sendShareSet, ThreadEvent } from './shareSet'; import * as css from './AlbumView.css'; /** Off unless `fileZoneShare.enabled` is true. An encrypted zone is never offered the share. */ @@ -29,6 +29,7 @@ type ShareViewProps = { onTitle: (title: string) => void; onSend: () => void; onCancel: () => void; + onStop: () => void; /** Adding to an existing album: the files join it, so there is no title to ask for. */ adding?: boolean; inputRef?: React.Ref; @@ -45,6 +46,7 @@ export function ShareSetView({ onTitle, onSend, onCancel, + onStop, adding, inputRef, }: ShareViewProps) { @@ -85,9 +87,14 @@ export function ShareSetView({ {files.map((f) => f.name).join(' · ')} {phase.kind === 'sending' ? ( - - Sending {phase.done} of {files.length}… - + <> + + Sending {phase.done} of {files.length}… + + + ) : ( <>