Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[web][contacts] harden session-scoped display state

Neeraj Gupta1d3022d2ca51
diff --git a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
index 87a0b3ae43..6c28d32be4 100644
--- a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
+++ b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
@@ -562,7 +562,7 @@ const ParticipantRow: React.FC<{
userID: participant.id,
email: participant.email,
});
- const label = resolvedDisplay.primaryLabel;
+ const label = resolvedDisplay.primaryLabel || email;
const initial =
resolved.source === "contact"
? resolved.initial
diff --git a/web/apps/photos/src/components/Collections/CollectionShare.tsx b/web/apps/photos/src/components/Collections/CollectionShare.tsx
index 254f22e1d0..78d0a2ebc5 100644
--- a/web/apps/photos/src/components/Collections/CollectionShare.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionShare.tsx
@@ -317,7 +317,7 @@ const ResolvedEmailRowLabel: React.FC<ResolvedEmailRowCommonProps> = ({
return (
<RowLabel
startIcon={<Avatar email={email} {...{ user, emailByUserID }} />}
- label={fallbackLabel ?? resolved.primaryLabel}
+ label={(fallbackLabel ?? resolved.primaryLabel) || email || ""}
/>
);
};
@@ -344,7 +344,7 @@ const ResolvedEmailRowButton: React.FC<ResolvedEmailRowButtonProps> = ({
fontWeight="regular"
disabled={disabled}
onClick={onClick ?? (() => undefined)}
- label={fallbackLabel ?? resolved.primaryLabel}
+ label={(fallbackLabel ?? resolved.primaryLabel) || email || ""}
startIcon={<Avatar email={email} {...{ user, emailByUserID }} />}
endIcon={endIcon}
/>
@@ -356,7 +356,7 @@ const ResolvedEmailText: React.FC<{
fallbackLabel?: string;
}> = ({ email, fallbackLabel }) => {
const resolved = useResolvedContactDisplay({ email });
- return <>{fallbackLabel ?? resolved.primaryLabel}</>;
+ return <>{(fallbackLabel ?? resolved.primaryLabel) || email || ""}</>;
};
type SharingDetailsProps = Pick<
@@ -1396,7 +1396,7 @@ const ManageParticipant: React.FC<ManageParticipantProps> = ({
{...{ open, onClose }}
onRootClose={handleRootClose}
title={t("manage")}
- caption={participantDisplay.primaryLabel}
+ caption={participantDisplay.primaryLabel || participant.email || ""}
>
<Stack sx={{ gap: "32px", py: "20px", px: "8px" }}>
<Stack>
diff --git a/web/packages/contacts/index.test.ts b/web/packages/contacts/index.test.ts
index 83eec0d3c2..e087ae3999 100644
--- a/web/packages/contacts/index.test.ts
+++ b/web/packages/contacts/index.test.ts
@@ -55,11 +55,11 @@ describe("resolveContactDisplayFromSnapshot", () => {
expect(resolved.source).toBe("fallback");
});
- test("falls back to Someone when no user or email exists", () => {
+ test("returns an empty label when no user or email exists", () => {
const resolved = resolveContactDisplayFromSnapshot(makeSnapshot(), {});
- expect(resolved.primaryLabel).toBe("Someone");
- expect(resolved.initial).toBe("S");
+ expect(resolved.primaryLabel).toBe("");
+ expect(resolved.initial).toBe("?");
expect(resolved.source).toBe("fallback");
});
});
@@ -137,6 +137,11 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
vi.doMock("ente-base/log", () => ({
default: { info, warn, error },
}));
+ vi.doMock("ente-base/app", () => ({
+ clientPackageName: "io.ente.photos.web",
+ desktopAppVersion: undefined,
+ isDesktop: false,
+ }));
vi.doMock("ente-wasm", () => ({
contacts_open_ctx: vi.fn(async () => ({
update_auth_token,
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
index d7c8577ff0..8b34cdaf81 100644
--- a/web/packages/contacts/index.ts
+++ b/web/packages/contacts/index.ts
@@ -58,6 +58,7 @@ type ContactsState = {
snapshot: ContactsDisplaySnapshot;
listeners: Set<() => void>;
currentSessionKey: string | undefined;
+ sessionGeneration: number;
currentAuthToken: string | undefined;
ctx: ContactsCtxHandle | undefined;
readyPromise: Promise<void> | undefined;
@@ -83,6 +84,7 @@ const state: ContactsState = {
snapshot: emptySnapshot(),
listeners: new Set(),
currentSessionKey: undefined,
+ sessionGeneration: 0,
currentAuthToken: undefined,
ctx: undefined,
readyPromise: undefined,
@@ -123,6 +125,10 @@ const cleanupAvatarURL = (contactID: string, shouldEmit = false) => {
state.avatarFailureUntilByContactID.delete(contactID);
};
+const isCurrentSession = (sessionKey: string, generation: number) =>
+ state.currentSessionKey === sessionKey &&
+ state.sessionGeneration === generation;
+
const clearInMemoryState = () => {
for (const avatarURL of state.avatarURLByContactID.values()) {
URL.revokeObjectURL(avatarURL);
@@ -272,10 +278,16 @@ const useContactsSnapshot = () =>
);
const loadLocalSessionState = async (sessionKey: string) => {
- clearInMemoryState();
+ state.sessionGeneration += 1;
+ const generation = state.sessionGeneration;
state.currentSessionKey = sessionKey;
+ clearInMemoryState();
+ emitSnapshot(false);
const savedRecords = await savedContactDisplayRecords(sessionKey);
+ if (!isCurrentSession(sessionKey, generation)) {
+ return;
+ }
for (const record of savedRecords) {
upsertContact(record);
}
@@ -294,29 +306,42 @@ const syncContacts = async ({
baseURL: string;
authToken: string;
}) => {
- if (!state.ctx) {
- state.ctx = await contacts_open_ctx({
+ let ctx = state.ctx;
+ const generation = state.sessionGeneration;
+ if (!ctx) {
+ const cachedRootKey = await savedWrappedRootContactKey(sessionKey);
+ if (!isCurrentSession(sessionKey, generation)) {
+ return;
+ }
+ const openedCtx = await contacts_open_ctx({
baseUrl: baseURL,
authToken,
userId: userID,
masterKeyB64,
- cachedRootKey: await savedWrappedRootContactKey(sessionKey),
+ cachedRootKey,
userAgent: globalThis.navigator?.userAgent,
clientPackage: clientPackageName,
clientVersion: isDesktop ? desktopAppVersion : undefined,
});
+ if (!isCurrentSession(sessionKey, generation)) {
+ return;
+ }
+ state.ctx = openedCtx;
+ ctx = openedCtx;
const wrappedRootKey =
- state.ctx.current_wrapped_root_key() as WrappedRootContactKey;
+ openedCtx.current_wrapped_root_key() as WrappedRootContactKey;
await saveWrappedRootContactKey(sessionKey, wrappedRootKey);
+ if (!isCurrentSession(sessionKey, generation)) {
+ return;
+ }
} else if (state.currentAuthToken !== authToken) {
- state.ctx.update_auth_token(authToken);
+ ctx.update_auth_token(authToken);
}
- if (!state.ctx || state.currentSessionKey !== sessionKey) {
+ if (!ctx || !isCurrentSession(sessionKey, generation)) {
return;
}
- const ctx = state.ctx;
state.currentAuthToken = authToken;
let sinceTime = (await savedContactsSinceTime(sessionKey)) ?? 0;
@@ -327,7 +352,7 @@ const syncContacts = async ({
BigInt(sinceTime),
CONTACT_DIFF_LIMIT,
)) as RemoteContactRecord[];
- if (state.currentSessionKey !== sessionKey) {
+ if (!isCurrentSession(sessionKey, generation)) {
return;
}
if (diff.length === 0) {
@@ -346,7 +371,7 @@ const syncContacts = async ({
}
if (didChange) {
- if (state.currentSessionKey !== sessionKey) {
+ if (!isCurrentSession(sessionKey, generation)) {
return;
}
await saveContactDisplayRecords(
@@ -365,6 +390,10 @@ export const ensureContactsReady = async ({
state.lastReadyInput = { userID, masterKeyB64 };
const authToken = await savedAuthToken();
if (!authToken) {
+ state.sessionGeneration += 1;
+ state.currentSessionKey = undefined;
+ clearInMemoryState();
+ emitSnapshot(false);
return;
}
@@ -456,7 +485,10 @@ const inferImageMimeType = (bytes: Uint8Array) => {
const ensureProfilePictureLoaded = async (contactID: string) => {
const contact = state.contactsByID.get(contactID);
- if (!contact?.profilePictureAttachmentID || !state.ctx) {
+ const ctx = state.ctx;
+ const sessionKey = state.currentSessionKey;
+ const generation = state.sessionGeneration;
+ if (!contact?.profilePictureAttachmentID || !ctx || !sessionKey) {
return;
}
@@ -475,9 +507,12 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
return;
}
- const load = state.ctx
+ const load = ctx
.get_profile_picture(contactID)
.then((bytes: Uint8Array) => {
+ if (!isCurrentSession(sessionKey, generation) || state.ctx !== ctx) {
+ return;
+ }
const blob = new Blob([bytes], {
type: inferImageMimeType(bytes),
});
@@ -488,6 +523,9 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
emitAvatarURL(contactID);
})
.catch((error: unknown) => {
+ if (!isCurrentSession(sessionKey, generation) || state.ctx !== ctx) {
+ return;
+ }
state.avatarFailureUntilByContactID.set(
contactID,
Date.now() + AVATAR_FAILURE_TTL_MS,
@@ -498,7 +536,9 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
);
})
.finally(() => {
- state.avatarLoadsByContactID.delete(contactID);
+ if (state.avatarLoadsByContactID.get(contactID) === load) {
+ state.avatarLoadsByContactID.delete(contactID);
+ }
});
state.avatarLoadsByContactID.set(contactID, load);
diff --git a/web/packages/contacts/resolver.ts b/web/packages/contacts/resolver.ts
index 1f8a18ac06..a11e4164ca 100644
--- a/web/packages/contacts/resolver.ts
+++ b/web/packages/contacts/resolver.ts
@@ -4,8 +4,6 @@ import type {
ResolvedContactDisplay,
} from "./types";
-const SOMEONE_LABEL = "Someone";
-
export const normalizeEmail = (email?: string | null) => email?.trim().toLowerCase();
export const knownEmailOrUndefined = (email?: string | null) => {
@@ -35,15 +33,15 @@ export const resolveContactDisplayFromSnapshot = (
const matched = contactRecordForLookup(snapshot, lookup);
const actualEmail =
matched?.resolvedEmail ?? knownEmailOrUndefined(lookup.email);
- const primaryLabel =
- matched?.displayName ?? actualEmail ?? SOMEONE_LABEL;
+ const primaryLabel = matched?.displayName ?? actualEmail ?? "";
+ const initialSource = primaryLabel || actualEmail || "?";
return {
contactId: matched?.contactId,
profilePictureAttachmentID: matched?.profilePictureAttachmentID,
primaryLabel,
actualEmail,
- initial: primaryLabel[0]?.toUpperCase() ?? "S",
+ initial: initialSource[0]?.toUpperCase() ?? "?",
source: matched ? "contact" : "fallback",
};
};
diff --git a/web/packages/gallery/components/viewer/CommentsSidebar.tsx b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
index 5b328870f7..633ff8cdba 100644
--- a/web/packages/gallery/components/viewer/CommentsSidebar.tsx
+++ b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
@@ -252,7 +252,8 @@ const CommentHeader: React.FC<CommentHeaderProps> = ({
userID: useContactDisplay ? userID : undefined,
email: useContactDisplay ? email : undefined,
});
- const displayName = useContactDisplay ? resolved.primaryLabel : userName;
+ const displayName =
+ useContactDisplay ? (resolved.primaryLabel || userName) : userName;
return (
<CommentHeaderContainer>
@@ -336,7 +337,7 @@ const QuotedReply: React.FC<QuotedReplyProps> = ({
// For registered users, look up email
return shouldResolveParent
- ? resolvedParent.primaryLabel
+ ? (resolvedParent.primaryLabel || parentEmail || t("user"))
: (parentEmail ?? t("user"));
};
diff --git a/web/packages/gallery/components/viewer/LikesSidebar.tsx b/web/packages/gallery/components/viewer/LikesSidebar.tsx
index 8846f7ca4b..07f08305eb 100644
--- a/web/packages/gallery/components/viewer/LikesSidebar.tsx
+++ b/web/packages/gallery/components/viewer/LikesSidebar.tsx
@@ -90,8 +90,10 @@ interface Liker {
userID: number;
anonUserID?: string;
userName: string;
- /** The actual email for avatar color, even when userName is "You". */
- email: string;
+ /** The actual email when known. */
+ email?: string;
+ /** Stable fallback key for avatar color when email is missing. */
+ avatarColorKey: string;
/** The first letter of the actual name (not "You") for the avatar. */
avatarInitial: string;
/** True if this is a registered user with masked email (show person icon). */
@@ -117,7 +119,7 @@ const LikerRowItem: React.FC<{ liker: Liker }> = ({ liker }) => {
width: 32,
height: 32,
fontSize: 14,
- bgcolor: getAvatarColor(liker.email),
+ bgcolor: getAvatarColor(liker.avatarColorKey),
color: "#fff",
}}
src={resolved.avatarURL}
@@ -131,7 +133,9 @@ const LikerRowItem: React.FC<{ liker: Liker }> = ({ liker }) => {
)}
</Avatar>
<LikerName>
- {shouldResolveContact ? resolved.primaryLabel : liker.userName}
+ {shouldResolveContact
+ ? (resolved.primaryLabel || liker.userName)
+ : liker.userName}
</LikerName>
<HeartFilledIcon />
</LikerRow>
@@ -295,7 +299,8 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
// Check if this is the current logged-in user.
const isCurrentUser = r.userID === currentUserID;
- let email: string;
+ let email: string | undefined;
+ let avatarColorKey: string;
let userName: string;
let actualName: string;
@@ -309,12 +314,13 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
`${t("anonymous")} ${r.anonUserID?.slice(-4) ?? ""}`;
// Use actualName for avatar color (varying length like mobile emails)
email = actualName;
+ avatarColorKey = actualName;
userName = actualName;
} else {
const emailFromMap = prefetchedUserIDToEmail?.get(r.userID);
- // Use userID as string for unique avatar color
- email = emailFromMap ?? String(r.userID);
- actualName = emailFromMap ?? t("anonymous");
+ email = emailFromMap;
+ avatarColorKey = emailFromMap ?? String(r.userID);
+ actualName = emailFromMap ?? t("user");
userName = isCurrentUser ? t("you") : actualName;
}
@@ -328,6 +334,7 @@ export const LikesSidebar: React.FC<LikesSidebarProps> = ({
anonUserID: r.anonUserID,
userName,
email,
+ avatarColorKey,
avatarInitial: actualName[0]?.toUpperCase() ?? "?",
isMaskedEmail,
isCurrentUser,