Files
buzz/desktop/src/shared/api/relayClientShared.ts
Taylor Ho 83ca595ada fix(desktop): preserve theme when opening communities (#5266)
**Category:** fix
**User Impact:** Previously selected community themes are preserved when
opening a relay through onboarding, while first-time theme migration
still completes for communities with no saved theme.

**Problem:** During community initialization, desktop queried theme
history before establishing live delivery. If a replacement event
arrived while an empty history query was in flight, the client could
incorrectly treat the theme as absent and publish the default over the
user's saved selection.

**Solution:** Subscribe before fetching history, expose whether live
readiness reached EOSE, flush buffered live events before resolving
EOSE, and retain the newest delivered replacement through hydration.
Seed the inherited/default theme only when both live and history
snapshots reach EOSE with no valid or unreadable event; subscription
failures, CLOSED, readiness timeout, relay failure, and unreadable
events fail closed without publishing.

<details>
<summary>File changes</summary>

**desktop/src/shared/api/relayClientSession.ts / relayClientShared.ts /
relayClosedRecovery.ts**
Distinguish EOSE from CLOSED/timeout readiness and flush buffered events
before resolving an EOSE fence.

**desktop/src/shared/theme/CommunityThemeController.tsx**
Seed and complete first-community migration only for confirmed absence;
uncertain hydration remains non-publishing.

**desktop/src/shared/theme/communityThemePreference.ts**
Keep the inherited appearance for the first migrated community and the
stable default for later empty communities.

**desktop/src/shared/theme/communityThemeSync.ts**
Arbitrate live and history results into valid, confirmed-absent,
invalid, or unavailable hydration outcomes.

**Tests**
Cover EOSE/CLOSED readiness, subscription failure, timeout, unreadable
and live-racing events, no-op initialization, and first-to-later
community fallback isolation.

</details>

## Reproduction steps

1. Save a non-default appearance for a community relay.
2. Remove the community locally, then open the same relay again through
onboarding.
3. Arrange for the saved replacement event to arrive live while the
initial history query returns empty.
4. Confirm the saved appearance remains selected and the client does not
publish the default theme over it.
5. On an account with no theme records, open a first empty community and
confirm its inherited appearance is migrated; open a later empty
community and confirm it starts from the stable default.

## Validation

- Pre-push desktop checks, typecheck, and full desktop tests: passed at
`f79556b0e`
- Focused theme/relay readiness tests: 38 passed
- Desktop file-size ratchet and diff check: passed

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Signed-off-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz>
2026-08-11 08:21:34 -07:00

132 lines
3.9 KiB
TypeScript

import type { RelayEvent } from "@/shared/api/types";
/**
* Observable connection state for the relay singleton.
*
* - `idle` — never tried to connect yet (post-init, pre-community).
* - `connecting` — initial socket + AUTH handshake in flight.
* - `connected` — socket open and AUTH'd.
* - `reconnecting` — socket dropped, waiting for the backoff timer.
* - `stalled` — socket is *open* per the WS layer but no inbound frames
* for a long time (half-open socket / VPN split-brain). We
* surface this so the UI can warn even though tungstenite
* hasn't reported anything wrong yet.
* - `disconnected` — final/terminal disconnect (auth rejected, community
* switch, etc.) — no auto-reconnect scheduled.
*/
export type ConnectionState =
| "idle"
| "connecting"
| "connected"
| "reconnecting"
| "stalled"
| "disconnected";
/** True when the UI should surface a "connection lost" indicator. */
export function isRelayConnectionDegraded(state: ConnectionState): boolean {
return (
state === "reconnecting" || state === "stalled" || state === "disconnected"
);
}
export type RelaySubscriptionFilter = {
ids?: string[];
kinds: number[];
limit: number;
authors?: string[];
since?: number;
until?: number;
} & Partial<Record<`#${string}`, string[]>>;
type HistorySubscription = {
mode: "history";
events: RelayEvent[];
resolve: (events: RelayEvent[]) => void;
reject: (error: Error) => void;
timeout: number;
};
type FirstEventSubscription = {
mode: "first";
onEvent: (event: RelayEvent) => void;
resolve: (event: RelayEvent | null) => void;
reject: (error: Error) => void;
timeout: number;
};
export type LiveSubscriptionReadiness = "eose" | "closed" | "timeout";
type LiveSubscription = {
mode: "live";
filter: RelaySubscriptionFilter;
onEvent: (event: RelayEvent) => void;
resolveReady?: (readiness: LiveSubscriptionReadiness) => void;
lastSeenCreatedAt?: number;
/**
* Lower bound of a reconnect backfill window that has not yet completed.
*
* Events on the restored live REQ advance `lastSeenCreatedAt` regardless of
* backfill success, so after an exhausted backfill the cursor alone would
* make the next reconnect skip the unresolved older window — silent message
* loss. This floor is pinned when paging starts and cleared only when a
* backfill pass completes; the next replay starts from
* `min(pendingReplaySince, cursor window)`.
*/
pendingReplaySince?: number;
closedRetryAttempt?: number;
closedRetryTimeout?: number;
};
export type PendingEvent = {
event: RelayEvent;
resolve: (event: RelayEvent) => void;
reject: (error: Error) => void;
timeout: number;
};
export type RelaySubscription =
| HistorySubscription
| FirstEventSubscription
| LiveSubscription;
export function sortEvents(events: RelayEvent[]) {
return [...events].sort((left, right) => {
if (left.created_at !== right.created_at) {
return left.created_at - right.created_at;
}
// Same (created_at, id) tiebreak as the cache sort (sortMessages) so a
// history REQ resolves same-second events in a stable, relay-matching
// order. Currently every consumer re-sorts downstream, but keeping the
// two sorts on one invariant avoids a latent ordering drift.
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
});
}
export function getTextPayload(message: unknown) {
if (typeof message === "string") {
return message;
}
if (
typeof message === "object" &&
message !== null &&
"type" in message &&
message.type === "Text" &&
"data" in message &&
typeof message.data === "string"
) {
return message.data;
}
if (
typeof message === "object" &&
message !== null &&
"Text" in message &&
typeof message.Text === "string"
) {
return message.Text;
}
return null;
}