A Backups section (for administrators, PrivaPub's /clientapi/admin/backups): the backups kept with their kind, size, media and the logins deleted since, what runs, the restore waiting and the last restore's report. Back up now; download for the password through a link good for ten minutes, which the browser saves to disk; upload a downloaded backup in pieces straight from the picked file (js/transfer.js PUTs file.slice at the offset PrivaPub has, never through .NET's memory, and carries on after a refused or lost piece); delete after asking; restore for the password and the host typed out, saying what it keeps and what it loses, then showing PrivaPub restarting until the ended session sends the page to sign in. e2e: a backup made, downloaded and uploaded again; and, only with --filter "Category=Restore", a real restore of the pasture, which signs the town in again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LsXgEaXee4GCU1hwYgPJXw
48 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
What this is
decePubClient is a Blazor WebAssembly PWA (.NET 10). It is meant as a Pleroma-FE-like client for PrivaPub, the
owner's ActivityPub server, whose repo is thepra/SocialPub. It is deployed as a static site at
https://decepub.thepra.dev, and its API base address is https://privapub.thepra.dev
(AppConfiguration:ApiBaseAddress in wwwroot/appsettings.json).
It talks to PrivaPub through both of its APIs with one sign-in (see PrivaPub wiring below). The feed page has three
columns: navigation, the feed with a tab per kind of feed, and a 3D globe that follows the posts in view. Nerd stats sit
in tooltips wherever there is data. Development builds point at a local PrivaPub on http://127.0.0.1:6970
(wwwroot/appsettings.Development.json, never published).
Docs/Insomnia_APIs.json is an old API collection for a localhost backend. Don't treat it as PrivaPub's API.
Sibling repo dependency
The project references ../SocialPub/PrivaPub.ClientModels/PrivaPub.ClientModels.csproj, so SocialPub must be
checked out next to this repo. CI clones it there. That project supplies:
- the shared DTOs;
Policies(IsAdmin, IsUser, IsModerator);- the
FieldsNameResourceandErrorsResourcelocalization resources.
Before wiring anything to the API, read ../SocialPub/CLAUDE.md. PrivaPub's route names (/peasants/..., /mouth,
/anus, ...) are deliberate. Never "correct" them. The API surface is the Mastodon client API plus PrivaPub's private
/clientapi and /api/privapub/v1.
To run against a local PrivaPub: start a mongod, run SocialPub's PrivaPub with the Development command in its
CLAUDE.md on 127.0.0.1:6970 (Registrations__Mode=Open lets /clientapi/user/signup create a root), then create
personas with /clientapi/avatar/private/insert. Federated posts come from SocialPub's pasture
(tools/pasture/run.sh up gts akkoma, then tools/pasture/interop.sh gts akkoma), whose API is 127.0.0.1:6971.
Neither DB-IP nor PrivaPub locate private addresses, so for the globe set RemoteInstance.Geo in mongo and
Statistics:Geo:Self in PrivaPub's configuration.
Commands
dotnet build decePubClient.csproj # what CI runs (-c Release) on every push to master and on PRs
dotnet run # dev server: https://localhost:7046 / http://localhost:5046
dotnet publish decePubClient.csproj -c Release -o publish # static site lands in publish/wwwroot
global.json pins SDK 10.0.100 with rollForward: latestFeature. There is no linter.
Testing: end to end against the pasture
tests/e2e (Playwright for .NET 1.61.0 on xunit v3) runs the published app in Chromium against SocialPub's pasture: a
private fediverse of PrivaPub and its peers (GoToSocial, Mastodon, Misskey, Sharkey, Akkoma, Lemmy) seeded with a fake
community, the town (see ../SocialPub/CLAUDE.md, "The town"). Never in CI: it needs podman and the pasture.
../SocialPub/tools/pasture/run.sh up gts mastodon misskey sharkey akkoma lemmy # PASTURE_PORT if 6971 is taken
../SocialPub/tools/pasture/town.sh seed village
tests/e2e/run.sh [--filter ...] # publishes with WasmApplicationEnvironmentName=Pasture, serves https://decepub.test, runs
-
The app under test is the deploy's own build with the environment baked in: Blazor on .NET 10 ignores the
Blazor-Environmentheader, sowwwroot/appsettings.Pasture.json(APIhttps://privapub.test) is chosen at publish time and published only then; the deploy fails if it ever ships. -
Chromium resolves
*.testto Caddy on127.0.0.1:6443(--host-resolver-rules) and ignores the pasture CA. The tests use the Chromium headless shell 1228 cached in~/.cache/ms-playwrightand never install a browser. -
Guards on every test (
Support/Browser.cs): the app talks only to its own site and to PrivaPub, a root JWT never goes to/apinor a persona token to/clientapi, no 5xx, no Blazor error bar. -
The tests ask the town (
Support/Pasture.cs) which accounts exist and what each object holds (town.sh expect), and check the other side of the wire throughtown.sh stored. Each render and action test is also a cell of the town's report (out/client.jsonl). -
Cards carry
data-uri(their ActivityPub id) and the empty feeddata-feed-empty, for the tests. The feed renders only the cards near the view, so a test looks for recent cards, and counts what is loaded bydata-feed-count. -
Phones (
Mobile/,Category=Mobile):Browser.Open(state, Phone)opens Playwright's own device presets (shipped in its package): 360×800, iPhone SE (3rd gen), Pixel 7, and the Pixel 7 held sideways, with touch, a coarse pointer and reduced motion; a phone session fails at once if the page doesn't see a touch screen.SignIn.As(browser, persona, phone)reuses the desktop sign-in, and any saved sign-in that has expired is renewed.-
RouteSweepTestsmeasures every page, one screen at a time down its main scroller (Mobile/fit.js). It checks:- sideways scroll, unless the strip is marked
data-scroll-x; - boxes past the screen's sides;
- open menus, sheets and dialogs that are cut or outside the screen;
- targets without a 44px hit area: hit-tested at their centre and 21px around it, so a crowding neighbour fails
them too. Inline links in post text, native media controls and disabled controls are exempt, a fixed floating
control covering a target doesn't count, and
data-touch-exemptexempts one explicitly; - control text under 12px.
Screenshots, findings and a contact sheet go to
tests/e2e/out/mobile/<run>/. Cells areclient.mobile.fit.*andclient.mobile.touch.*, with the phone as the ref. - sideways scroll, unless the strip is marked
-
FlowTestsdrives the narrowest phone through the menu, a dialog, a new post, a reply, a reaction, a deletion, the full-screen globe, a phone held sideways, a tap into a thread, a picture and the Back button (client.mobile.flow.*). -
DesktopUnchangedTestsholds desktop's control sizes.
-
-
The globe (
Render/GlobeTests.cs): the instruments are built, with the Sun drawn over its subsolar point.- On desktop, a located post written from Milano is pinned, and the globe is photographed in both themes and again turned to the subsolar point.
- On a phone, the banner draws little, full screen draws everything with the camera moved back, and closing returns to the banner.
- An idle globe draws no frame.
Photos and stats go to
tests/e2e/out/globe/. -
Restore (
Category=Restore, inActions/BackupsTests.cs): a real restore of the pasture from Administration. It ends every session, the town's too, so it runs only when asked (--filter "Category=Restore", never next to other tests) and signs the town in again (town.sh renew privapub). Normal runs use--filter "Category!=Perf&Category!=Restore". -
Perf (
Perf/,Category=Perf, left out of the normal runs with--filter "Category!=Perf"):FeedPerfTestsscrolls load0's home (thousands of posts from SocialPub'sload.sh) to 2000 posts and writes, per step, the time, DOM nodes, JS and .NET heaps and long tasks toperf.json. -
The root project globs
**/*.cs, so it excludestests/**(DefaultItemExcludes), and Tailwind does not scan it.
CSS: Tailwind 4 + daisyUI 5, vendored, offline
Styles/app.css is compiled into wwwroot/css/app.css by the Tailwind CSS standalone binary with the daisyUI
plugin. app.css is gitignored and regenerated on every build.
Nothing in the build or the CI may download from github.com. Tools live in the repo, and the CSS build runs without network access. NuGet restore still uses nuget.org.
tools/tailwind/holds the pinned tools:- Tailwind 4.3.3 as
tailwindcss-linux-x64.xz; - daisyUI 5.7.47 (
daisyui.mjs,daisyui-theme.mjs); - daisyUI's component reference,
daisyui-llms.txt.
- Tailwind 4.3.3 as
.gitattributeskeeps these files byte-exact.tools/tailwind.sh preparechecks them against the sha256 values pinned in the script, and unpacks the binary into the gitignored.tools/tailwind/. It needsxz.- Only linux-x64 is vendored.
- The script's header explains how to upgrade or add a platform.
- The
TailwindCompiletarget in the csproj runs it, sodotnet build/publishare enough, in CI as well. Debug builds use--optimize, Release builds--minify. Pass-p:SkipTailwind=trueto skip it. IncludeTailwindOutputadds the generated file toContentbefore static web assets are resolved. Without that, a clean-clone publish would shipapp.csswithout its.gz/.brcopies and outsideservice-worker-assets.js. The deploy workflow checks forcss/app.css.gz.bash tools/tailwind.sh watchrebuilds the CSS live next todotnet watch.- Tailwind scans every file
.gitignoredoesn't exclude (minustools/,wwwroot/vendor/,Docs/), and only generates the classes it finds written out whole. Never build a class name by concatenation or interpolation ("btn-" + size,$"btn-{size}"). Write every variant as a literal, e.g. in a switch arm.
Ionicons 4.5 (wwwroot/vendor/ionicons.min.css, <i class="ion-md-...">) is loaded as its own stylesheet.
Theme and neumorphism
Styles/theme.cssholds two daisyUI themes,neo-light(default) andneo-dark(prefersdark). Every colour is anhsl()of--neo-hue-light/--neo-hue-dark/--neo-chroma(0 for the grey themes).wwwroot/js/theme.jssets those variables anddata-themeon<html>fromPageSettings. It runs in<head>from localStorage, so there is no flash before Blazor boots. After that, CascadingState calls it throughAppStatusService.ApplyThemewhenever the settings change. WithPreferSystemThemingit leavesdata-themeoff, and the OS decides.- Change the theme flags through
PageSettings.SetDarkMode/SetGray/SetHueandCascadingState.UpdatePageSettings, which keep the flags consistent:- choosing light or dark leaves system theming;
- picking a hue leaves grey.
AppStatusService.IsDarkTheme()tells which variant is showing.- Settings → General edits every theme setting. NavMenu's toggle and slider are shortcuts to the dark and hue ones. The other sections of Settings belong to the persona (see Settings under PrivaPub wiring).
Styles/neo.cssholds the neumorphic layer:neo-raised/neo-inset/neo-flat, with sizesneo-2xs/neo-xs/neo-sm/neo-md(these replace the oldneomorph is-nxsmallclasses);neo-gradient(-pressed)andneo-hue-track;@utility <daisy-component>overrides that give btn, input, select, card, … the neo look. daisyUI puts its rules in sublayers ofutilities, so these overrides beat every daisyUI rule. Each override must exclude the daisyUI variants it shouldn't touch, e.g.:not(:where(.btn-ghost, .btn-link, ...)), and call sites drop a neo shadow withshadow-none!.
- Never write
@utility collapse. It brings back Tailwind's owncollapseutility (visibility: collapse), and every collapse disappears.
Phones
Below md the app is laid out for a phone, and a touch screen gets thumb-sized targets. The rules:
-
Width and pointer are separate.
- Layout differences between a phone and a desktop use the width variants at the call site (
max-md:,md:). - How big a thing is to a finger uses the pointer:
Styles/touch.cssunder@media (pointer: coarse), andpointer-coarse:at a call site. - A mouse matches none of it, so desktop keeps daisyUI's sizes (
Mobile/DesktopUnchangedTestsholds them). - A window at most 30rem tall (a phone held sideways) is the
short:variant.
- Layout differences between a phone and a desktop use the width variants at the call site (
-
touch.cssis plain CSS in Tailwind's utilities layer, so likeneo.cssit beats daisyUI's sublayers. It sets daisyUI's own size variables:- buttons, tabs, inputs and selects are 44px tall;
- extra small buttons and the badges that act are 36px, with a transparent
::afterthat reaches 44 (5px around the padding box); - checkboxes and radios are 24px, toggles and range thumbs 28;
- field text is 16px, so iOS doesn't zoom into a focused field.
Its
touch-targetutility gives a small link or button a 44px hit area. It can't be used on something that clips its own overflow (atruncated name takespointer-coarse:py-3.5instead), nor on a daisyUI tooltip, which draws its arrow with::after(NerdTip takes minimum sizes). -
Every target has a 44px hit area on touch, with 8px between targets in a row (
pointer-coarse:gap-2). The phone sweep fails anything less. -
Overlays on a phone rise from the bottom.
DModal Placement="ResponsiveBottom"is a sheet below md and a centred dialog from md. Every DModal has a visible close button (ShowClose, named byCloseText).DDropdown SheetOnNarrowturns its content into a bottom sheet.Components/PhoneSheet.razorshows what opens in place on a desktop (the composer, a reply, a quote, an edit) as a sheet on a phone.- All are capped by
dvh, and the app itself ish-dvh.
-
The Back button closes the newest open overlay instead of leaving the page.
- Overlays register through
IDOverlayHost(Components/Daisy, cascaded fromMainLayout):DModalandDDropdownthrough the cascade;- the nav menu,
PhoneSheetand the full-screen globe throughServices/OverlayService.cs.
main.jsmarks a real Back press (a capture-phasepopstate), since Blazor can't tell it from the app's own navigation, which closes every overlay and goes on.- No history entries are pushed.
- Overlays register through
-
What can't be undone asks first through
Services/ConfirmService.cs(Ask, shown byConfirmHostinMainLayout): deleting a post, taking it off a wall, muting, blocking, leaving a group, dropping a scheduled post and signing out. -
On a touch screen:
- a tap on a post opens its thread (
main.js,data-threadon the card, itsdata-thread-link), and cards are pinned to the globe with a mouse only; - a tap on a nerd-stats trigger opens its rows in a sheet (
NerdTip,AppStatusService.CanHover); - pictures open in
Components/MediaViewer.razor.
- a tap on a post opens its thread (
-
The feed on a phone:
- a card's actions are five equal cells (Reply, Boost, Favourite, React, More). Bookmark, the thread and the nerd stats' Details are in More, and the author's picture is in the header;
- a new post starts from a floating button;
- the globe's banner opens full screen, and a phone held sideways opens it full screen from the tabs;
- the feed tabs show their names and fade at the edge where more wait (
edge-fade-x,data-scroll-x).
daisyUI Blazor components (Components/Daisy/)
Every daisyUI component has a D-prefixed wrapper (DButton, DModal, DDropdown, DInput, ...), grouped by
daisyUI's categories into folders whose namespaces are imported in _Imports.razor. /styleguide (not linked) renders
all of them in every theme. When you add or change one:
- Map each enum to its classes in a switch with whole literal class names.
- Value-holding fields derive from
DInputBase<TValue>, Blazor'sInputBase, so@bind-Valueand EditForm validation work. Everything else derives fromDComponentBase(Class, pass-through attributes,Cx(...)). - Open/active state lives in C# (
@bind-IsOpen,@bind-Active) and is rendered with daisyUI's*-openmodifier classes. No JS interop.- What daisyUI does with scripts has a script-free equivalent here:
DCheckbox.Indeterminaterendersaria-checked="mixed", andDCarousel's navigation links to the slides' ids, which Blazor scrolls to. DCalendaris the one exception: it wraps the vendored Cally web component (wwwroot/vendor/cally.js).
- What daisyUI does with scripts has a script-free equivalent here:
- Images and links in
/styleguidestay local (wwwroot/imgs/styleguide/). - Don't name a parameter after an HTML attribute (
Title,Style,Id,Label, ...). Blazor matches attributes to parameters without regard to case, so the parameter would swallow the attribute. - Components don't use
LocalizerorCascadingState; their user-visible strings are parameters.
Architecture
Startup (Program.cs).
- DI registration happens here.
- The named
HttpClient"default" usesApiBaseAddressas its base address. It falls back to the host's base address when that setting is empty. SetDefaultCulture()(Extensions/ExtensionMethods.cs) runs before the app starts. It picks the culture from the savedPublicCacheData, or on a first visit from the browser language.- Only English (
en-GB) and Italian (it-IT) have resources; any other language gets English. - Settings → General changes the language, saves it, and reloads the app.
LayerComponents/CascadingState.razor wraps the router in App.razor. It is the app-wide state object. It handles:
PublicCacheData(page settings: theme colours, dark/light/system theming, language), persisted in localStorage;- the theme, applied through
AppStatusService.ApplyTheme(wwwroot/js/theme.js); IsOnline/IsOffline, polled every 10 seconds;- the session:
IsSignedIn,Personas(the root's),PersonaIdandPersona(its MastodonAccount), withLoadSession,SwitchPersonaandSignOut. A persona change re-renders every subscriber; pages comparePersonaIdand reload what belongs to the persona. The JWT is renewed hourly when needed; ProcessError/ProcessWarning, which log throughILoggingServiceand show a toast;LogFromJs, which JS calls back into through aDotNetObjectReference.
Components and pages inherit LocalizableComponentBase, the equivalent of b2b.next's WidmannComponentBase. It
supplies:
CascadingState,Localizer,NavigationandToast;IsLoading, which starts true, andIsDefaultDisabled;AfterRenderAsyncJobs, run once after the next render;WhenOnline/StartOnlinePolling.
PagesBase is an empty subclass of it that nothing uses. Never redeclare the base's members in a component.
UI feedback.
Services/ToastService.csis the snackbar: the SUtility extensionsAddResponseError(WebResult)(silent on 410/cancelled; connectivity failures show as warnings),AddResponseError(string),AddResponseSuccess(closes after 5 s),AddWarningandAddException.Components/ToastHost.razor, placed inMainLayout, shows the messages.Components/ErrorViewer.razorshows in-page errors: the cascadingEditContext's validation messages,AdditionalErrorandAdditionalErrors.ConfirmServiceasks before what can't be undone (see Phones).
HTTP (Services/IHttpService.cs).
- Routes are constants in
Models/APIs.cs(b2b.next naming:GET_/POST_/DELETE_,_M_for routes built from parameters), relative toApiBaseAddress. - The route picks the credentials:
clientapi/sends the root's JWT,api/the current persona's Mastodon token (exchanged when missing, exchanged once more and retried when PrivaPub refuses it),oauth/nothing. - It also picks the JSON:
SUtility.MastodonSerializer(snake_case,MastodonJsonContext) forapi/andoauth/,SUtility.DefaultSerializer(camelCase, enums by name like PrivaPub,ClientJsonContext) forclientapi/. A payload can be an object (JSON), name/value pairs (a form) or aFunc<HttpContent>(multipart), built once per attempt. - Auth levels:
Get/Post/Put/Patch/Deleteneed credentials and end the session when PrivaPub refuses them;GetAnon/PostAnonadd them when there are some;*TotallyAnonsend none (the login must not carry a JWT: PrivaPub redirects it). retryOnErrorbackoff: 1, 2, 4, 8, 16, 29 s, then 60 s, for at most 10 minutes.- Each request has its own timeout (
Measure): 100 s, or 10 minutes for a multipart body (an upload); theHttpClient's own is off. - Failures never throw. They come back as responses carrying an invalid
WebResult, with anErrorCodefromModels/FailureCodes.cs; a cancelled request comes back as HTTP 410. - Read failures with
ReadWebResult(it understandsWebResult, validation ProblemDetails and Mastodon's{"error": ...}) and bodies withDefaultReadFromJsonAsync/MastodonReadFromJsonAsync; a body that doesn't fit comes back as the default and is written to the browser console.PageCursors()readsmax_id/min_idfromLink. - Every request PrivaPub answers is recorded in
RequestStats(method, route template, status, duration, size, rate limit headers; never a body or a token), for the nerd stats. - PrivaPub's
WebResultgetsIsInvalidfromExtensions/WebResultExtensions.cs, a C# 14 extension property.
PrivaPub wiring.
- One sign-in (
Services/AuthService.cs,Pages/Login.razor): the root signs in on/clientapi/user/login, then each persona the client uses gets its own Mastodon token in exchange for the JWT (PrivaPub'sPersonaExchange, RFC 8693 on/oauth/token, first-party client idAppConfiguration:ClientId).AuthDatakeeps the JWT and the persona tokens; logout revokes every persona token, then forgets the session and IndexedDB. - Services (
Services/):TimelineService(every feed asFeedPages ofFeedPosts, paged bymax_id/min_id; circles are read as ids from/clientapiand hydrated through/api/v1/statuses?id[]=; located posts come from/clientapi/post/nearbyand have no Mastodon actions),StatusService(publish, favourite, boost, bookmark, delete, threads, mute, block, poll votes, emoji reactions through Pleroma's/api/v1/pleroma/statuses/:id/reactions, joining and leaving remote events through/api/privapub/v1/statuses/:id/join|leave; located and group posts go through/clientapi/post/insert, and a located post's author deletes it through/clientapi/post/delete, its card's one action),AccountService(profiles, relationships, follow, block, mute, follow requests,/api/v2/search, whose handles and URLs PrivaPub resolves),ListService(the persona's lists and their members; members are only accounts it follows, found withaccounts/search?following=true),FilterService(the persona's v2 filters, their keywords and filtered posts),DiscoveryService(hashtags and following them, trends, the directory),PortabilityService(Mastodon's CSV exports and imports),AdminService(/clientapi/moderatorand/clientapi/admin),MediaService(uploads),GroupService,InstanceServiceandProvenanceService. - Reactions and votes are public (owner decision, PrivaPub's ROADMAP): before a persona's first reaction or poll
vote,
PublicNoticeServiceasks it once (PublicNoticeHostinMainLayout) and remembers the persona in localStorage (PublicActionNotices). Anything else that makes a persona's act visible to others gets the same notice, with its ownPublicAct: joining an event (owner decision 2026-10-05) is asked once more, since the event's server shows who takes part. An event card shows the persona's participation (privapub.event.participation: pending, accepted, rejected) with Join or Leave, except for events by invitation or taken on another site (join_mode). - What a card shows of other platforms: custom emoji (
Helpers/CustomEmojis.cs: a post's or account's:shortcode:in its text, name, warning, bio and fields, as the picture the server listed, never inside a tag), a threadiverse post's downvotes next to its favourites, blurhash placeholders until a picture loads (wwwroot/js/blurhash.jspaints any[data-blurhash]: a picture's until it loads, again when its source changes, and for good behind the sensitive-media button), a picture's focal point (object-position), and an event's online link, participants and status. A picture, video or sound that fails to load says "Media unavailable" with "Open original" (data-media-unavailable), and a gifv plays only on a tap underprefers-reduced-motion. - Profiles and search (
Pages/Profile.razorat/account/{id},Pages/Search.razorat/search?q=): a card's author and a notification's account open the profile in the app; "Open original" is the only way to the remote site. A profile shows the posts the account pins above its posts (pinned=true: what an account elsewhere features); the persona pins and unpins its own public and unlisted posts from the card's menu. An account that moved says where to (Account.Moved, which PrivaPub fills once the new account names the old one), linking the new account's profile. Another's profile and posts can be reported (Components/ReportDialog.razor,/api/v1/reports): a category, words, and for a remote account a copy to its server, which PrivaPub sends from its own actor, never naming the persona. Who liked or boosted a post opens from its card's menu (Components/InteractedByDialog.razor). - Walls (Smithereen's, FEP-400e): a post written on someone's wall says whose (
privapub.wall,data-wall, linking that profile); one written on the persona's own wall is taken off from the card's menu (DELETEon the status, which PrivaPub turns into aRemovethat Smithereen takes for a deletion). Only the persona's followers may write there. A card in a fixed-height flex column withoverflow-hiddenneedsflex-none, or it collapses to nothing. - Groups (
Pages/Groups.razorat/groups): the persona's communities and circles (GroupService,/clientapi/group): made (a circle unless it is a community, with an invitation code and an optional password), joined by invitation and left; the ones it runs edited, their invitation shown, the requests to join let in or declined, members taken out. Only a group's owner and moderators see who is in it. - Lists (
Pages/Lists.razorat/lists): made, renamed, given a replies policy and made exclusive (their members leave the home feed) there, filled from the accounts the persona follows; a followed account's profile has a Lists menu too. A list is read as the feed's Lists tab (FeedFilter.ListId). Lists never leave PrivaPub. - Filters (
Pages/Filters.razorat/filters, linked from Settings): PrivaPub marks every status with the filters it matches (Status.Filtered), whatever their context; a page tells each card where it is (Content.FilterIn: home and lists, notifications, public feeds, threads around the opened post, profiles; none for favourites, bookmarks, conversations and search), and the card leaves the post out (hide), folds it behind the filter's title (warn) or blurs its media (blur). - Articles fold in a feed (
Content.IsFoldedArticle): an Article or a Page with its title, or a titled post longer than a few paragraphs (WriteFreely sends Notes with a name), shows its cover, its excerpt and a Read button; the post opened in its thread shows whole. - The composer (
Components/Composer.razor) writes a post, a reply (InReplyTo), a quote (Quoting, offered on a card when the server says the persona may quote it) or an edit of the persona's own post (Editing); a post can hold a poll instead of media.- Media are uploaded as soon as they are picked (
Services/MediaService.cs,Models/UploadMedia.cs):- each is streamed from the browser's file, and only a 320 px thumbnail (
RequestImageFileAsync) is kept to show it; - each shows its state (
data-upload-state: uploading, processing, ready, or failed with Retry); - audio and video PrivaPub answers 202 for are followed (
GET /api/v1/media/:id, 206 until ready); - the ids are kept, so a post that fails never uploads its media again;
- the types and sizes accepted are PrivaPub's own (
/api/v2/instance,MediaService.Limits); - a description changed after the upload is PUT before the post.
- each is streamed from the browser's file, and only a 320 px thumbnail (
- Alt text: publishing a picture without a description asks once (
data-alt-reminder, "Publish anyway"), unless the reader turnedPageSettings.RemindAltTextoff in Settings → General. - Edits send the whole post, as Mastodon wants it: its words and warning from
/source, its own language and sensitive flag, the media it keeps or adds (media_ids; removing them all is[]), and the descriptions changed (media_attributes). Its visibility and poll stay. - A new post's media are sensitive when the persona's "always mark media as sensitive" (
source.sensitive) says so. A mention or hashtag being written at the end of the words is offered what PrivaPub already knows (/api/v2/search, never resolving), once typing pauses. An edited post's card says so, and its versions open from there (/statuses/:id/history, newest first; PrivaPub keeps a remote post's earlier versions from its edits and from Pleroma'sformerRepresentations).
- Media are uploaded as soon as they are picked (
- Threads (
Pages/ExpandMessage.razorat/expand/{id}): opening a remote thread makes PrivaPub read its replies from their servers (its FEP-7888context, elsereplies), so the page reads the thread again after 4 and 15 seconds and adds what was found, in the thread's order. - Interaction policies (GoToSocial's, and FEP-5624's
canReplyon a PeerTube video whose comments are moderated): a reply or boost whose target's author must approve it shows so on its card (privapub.approval: pending, then nothing once approved, or rejected); one the policy shuts out is refused by PrivaPub (422) and shown as an error. - Settings (
Pages/Settings.razor,Components/Settings/): the login itself (AccountEditor: its password changed, or the whole of it deleted, every persona with it, through/clientapi/user/update/passwordand/clientapi/user/delete; the client then signs out), the persona's profile (ProfileEditor:update_credentialsas multipart, its words as written fromAccount.Source, pictures (streamed from the file, and removed withDELETE /api/v1/profile/avatar|header), fields, locked, bot, discoverable, indexable and posting defaults; the composer starts a new post at its default visibility), its mutes, blocks and blocked servers (MutesAndBlocks), andDataTransfer: follows, lists, blocks, mutes, blocked servers and bookmarks exported and imported as the CSV files Mastodon writes, so a persona moves between servers. An import resolves each row through PrivaPub and acts one row at a time; it can be stopped. - Administration (
Pages/Administration.razor,Components/Admin/, for moderators): reports, then for administrators the servers blocked for everyone, the federation statistics and the backups. PrivaPub has no admin list of users, and adding an admin endpoint waits for the owner, so the Users section stays empty. - Backups (
Components/Admin/BackupsPanel.razor,/clientapi/admin/backups; owner decision 2026-10-07): the server's backups (nightly, before each deploy, made here, uploaded), with what runs and the last restore's report.- A download asks for the password and gives a link good for ten minutes, a plain anchor, so the browser saves the tar to disk.
- An upload never passes through .NET's memory:
wwwroot/js/transfer.jsPUTsfile.slicepieces at the offset PrivaPub has, and carries on from what PrivaPub says after a refused or lost piece. - A restore asks for the password and the server's host typed out, and says what it means. PrivaPub stops, restores as it starts again and ends every session, so the page shows it restarting until the ended session sends it to sign in.
- Notification policy (
Components/Settings/NotificationPolicyEditor.razor, in Settings and at/notifications/filtered): what notifications from people the persona does not follow, people who do not follow it, new accounts, private mentions it did not ask for and limited accounts become (accept, filter, drop;/api/v2/notifications/policy), and the filtered ones, one request per account, let in (with that account from then on) or dismissed. The Notifications tab links there while requests wait. - Scheduled posts (
Pages/Scheduled.razorat/scheduled): the composer's clock button gives a Mastodon API post a time (scheduled_at, at least five minutes ahead; located and group posts have none); the page moves or drops them. - Explore (
Pages/Explore.razorat/explore): trending hashtags, posts and links (PrivaPub's, from public posts it holds), the directory, and the hashtags the persona follows. A hashtag's feed tab follows it too. - Mastodon DTOs are client-side, in
Models/Mastodon/(snake_case)./clientapiDTOs come fromPrivaPub.ClientModels. - Where a post is (
InstanceService.Locate,Models/FeedPost.cs): its own place (Pixelfed's,privapub.place), its event's venue, the reader for a located post, its author's server (to 0.1°, or a point in its country fromHelpers/CountryPoints.cswhen DB-IP located it only to a country), or, for a CDN-fronted server, its CDN's group (LocationSource.Cdn: no point, aCdnKeyand the placeBeforethe CDN). Server descriptions are cached a day in localStorage (ServerInfos); a server's weekly history (/instances/:host/history) and a CDN's page (/cdns/:key) are read on the first hover and kept for the session. PrivaPub's own host is the signed-in persona's account host, since the API may be reached under another name. - The feed page (
Pages/Index.razor):FeedTabs,Content(the card, which does its own actions),Composer,GlobePanel. Leaving it keeps the feed inServices/FeedMemory.cs(its posts, waiting posts, cursors and scroll, ten minutes, for the same feed of the same persona), so coming back from a thread or a profile shows it again at once without reading it anew. Older pages load as the end comes near (wwwroot/js/feed.js). Newer ones come through PrivaPub's streaming API (Services/StreamingService.cs: one WebSocket, the persona's token as its protocol, never in a URL) for home, lists, local, federated, hashtags and notifications, and wait behind a "new" button; a deletion or an edit it tells applies at once. Other feeds, and any feed while the stream is down, are polled every 45 s while visible.- At volume: the list is a
<Virtualize>(only the cards near the view are rendered), and a card re-renders only when its own events run or its render key changes (Content.RenderKey: the post, its status, notification, conversation, place, grouping, where it is shown, the persona and the connection). Anything that changes what a card shows from outside it must replace one of those objects or be added to the key; mutating one in place leaves the card as it was. Without these a feed took seven minutes to reach a thousand cards and held 900 MB at two thousand.
- At volume: the list is a
- The globe (
wwwroot/js/globe.js, an ES module imported byGlobePanel) runs on globe.gl, vendored inwwwroot/vendor/globe/with its textures andcountries.json(SOURCES.mdhas versions, licences and hashes; the service worker never precaches it). It looks at the spherical mean of the located posts in view, pulses and draws an arc to a hovered post, honoursprefers-reduced-motion, and draws only while something moves (idle, it costs no GPU time;wake()before anything that animates).-
Map. Each pixel computes its own map coordinates from its point on the sphere (
sharpen), so the poles don't pinch; the maps wrap horizontally and get 8× anisotropic filtering (keepSharp). The day texture is NASA's, its seam repaired bytools/globe/prepare-day-texture.py(dev-only, needs Pillow). -
Sun.
wwwroot/js/sun.js(pure functions of a date: the subsolar point, Earth–Sun distance, seasons, a place's elevation, phase of the day, solar time and day length) lights the globe in the shader: the day map shaded by the Sun's height and distance, city lights on the night side, a twilight blend between. It shows now (refreshed every 30 s), or the moment of the hovered, focused or pinned post (data-post-aton the card; a click pins a card,data-globe-pinned), and tellsGlobePanelthroughSunChanged, which shows the moment and its phase at the panel's top and keeps the Sun's numbers as screen-reader text (aria-describedby). The theme changes only the atmosphere and the points. -
Instruments (
wwwroot/js/instruments.js; owner decision 2026-10-06: the nerd stats drawn where they belong, not a table). The globe has no tooltip. What it draws:- the Sun: its ray and bead over the subsolar point, the day/night line and the twilights, the declination, the noon and midnight meridian, and its analemma at this hour to the next equinox or solstice;
- a focused post's place: its horizon, its Sun's height and its day lit on its latitude;
- the tropics, the polar circles and the CDN ring;
- the view's centre and spread, and rings around the posts in view;
- a small orrery in the top left corner, re-anchored to the camera before each render.
The numbers are chips in a DOM overlay (
.globe-instruments,aria-hidden), placed after each frame globe.gl renders (scene.onAfterRender), clear of each other, the moment's caption, the orrery and the legend. The frame rate is a ring around the globe; what is left is a legend in the bottom left. Geometry changes only inside a wake globe.js already made, so an idle globe still draws nothing.- three.js's classes come from objects globe.gl made (
classesOf), neverwindow.THREE, since that would mix two copies. three.js sets itsis*flags on instances, so the lookup checks instances. globe.gl adds its globe on its first update, afternew Globe(), so the parts are built before the first render that finds it. Without the classes, only the ring and the legend remain. - A canvas under 320px tall (a phone's banner) gets the day/night line and the subsolar point only; full screen gets everything.
-
Countries. Land borders as thin paths, and names placed by
placeLabels: largest countries first, once they span enough pixels, away from the globe's edge and clear of each other, in the reader's language (Intl.DisplayNames).countries.jsonis built bytools/globe/prepare-countries.pyfrom world-atlas (Natural Earth). The label renderer ownsdisplay, so labels hide throughvisibility. -
CDN-fronted posts are labels per CDN on a ring at 68°N, never a place; hovering one draws its arc there and a ring where the server was before the CDN. The posts' places reach it in one call per feed change; cards are matched by
data-post-id.
-
- Nerd stats (
Components/Nerd/NerdTip.razor, rows fromNerdRow): a post's ids, times and provenance (read on hover), its author and server with the server's changes of place and CDN week by week, its place or its CDN (how PrivaPub found it, the place before it, the CDN's servers week by week), media and counts; the feed's paging and last request. The globe's are its instruments (see The globe), with no tooltip and no poll.
Localization (Services/CoalescingStringLocalizer.cs).
- Lookup order: this repo's
Resources/AllStrings.resx(+.it.resx), thenFieldsNameResource, thenErrorsResource. - A missing key renders as the key itself, formatted with its arguments, so a typo fails silently.
- The class lives in namespace
collAnon.Client.Services, a leftover from another project. Resources/ErrorMessages.resxis read by[Required]/[StringLength]throughErrorMessageResourceType. A new key needs itspublic static stringproperty inErrorMessages.Designer.cstoo, or validation throws at runtime.
Client storage comes in two layers:
- localStorage (Blazored.LocalStorage, camelCase JSON) holds
AuthData,PublicCacheData,FeedFilterand the server cacheServerInfos, keyed bynameof(Type). - IndexedDB (DnetIndexedDb, database
data) is reached throughIStorage. Its schema is declared inGenericExtensions.AddIndexedDb(), and you must bumpWithVersionwhen you change it. - The schema is at version 3: the
ClientLogsstore thatIStorage.AddLogwrites (version 2 added it; version 3 left the mock feed'sMessagestore out).
Auth. TokenAuthStateProvider holds AuthData (localStorage, cached in memory) and builds the auth state from
it: the root's name, its policies as claims, and the current persona. Pages that need a session carry
[Authorize]; RedirectToLogin sends the reader to /login?returnUrl=….
JS interop.
wwwroot/main.jsdefineswindow.*helpers.Services/AppStatusService.cscalls them, mostly through the synchronousIJSInProcessRuntime.- Each helper reports its errors back through
window.logFromJs. - The other scripts (IndexedDB, HeadElement, rxjs) are loaded by
<script>tags inwwwroot/index.html; the feed's modules (js/feed.js,js/globe.js) are imported on demand throughIJSObjectReference.
PWA. Published builds use wwwroot/service-worker.published.js, and service-worker.js is the dev version.
Development rules
These rules are adapted from the owner's b2b.next project. They are enforced by review: the build doesn't check them, so follow them in every change.
| Area | Rule |
|---|---|
| All | var everywhere; uninitialised locals are var x = default(T); |
| All | Primary constructors for DI (class Foo(IBar bar)), not constructor + fields |
| All | Every async method takes a CancellationToken as its last parameter |
| All | Early return on error: guard, handle, return; never if/else for success vs failure |
| Models / state | Lists and arrays = [], never null; no = string.Empty / "" defaults; explicit enum defaults |
| Components | No @{ } blocks in markup: locals become @code members |
| Components | [Inject] in @code, never @inject |
| Components | Disable controls with IsDefaultDisabled (plus local conditions), never bare offline state |
| Components | Every text/number input declares autocomplete |
| Services | Task<WebResult> for mutations, Task<List<T>> ([] on error) for lists, Task<T> with a default for values |
| Localization | Every user-facing string through Localizer, its key in both AllStrings.resx and AllStrings.it.resx |
CancellationToken. It goes on every async method in services, CascadingState and helpers, defaulting to
default; pass it on to what you call. Exempt: Blazor lifecycle overrides, [JSInvokable] methods, framework overrides
(GetAuthenticationStateAsync), and private UI handlers bound from markup.
State initialisation. Initialise page and component state (= new(), = []) and bind it directly. No passthrough
getters and no ?. chains over state that can't be null:
List<FeedPost> posts = []; // DO
@posts.Count // DO
@(posts?.Count ?? 0) // DON'T
= "" is allowed only as a documented exception, with the reason in a comment (e.g. a decorative image's Alt).
Pages that load data. Pages fetch in LoadData and keep lifecycle concerns in the lifecycle method:
protected override async Task OnInitializedAsync()
{
if (CascadingState.IsOffline)
{
WhenOnline(LoadData);
StartOnlinePolling();
IsLoading = false;
return;
}
await LoadData();
IsLoading = false;
}
- Reuse the base
IsLoading; don't add per-section loading flags. - A component that binds
IsDefaultDisabledmust setIsLoading = falseonce it is ready, even if it loads nothing; otherwise its controls stay disabled. - Never wrap a service call in try/catch. Services already catch and log, and return an invalid
WebResult. Branch onresult.IsInvalidinstead:
var result = await StatusService.Delete(Status.Id);
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
Toast.AddResponseSuccess(Localizer["Message deleted."]);
await OnDeleted.InvokeAsync(Post);
Client services follow b2b.next's two patterns (see its StoreService):
- Create
var result = new WebResult();, callhttpServiceinside a try/catch, and on a non-success statusresult = await response.Content.ReadWebResult(response.StatusCode, localizer, ct). Log withILoggingService. - Return
result(mutations) or[](lists), and setresult.Dataon success. - POST bodies are JSON payloads for
/clientapiand the Mastodon API (snake_case DTOs), forms for/oauth.
In-page errors. ErrorViewer takes AdditionalError for one message and AdditionalErrors for a list. Never
join a list into one string with <br/> or \n.
Autocomplete values:
autocomplete="off"for search, filter and free text;new-passwordwhen setting a password;one-time-codefor OTP (DOtp sets it);usernameandcurrent-passwordon the login form, so password managers fill it;- inside
Components/Daisy, attributes pass through from the caller.
Localization:
- Keys are English source strings. Grep both resx files for an existing key before adding one; match keys exactly.
- Never add a key that differs from an existing one only by case ("users" next to "Users"): resource lookups collide on them and one of the two silently shows the other's text. Reuse the existing key.
- Use
Localizer[key, args], neverstring.Format(Localizer[key], …). Don't write.Value. - Enum members shown through
Localizer[value.ToString()]are keys too: when you add a member, add its key. - Language names in the language picker stay in their own language.
Formatting. Date formats come from SUtility.dateTimeFormat / timeFormat / dateTimeFormatExt. Relative times
and sizes come from GetPassedTime / GetFileSize (Extensions/GenericExtensions.cs). No inline format strings for
display.
JSON. Register every /clientapi or localStorage type in ClientJsonContext.cs (camelCase: theme.js reads
pageSettings straight from localStorage), every Mastodon API type in MastodonJsonContext.cs (snake_case).
Wiring a feature to PrivaPub:
- For
/clientapi, add the request/response DTOs toPrivaPub.ClientModelsin the SocialPub repo:View*for responses,*Requestfor requests,*Formfor forms with validation. Lists= [], no string defaults. For the Mastodon API, add the shape toModels/Mastodon/. - Register them in
ClientJsonContextorMastodonJsonContext, and the route inModels/APIs.cs. - Add a client service method that calls
IHttpServiceagainst the server's route, following the patterns above. - Wire the page with early returns, toasts and/or an
ErrorViewer.
Not adopted from b2b.next, on purpose:
- The
tw:Tailwind prefix. b2b.next needs it next to MudBlazor's CSS; here daisyUI is the only component CSS. - Server-only rules: no 5XX responses, the controller pattern,
IOptionsMonitor, data access and caching. - b2b.next-specific features: Excel import/export, password policy, legacy porting rules, the
{culture}route placeholder (PrivaPub's routes are absolute/clientapi/...), and the release/API-status worker. - Mandatory
/// <summary>on every[Parameter]. Document only what isn't obvious from the name.
Deployment
Both workflows check the repo out with a plain git fetch from this Gitea, not actions/checkout, because the runner
would download that action from github.com. Never add a uses: step.
.gitea/workflows/deploy.yml runs on a v* tag or a manual dispatch, on a self-hosted runner that is also the web
host. The steps:
- Publish the site.
- Write
build.json(commit, ref, time). - Snapshot the live directory to
/var/backups/decepub.thepra.dev. rsync --deleteinto/var/www/decepub.thepra.dev.- Check that
build.jsonserves the new commit and that a deep client route returns 200 (the SPA fallback). Otherwise, roll back to the snapshot.
The nginx vhost and headers are in deploy/nginx/ (it sends X-Robots-Tag: noindex, nofollow), and
deploy/max/setup.sh is the one-time root setup on the server. If you add a file that must never be cached, add it to the expires -1 locations in the vhost.
Conventions
- Indent with tabs.
Nullableis disabled andImplicitUsingsis enabled.- Global Razor usings are in
_Imports.razor. - Styling uses the D components, Tailwind utilities and the
neo-*utilities. Usegap-*rather thanspace-x/y-*on flex containers; the feeds useflex-col-reverse, whichspace-*gets wrong. SUtility.IfTrueThen(cond, "class")is the helper for conditional classes.