Skip to content

Commit a2ff6cb

Browse files
authored
fix(ui): consistently load and cache user avatars (#114444)
* fix(ui): consistently load and cache user avatars * fix(ui): retain avatar images across profile updates
1 parent 914bd19 commit a2ff6cb

11 files changed

Lines changed: 617 additions & 67 deletions

‎ui/src/app/gateway-store.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type {
1818
ApplicationGatewayConnection,
1919
ApplicationGatewaySnapshot,
2020
} from "./context.ts";
21+
import { resolveControlUiAuthHeader } from "./control-ui-auth.ts";
2122
import { loadSettings, patchSettings, persistSessionToken } from "./settings.ts";
2223
import { readPresenceEntries, resolveSelfPresenceUser } from "./user-profile.ts";
2324

@@ -272,7 +273,13 @@ export function createApplicationGateway(
272273
connection = nextConnection;
273274
// Trust the connected gateway's origin for avatar route resolution so
274275
// split-origin Control UI deployments load uploaded/proxied avatars.
275-
setAvatarGatewayOrigin(nextConnection.gatewayUrl);
276+
setAvatarGatewayOrigin(
277+
nextConnection.gatewayUrl,
278+
resolveControlUiAuthHeader({
279+
settings: { token: nextConnection.token },
280+
password: nextConnection.password,
281+
}),
282+
);
276283
updateSettings(
277284
{
278285
gatewayUrl: nextConnection.gatewayUrl,
@@ -306,6 +313,14 @@ export function createApplicationGateway(
306313
if (client !== nextClient) {
307314
return;
308315
}
316+
setAvatarGatewayOrigin(
317+
nextConnection.gatewayUrl,
318+
resolveControlUiAuthHeader({
319+
hello,
320+
settings: { token: nextConnection.token },
321+
password: nextConnection.password,
322+
}),
323+
);
309324
connection = { ...connection, bootstrapToken: "" };
310325
if (persistConnectionSettings) {
311326
settings = loadSettings();

‎ui/src/app/user-profile.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,6 @@ describe("connection user profile helpers", () => {
6161
42,
6262
"https://gateway.example.test/control/profile",
6363
),
64-
).toBeNull();
64+
).toBe("https://remote.example.test/api/users/profile-1/avatar?v=42");
6565
});
6666
});

‎ui/src/app/user-profile.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,9 @@ export function userProfileAvatarUrl(
5858
} else if (url.protocol === "wss:") {
5959
url.protocol = "https:";
6060
}
61-
// The authenticated avatar endpoint is HTTP-only and the Control UI CSP
62-
// permits images from its own origin. Cross-origin gateways keep initials.
63-
if (
64-
!["http:", "https:"].includes(url.protocol) ||
65-
url.origin !== new URL(documentHref).origin
66-
) {
61+
// The shared avatar loader authenticates cross-origin Gateway requests and
62+
// turns their response into a local blob accepted by the Control UI CSP.
63+
if (!["http:", "https:"].includes(url.protocol)) {
6764
return null;
6865
}
6966
url.username = "";

‎ui/src/components/viewer-facepile.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,64 @@ it("renders trusted presence avatar routes directly", async () => {
5353
});
5454
});
5555

56+
it("derives a missing presence avatar from the durable profile id, not the email", async () => {
57+
const profileId = "c3e32452-0467-47e5-aafa-233cd5dae29f";
58+
const avatar = document.createElement("openclaw-viewer-avatar") as ViewerAvatarElement;
59+
avatar.user = {
60+
id: profileId,
61+
62+
name: "Ada Lovelace",
63+
watchedSessions: [],
64+
};
65+
document.body.append(avatar);
66+
67+
await vi.waitFor(async () => {
68+
await avatar.updateComplete;
69+
expect(avatar.querySelector("img")?.getAttribute("src")).toBe(`/api/users/${profileId}/avatar`);
70+
});
71+
});
72+
73+
it("shares an authenticated avatar blob between the same user in the roster and profile", async () => {
74+
setAvatarGatewayOrigin("https://gateway.example.test", "Bearer viewer-token");
75+
const fetchAvatar = vi.spyOn(globalThis, "fetch").mockResolvedValue(
76+
new Response(new Uint8Array([1, 2, 3]), {
77+
headers: { "content-type": "image/png" },
78+
}),
79+
);
80+
vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:shared-viewer-avatar");
81+
const user: PresenceViewer = {
82+
id: "profile-ada",
83+
84+
name: "Ada Lovelace",
85+
avatarUrl: "/api/users/profile-ada/avatar?v=7",
86+
watchedSessions: [],
87+
};
88+
const avatars = Array.from({ length: 2 }, () => {
89+
const avatar = document.createElement("openclaw-viewer-avatar") as ViewerAvatarElement;
90+
avatar.user = user;
91+
document.body.append(avatar);
92+
return avatar;
93+
});
94+
95+
await vi.waitFor(async () => {
96+
await Promise.all(avatars.map((avatar) => avatar.updateComplete));
97+
expect(avatars.map((avatar) => avatar.querySelector("img")?.getAttribute("src"))).toEqual([
98+
"blob:shared-viewer-avatar",
99+
"blob:shared-viewer-avatar",
100+
]);
101+
});
102+
103+
expect(fetchAvatar).toHaveBeenCalledOnce();
104+
expect(fetchAvatar).toHaveBeenCalledWith(
105+
"https://gateway.example.test/api/users/profile-ada/avatar?v=7",
106+
expect.objectContaining({ headers: { Authorization: "Bearer viewer-token" } }),
107+
);
108+
for (const avatar of avatars) {
109+
avatar.querySelector("img")?.dispatchEvent(new Event("load"));
110+
expect(avatar.querySelector(".viewer-avatar")?.classList.contains("is-fallback")).toBe(false);
111+
}
112+
});
113+
56114
type ViewerFacepileElement = HTMLElement & {
57115
presencePayload: unknown;
58116
selfInstanceId?: string;

‎ui/src/components/viewer-facepile.ts‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
import { html, nothing } from "lit";
22
import { property } from "lit/decorators.js";
3+
import { live } from "lit/directives/live.js";
4+
import { until } from "lit/directives/until.js";
35
import type { PresenceEntry } from "../api/types.ts";
46
import { CONTROL_UI_BUILD_INFO, type ControlUiBuildInfo } from "../build-info.ts";
57
import { t } from "../i18n/index.ts";
6-
import { resolveAvatar } from "../lib/identity-avatar.ts";
8+
import {
9+
resolveAvatar,
10+
resolveAvatarImageUrl,
11+
settleAvatarImageUrl,
12+
type ResolvedIdentityAvatar,
13+
} from "../lib/identity-avatar.ts";
714
import { OpenClawLightDomContentsElement } from "../lit/openclaw-element.ts";
815
import { renderSidebarServerDetails } from "./sidebar-build-chip-format.ts";
916
import "./tooltip.ts";
@@ -135,28 +142,34 @@ function renderAvatarInitials(user: PresenceViewer) {
135142
return html`<span style=${`background: ${avatarColor(user.id)}`}>${initialsFor(user)}</span>`;
136143
}
137144

138-
function resolveViewerAvatar(user: PresenceViewer) {
139-
const avatar = resolveAvatar({
140-
id: user.email ?? user.id,
141-
name: user.name,
142-
profileAvatarUrl: user.avatarUrl,
143-
});
144-
if (avatar.kind === "initials") {
145+
function renderViewerAvatar(
146+
user: PresenceViewer,
147+
avatar: ResolvedIdentityAvatar,
148+
imageUrl: string | Promise<string | null> | null,
149+
) {
150+
if (avatar.kind === "initials" || !imageUrl) {
145151
return renderAvatarInitials(user);
146152
}
147153
return html`<img
148-
src=${avatar.url}
154+
src=${typeof imageUrl === "string"
155+
? imageUrl
156+
: until(
157+
imageUrl.then((url) => url ?? nothing),
158+
nothing,
159+
)}
149160
alt=""
150161
referrerpolicy="no-referrer"
151162
@error=${(event: Event) => {
152163
const image = event.currentTarget;
153164
if (image instanceof HTMLImageElement) {
165+
settleAvatarImageUrl(image.getAttribute("src"));
154166
image.closest<HTMLElement>(".viewer-avatar")?.classList.add("is-fallback");
155167
}
156168
}}
157169
@load=${(event: Event) => {
158170
const image = event.currentTarget;
159171
if (image instanceof HTMLImageElement) {
172+
settleAvatarImageUrl(image.getAttribute("src"));
160173
image.closest<HTMLElement>(".viewer-avatar")?.classList.remove("is-fallback");
161174
}
162175
}}
@@ -178,12 +191,22 @@ class ViewerAvatar extends OpenClawLightDomContentsElement {
178191
return nothing;
179192
}
180193
const label = presenceViewerLabel(user);
194+
const avatar = resolveAvatar({
195+
id: user.id,
196+
name: user.name,
197+
username: user.email,
198+
profileAvatarUrl: user.avatarUrl,
199+
});
200+
const imageUrl = avatar.kind === "initials" ? null : resolveAvatarImageUrl(avatar.url);
201+
const pending = imageUrl !== null && typeof imageUrl !== "string";
202+
// Image events toggle fallback imperatively; live() compares actual DOM so
203+
// a changed avatar restores initials without replacing its existing image.
181204
return html`<span
182-
class="viewer-avatar viewer-avatar--${this.variant}"
205+
class=${live(`viewer-avatar viewer-avatar--${this.variant}${pending ? " is-fallback" : ""}`)}
183206
data-viewer-id=${user.id}
184207
aria-label=${label}
185208
>
186-
${resolveViewerAvatar(user)}
209+
${renderViewerAvatar(user, avatar, imageUrl)}
187210
</span>`;
188211
}
189212
}

‎ui/src/e2e/profile-page.e2e.test.ts‎

Lines changed: 80 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { mkdir } from "node:fs/promises";
33
import path from "node:path";
44
import { chromium, type Browser, type Page } from "playwright";
55
import { afterAll, beforeAll, describe, expect, it } from "vitest";
6+
import {
7+
buildControlUiCspHeader,
8+
computeInlineScriptHashes,
9+
} from "../../../src/gateway/control-ui-csp.ts";
610
import {
711
canRunPlaywrightChromium,
812
installMockGateway,
@@ -148,6 +152,7 @@ const testPresenceUsers = [
148152
id: testProfile.id,
149153
name: testProfile.displayName,
150154
email: testProfile.emails[0],
155+
avatarUrl: `/api/users/${testProfile.id}/avatar?v=${testProfile.updatedAt}`,
151156
},
152157
];
153158

@@ -215,9 +220,31 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
215220
}
216221
});
217222

218-
it("renders the gateway avatar route in the profile preview", async () => {
219-
const context = await browser.newContext();
223+
it("shares one authenticated avatar between the sidebar and profile preview", async () => {
224+
if (captureUiProof) {
225+
await mkdir(proofDir, { recursive: true });
226+
}
227+
const context = await browser.newContext({
228+
...(captureUiProof
229+
? { recordVideo: { dir: proofDir, size: { width: 1280, height: 800 } } }
230+
: {}),
231+
viewport: { width: 1280, height: 800 },
232+
});
220233
const page = await context.newPage();
234+
await page.route(`${server.baseUrl}settings/profile`, async (route) => {
235+
const response = await route.fetch();
236+
const body = await response.text();
237+
await route.fulfill({
238+
body,
239+
headers: {
240+
...response.headers(),
241+
"content-security-policy": buildControlUiCspHeader({
242+
inlineScriptHashes: computeInlineScriptHashes(body),
243+
}),
244+
},
245+
response,
246+
});
247+
});
221248
const gatewayUrl = server.baseUrl.replace(/^http/u, "ws").replace(/\/$/u, "");
222249
await page.addInitScript((sameOriginGatewayUrl) => {
223250
(
@@ -229,16 +256,20 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
229256
token: "test",
230257
};
231258
}, gatewayUrl);
232-
const avatarRequests: string[] = [];
233-
// The gateway serves the avatar (uploaded first, Gravatar fallback second)
234-
// behind its own same-origin route; the Control UI renders only that route,
235-
// so the preview never requests gravatar.com directly — the Control UI CSP
236-
// (img-src 'self') would block it.
259+
const avatarRequests: Array<{ authorization?: string; url: string }> = [];
260+
// Profile images require the same bearer auth as gateway RPCs. One cached
261+
// blob keeps the sidebar and preview inside the Control UI's image CSP.
237262
await page.route(`**/api/users/${testProfile.id}/avatar*`, async (route) => {
238-
avatarRequests.push(route.request().url());
263+
avatarRequests.push({
264+
authorization: route.request().headers().authorization,
265+
url: route.request().url(),
266+
});
239267
await route.fulfill({
240-
body: '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>',
241-
contentType: "image/svg+xml",
268+
body: Buffer.from(
269+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/a6kAAAAASUVORK5CYII=",
270+
"base64",
271+
),
272+
contentType: "image/png",
242273
status: 200,
243274
});
244275
});
@@ -254,19 +285,49 @@ describeControlUiE2e("Control UI profile page mocked Gateway E2E", () => {
254285
try {
255286
const response = await page.goto(`${server.baseUrl}settings/profile`);
256287
expect(response?.status()).toBe(200);
288+
expect(response?.headers()["content-security-policy"]).toContain(
289+
"img-src 'self' data: blob:",
290+
);
257291

258292
const profileAvatar = page.locator("#settings-profile-identity openclaw-viewer-avatar img");
259293
await profileAvatar.waitFor({ timeout: 10_000 });
260-
// profile-page derives the src from userProfileAvatarUrl(id, updatedAt);
261-
// the gateway origin may absolutize it, so match the canonical path suffix.
262-
expect(await profileAvatar.getAttribute("src")).toContain(
263-
`/api/users/${testProfile.id}/avatar?v=2`,
264-
);
294+
const imageUrl = await profileAvatar.getAttribute("src");
295+
expect(imageUrl).toMatch(/^blob:/u);
265296
await expect
266-
.poll(() =>
267-
avatarRequests.some((url) => url.includes(`/api/users/${testProfile.id}/avatar`)),
268-
)
269-
.toBe(true);
297+
.poll(() => profileAvatar.evaluate((image) => (image as HTMLImageElement).naturalWidth))
298+
.toBe(1);
299+
expect(
300+
await profileAvatar.evaluate((image) =>
301+
image.closest(".viewer-avatar")?.classList.contains("is-fallback"),
302+
),
303+
).toBe(false);
304+
if (captureUiProof) {
305+
await page.screenshot({
306+
animations: "disabled",
307+
path: path.join(proofDir, "03-authenticated-profile-avatar.png"),
308+
});
309+
}
310+
311+
await page.getByRole("button", { name: "Back to app" }).click();
312+
const sidebarAvatar = page.locator(".sidebar-identity-card openclaw-viewer-avatar img");
313+
await sidebarAvatar.waitFor({ timeout: 10_000 });
314+
await expect.poll(() => avatarRequests.length).toBe(1);
315+
expect(avatarRequests[0]).toEqual({
316+
authorization: "Bearer e2e-device-token",
317+
url: expect.stringContaining(`/api/users/${testProfile.id}/avatar?v=2`),
318+
});
319+
expect(await sidebarAvatar.getAttribute("src")).toBe(imageUrl);
320+
expect(
321+
await sidebarAvatar.evaluate((image) =>
322+
image.closest(".viewer-avatar")?.classList.contains("is-fallback"),
323+
),
324+
).toBe(false);
325+
if (captureUiProof) {
326+
await page.screenshot({
327+
animations: "disabled",
328+
path: path.join(proofDir, "03-authenticated-user-avatar-cache.png"),
329+
});
330+
}
270331
} finally {
271332
await context.close();
272333
}

0 commit comments

Comments
 (0)