Skip to content

Commit 2a1eba7

Browse files
fix(ui): show local project icons in the chat header (#122406)
* fix(ui): resolve project icons from deterministic paths Prepare project icon bytes during chat startup and serve only the process-stable snapshot. Keep all filesystem work asynchronous and lift the breadcrumb trail onto the topbar's optical axis. * fix(ui): keep project icon paths web-focused Drop the IDE-specific icon convention so every candidate remains an explicit web project path. * fix(ui): preserve project icon compatibility Restore existing web icon paths and refresh bounded session snapshots when they are served. Keep the IDE-specific path excluded per the final product decision.
1 parent 4401ff2 commit 2a1eba7

5 files changed

Lines changed: 203 additions & 32 deletions

File tree

‎src/gateway/server-methods/chat-history-handler.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
resolveSessionModelRef,
4242
resolveSessionStoreKey,
4343
} from "../session-utils.js";
44+
import { prepareSessionWorkspaceIcon } from "../workspace-icon-http.js";
4445
import { scheduleChatHistoryManagedMediaCleanup } from "./chat-assistant-content.js";
4546
import {
4647
CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES,
@@ -246,6 +247,16 @@ async function handleChatHistoryRequest({
246247
return;
247248
}
248249
}
250+
const workspaceIconPreparation =
251+
method === "chat.startup"
252+
? prepareSessionWorkspaceIcon({ sessionKey, agentId: sessionAgentId }).catch(
253+
(error: unknown) => {
254+
context.logGateway.debug(
255+
`chat.startup continuing without a workspace icon: ${formatErrorMessage(error)}`,
256+
);
257+
},
258+
)
259+
: Promise.resolve();
249260
const modelCatalogPromise =
250261
method === "chat.history"
251262
? (() => {
@@ -512,6 +523,7 @@ async function handleChatHistoryRequest({
512523
...(includeAgentsList && startupAgentsList ? { agentsList: startupAgentsList } : {}),
513524
...(startupMetadata ? { metadata: startupMetadata } : {}),
514525
};
526+
await workspaceIconPreparation;
515527
respond(true, payload);
516528
}
517529

‎src/gateway/workspace-icon-http.test.ts‎

Lines changed: 93 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ vi.mock("./server-methods/sessions-files.js", () => ({
3333
const {
3434
clearWorkspaceIconCacheForTest,
3535
handleWorkspaceIconHttpRequest,
36+
prepareSessionWorkspaceIcon,
3637
resolveWorkspaceIcon,
3738
SVG_ICON_MAX_BYTES,
3839
WORKSPACE_ICON_MAX_BYTES,
@@ -73,22 +74,35 @@ afterEach(async () => {
7374

7475
describe("resolveWorkspaceIcon", () => {
7576
const conventions = [
77+
{ relative: "favicon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
78+
{ relative: "favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
79+
{ relative: "favicon.png", body: PNG_BYTES, contentType: "image/png" },
7680
{ relative: "public/favicon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
7781
{ relative: "public/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
7882
{ relative: "public/favicon.png", body: PNG_BYTES, contentType: "image/png" },
83+
{ relative: "public/favicon-32.png", body: PNG_BYTES, contentType: "image/png" },
7984
{ relative: "public/apple-touch-icon.png", body: PNG_BYTES, contentType: "image/png" },
8085
{ relative: "static/favicon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
8186
{ relative: "static/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
8287
{ relative: "static/favicon.png", body: PNG_BYTES, contentType: "image/png" },
88+
{ relative: "ui/public/favicon-32.png", body: PNG_BYTES, contentType: "image/png" },
89+
{ relative: "ui/public/favicon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
90+
{ relative: "ui/public/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
91+
{ relative: "ui/public/favicon.png", body: PNG_BYTES, contentType: "image/png" },
92+
{ relative: "app/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
93+
{ relative: "app/favicon.png", body: PNG_BYTES, contentType: "image/png" },
8394
{ relative: "app/icon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
8495
{ relative: "app/icon.png", body: PNG_BYTES, contentType: "image/png" },
85-
{ relative: "app/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
96+
{ relative: "app/icon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
97+
{ relative: "src/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
98+
{ relative: "src/favicon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
99+
{ relative: "src/app/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
86100
{ relative: "src/app/icon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
87101
{ relative: "src/app/icon.png", body: PNG_BYTES, contentType: "image/png" },
88-
{ relative: "src/app/favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
89-
{ relative: "favicon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
90-
{ relative: "favicon.ico", body: ICO_BYTES, contentType: "image/x-icon" },
91-
{ relative: "favicon.png", body: PNG_BYTES, contentType: "image/png" },
102+
{ relative: "assets/icon.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
103+
{ relative: "assets/icon.png", body: PNG_BYTES, contentType: "image/png" },
104+
{ relative: "assets/logo.svg", body: SVG_BYTES, contentType: "image/svg+xml" },
105+
{ relative: "assets/logo.png", body: PNG_BYTES, contentType: "image/png" },
92106
] as const;
93107

94108
it.each(conventions)("resolves $relative as $contentType", async (convention) => {
@@ -99,16 +113,17 @@ describe("resolveWorkspaceIcon", () => {
99113
expect(icon?.etag).toMatch(/^"[\w-]+"$/u);
100114
});
101115

102-
it("prefers the framework-specific location over a bare root favicon", async () => {
116+
it("uses the first valid icon in the fixed precedence", async () => {
103117
const root = await makeWorkspace({
104118
"favicon.ico": ICO_BYTES,
105119
"public/favicon.svg": SVG_BYTES,
120+
"ui/public/favicon-32.png": PNG_BYTES,
106121
});
107-
expect((await resolveWorkspaceIcon(root))?.contentType).toBe("image/svg+xml");
122+
expect((await resolveWorkspaceIcon(root))?.contentType).toBe("image/x-icon");
108123
});
109124

110125
const rejected = [
111-
{ label: "an unconventional location", files: { "assets/favicon.ico": ICO_BYTES } },
126+
{ label: "an unconventional location", files: { "vendor/favicon.png": PNG_BYTES } },
112127
{ label: "an empty file", files: { "favicon.ico": Buffer.alloc(0) } },
113128
{ label: "bytes that are not an image", files: { "favicon.ico": Buffer.from("#!/bin/sh\n") } },
114129
{
@@ -212,6 +227,7 @@ describe("handleWorkspaceIconHttpRequest", () => {
212227
it("serves the session workspace icon with sandboxed asset headers", async () => {
213228
const root = await makeWorkspace({ "public/favicon.ico": ICO_BYTES });
214229
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(root);
230+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:one" });
215231

216232
const response = await fetch(iconRoute("agent:main:one"));
217233
expect(mocks.resolveLocalSessionWorkspaceRoot).toHaveBeenCalledWith({
@@ -233,6 +249,7 @@ describe("handleWorkspaceIconHttpRequest", () => {
233249
it("revalidates an unchanged icon without resending its bytes", async () => {
234250
const root = await makeWorkspace({ "favicon.png": PNG_BYTES });
235251
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(root);
252+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:one" });
236253

237254
const first = await fetch(iconRoute("agent:main:one"));
238255
const etag = first.headers.get("etag");
@@ -249,6 +266,7 @@ describe("handleWorkspaceIconHttpRequest", () => {
249266
it("omits the body but keeps the representation headers on HEAD", async () => {
250267
const root = await makeWorkspace({ "favicon.png": PNG_BYTES });
251268
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(root);
269+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:one" });
252270

253271
const response = await fetch(iconRoute("agent:main:one"), { method: "HEAD" });
254272
expect(response.status).toBe(200);
@@ -265,11 +283,77 @@ describe("handleWorkspaceIconHttpRequest", () => {
265283
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(
266284
hasWorkspace ? await makeWorkspace({}) : undefined,
267285
);
286+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:one" });
268287
const response = await fetch(iconRoute("agent:main:one"));
269288
expect(response.status).toBe(404);
270289
expect(response.headers.get("cache-control")).toBe("no-store");
271290
});
272291

292+
it("keeps a request made before chat startup retryable", async () => {
293+
const response = await fetch(iconRoute("agent:main:one"));
294+
expect(response.status).toBe(503);
295+
expect(response.headers.get("cache-control")).toBe("no-store");
296+
expect(response.headers.get("retry-after")).toBe("1");
297+
expect(mocks.resolveLocalSessionWorkspaceRoot).not.toHaveBeenCalled();
298+
});
299+
300+
it("waits for preparation already started by chat startup", async () => {
301+
const root = await makeWorkspace({ "public/favicon.ico": ICO_BYTES });
302+
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(root);
303+
304+
const preparation = prepareSessionWorkspaceIcon({ sessionKey: "agent:main:pending" });
305+
const responsePromise = fetch(iconRoute("agent:main:pending"));
306+
307+
await preparation;
308+
const response = await responsePromise;
309+
expect(response.status).toBe(200);
310+
expect(Buffer.from(await response.arrayBuffer()).equals(ICO_BYTES)).toBe(true);
311+
});
312+
313+
it("records the fallback when preparation fails", async () => {
314+
mocks.resolveLocalSessionWorkspaceRoot.mockImplementation(() => {
315+
throw new Error("broken workspace metadata");
316+
});
317+
await expect(prepareSessionWorkspaceIcon({ sessionKey: "agent:main:broken" })).rejects.toThrow(
318+
"broken workspace metadata",
319+
);
320+
321+
const response = await fetch(iconRoute("agent:main:broken"));
322+
expect(response.status).toBe(404);
323+
});
324+
325+
it("does no session-store or filesystem resolution in the HTTP request", async () => {
326+
const root = await makeWorkspace({ "ui/public/favicon-32.png": PNG_BYTES });
327+
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(root);
328+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:one" });
329+
mocks.resolveLocalSessionWorkspaceRoot.mockClear();
330+
await fs.rm(path.join(root, "ui/public/favicon-32.png"));
331+
332+
const first = await fetch(iconRoute("agent:main:one"));
333+
const second = await fetch(iconRoute("agent:main:one"));
334+
335+
expect(first.status).toBe(200);
336+
expect(second.status).toBe(200);
337+
expect(Buffer.from(await first.arrayBuffer()).equals(PNG_BYTES)).toBe(true);
338+
expect(Buffer.from(await second.arrayBuffer()).equals(PNG_BYTES)).toBe(true);
339+
expect(mocks.resolveLocalSessionWorkspaceRoot).not.toHaveBeenCalled();
340+
});
341+
342+
it("keeps a recently served session snapshot across bounded-cache eviction", async () => {
343+
const root = await makeWorkspace({ "favicon.png": PNG_BYTES });
344+
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(root);
345+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:kept" });
346+
for (let index = 0; index < 127; index += 1) {
347+
await prepareSessionWorkspaceIcon({ sessionKey: `agent:main:filler-${index}` });
348+
}
349+
350+
expect((await fetch(iconRoute("agent:main:kept"))).status).toBe(200);
351+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:newest" });
352+
353+
expect((await fetch(iconRoute("agent:main:kept"))).status).toBe(200);
354+
expect((await fetch(iconRoute("agent:main:filler-0"))).status).toBe(503);
355+
});
356+
273357
const malformed = ["/__openclaw__/workspace-icon/", "/__openclaw__/workspace-icon/a/b"];
274358

275359
it.each(malformed)("claims %s as a 404 instead of falling through", async (pathname) => {
@@ -316,6 +400,7 @@ describe("handleWorkspaceIconHttpRequest", () => {
316400
// resolveLocalSessionWorkspaceRoot withholds the root for exec-node sessions
317401
// so the route can never answer with this Gateway's own project icon.
318402
mocks.resolveLocalSessionWorkspaceRoot.mockReturnValue(undefined);
403+
await prepareSessionWorkspaceIcon({ sessionKey: "agent:main:remote" });
319404
const response = await fetch(iconRoute("agent:main:remote"));
320405
expect(response.status).toBe(404);
321406
expect(response.headers.get("cache-control")).toBe("no-store");

‎src/gateway/workspace-icon-http.ts‎

Lines changed: 81 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
// Serves a workspace directory's own project icon so the Control UI can render
22
// real project identity instead of a generic folder glyph.
33
import { createHash } from "node:crypto";
4-
import fs from "node:fs";
4+
import { close } from "node:fs";
55
import type { IncomingMessage, ServerResponse } from "node:http";
66
import path from "node:path";
7+
import { promisify } from "node:util";
78
import { fileTypeFromBuffer } from "file-type";
89
import {
910
openRootFileFollowingParents,
@@ -26,37 +27,51 @@ import {
2627
import { authorizeOperatorScopesForMethod } from "./method-scopes.js";
2728

2829
/**
29-
* Conventional project icon locations, ordered by framework specificity and then
30-
* by rendering fidelity (vector before raster). Resolution stops at the first
31-
* hit, so this list is the whole filesystem cost of a workspace: keeping it
32-
* bounded is what makes icon lookup a one-time-per-workspace operation.
30+
* Conventional project icon locations in deterministic product precedence.
31+
* Resolution stops at the first valid hit, so this fixed list is the whole
32+
* filesystem cost of opening a workspace and never becomes a recursive scan.
3333
*/
3434
const WORKSPACE_ICON_RELATIVE_PATHS = [
35+
"favicon.svg",
36+
"favicon.ico",
37+
"favicon.png",
3538
"public/favicon.svg",
3639
"public/favicon.ico",
3740
"public/favicon.png",
41+
"public/favicon-32.png",
3842
"public/apple-touch-icon.png",
3943
"static/favicon.svg",
4044
"static/favicon.ico",
4145
"static/favicon.png",
46+
"ui/public/favicon-32.png",
47+
"ui/public/favicon.svg",
48+
"ui/public/favicon.ico",
49+
"ui/public/favicon.png",
50+
"app/favicon.ico",
51+
"app/favicon.png",
4252
"app/icon.svg",
4353
"app/icon.png",
44-
"app/favicon.ico",
54+
"app/icon.ico",
55+
"src/favicon.ico",
56+
"src/favicon.svg",
57+
"src/app/favicon.ico",
4558
"src/app/icon.svg",
4659
"src/app/icon.png",
47-
"src/app/favicon.ico",
48-
"favicon.svg",
49-
"favicon.ico",
50-
"favicon.png",
60+
"assets/icon.svg",
61+
"assets/icon.png",
62+
"assets/logo.svg",
63+
"assets/logo.png",
5164
] as const;
5265

5366
/** Icons are small by construction; anything larger is not a favicon. */
5467
export const WORKSPACE_ICON_MAX_BYTES = 512 * 1024;
5568
/** Vector icons are markup the renderer must parse, so they get a tighter cap. */
5669
export const SVG_ICON_MAX_BYTES = 64 * 1024;
5770
const WORKSPACE_ICON_CACHE_MAX_ENTRIES = 32;
71+
const SESSION_WORKSPACE_ICON_CACHE_MAX_ENTRIES = 128;
5872
const SVG_MIME_TYPE = "image/svg+xml";
5973
const ICO_MIME_TYPE = "image/x-icon";
74+
const closeFileDescriptor = promisify(close);
6075

6176
/** Sniffable raster types the Control UI can render inside an <img> element. */
6277
const ALLOWED_RASTER_ICON_MIME_TYPES = new Set([
@@ -78,9 +93,11 @@ type WorkspaceIcon = {
7893
type WorkspaceIconResolution = WorkspaceIcon | null;
7994

8095
let workspaceIconCache = new Map<string, Promise<WorkspaceIconResolution>>();
96+
let sessionWorkspaceIconCache = new Map<string, Promise<WorkspaceIconResolution>>();
8197

8298
export function clearWorkspaceIconCacheForTest(): void {
8399
workspaceIconCache = new Map();
100+
sessionWorkspaceIconCache = new Map();
84101
}
85102

86103
/**
@@ -138,7 +155,7 @@ async function readWorkspaceIconCandidate(
138155
} catch {
139156
return undefined;
140157
} finally {
141-
fs.closeSync(opened.fd);
158+
await closeFileDescriptor(opened.fd);
142159
}
143160
if (body.byteLength === 0) {
144161
return undefined;
@@ -189,6 +206,41 @@ const getSessionsFilesModule = createLazyRuntimeModule(
189206
() => import("./server-methods/sessions-files.js"),
190207
);
191208

209+
/**
210+
* Prepares the immutable icon snapshot while opening a chat. The HTTP asset
211+
* request only reads this map: no session-store or filesystem work is allowed
212+
* on that hot path, and icon changes become visible after Gateway restart.
213+
*/
214+
export async function prepareSessionWorkspaceIcon(params: {
215+
sessionKey: string;
216+
agentId?: string;
217+
}): Promise<void> {
218+
const preparation = (async (): Promise<WorkspaceIconResolution> => {
219+
const workspaceRoot = (await getSessionsFilesModule()).resolveLocalSessionWorkspaceRoot(params);
220+
return workspaceRoot ? await resolveWorkspaceIcon(workspaceRoot) : null;
221+
})();
222+
sessionWorkspaceIconCache.delete(params.sessionKey);
223+
// A failed optional preparation still becomes a stable fallback snapshot;
224+
// the returned promise rejects separately so chat.startup can record it.
225+
sessionWorkspaceIconCache.set(
226+
params.sessionKey,
227+
preparation.catch(() => null),
228+
);
229+
pruneMapToMaxSize(sessionWorkspaceIconCache, SESSION_WORKSPACE_ICON_CACHE_MAX_ENTRIES);
230+
await preparation;
231+
}
232+
233+
function readPreparedSessionWorkspaceIcon(
234+
sessionKey: string,
235+
): Promise<WorkspaceIconResolution> | undefined {
236+
const prepared = sessionWorkspaceIconCache.get(sessionKey);
237+
if (prepared) {
238+
sessionWorkspaceIconCache.delete(sessionKey);
239+
sessionWorkspaceIconCache.set(sessionKey, prepared);
240+
}
241+
return prepared;
242+
}
243+
192244
/** `matched` claims the response so a malformed key 404s instead of reaching the SPA. */
193245
type WorkspaceIconRequest = { matched: false } | { matched: true; sessionKey: string | null };
194246

@@ -216,9 +268,8 @@ function parseWorkspaceIconRequest(
216268
}
217269

218270
/**
219-
* Serves the icon of the workspace a session runs in. The request names a
220-
* session, never a path: the served file is whatever the process-cached
221-
* resolution already picked inside that session's own workspace root.
271+
* Serves the icon snapshot prepared when the chat opened. The request names a
272+
* session, never a path, and performs no filesystem or session-store work.
222273
*/
223274
export async function handleWorkspaceIconHttpRequest(
224275
req: IncomingMessage,
@@ -272,15 +323,23 @@ export async function handleWorkspaceIconHttpRequest(
272323
return true;
273324
}
274325

275-
const workspaceRoot = parsed.sessionKey
276-
? (await getSessionsFilesModule()).resolveLocalSessionWorkspaceRoot({
277-
sessionKey: parsed.sessionKey,
278-
})
279-
: undefined;
280-
const icon = workspaceRoot ? await resolveWorkspaceIcon(workspaceRoot) : null;
326+
if (!parsed.sessionKey) {
327+
res.setHeader("cache-control", "no-store");
328+
respondNotFound(res);
329+
return true;
330+
}
331+
const prepared = readPreparedSessionWorkspaceIcon(parsed.sessionKey);
332+
if (!prepared) {
333+
// The header can paint before chat.startup finishes. Keep this state
334+
// retryable so it cannot be cached as the workspace's resolved fallback.
335+
res.statusCode = 503;
336+
res.setHeader("cache-control", "no-store");
337+
res.setHeader("retry-after", "1");
338+
res.end("workspace icon snapshot is not ready");
339+
return true;
340+
}
341+
const icon = await prepared;
281342
if (!icon) {
282-
// A workspace can gain an icon later, and this route has no revalidation
283-
// token for an absent one; caching the miss would hide it until expiry.
284343
res.setHeader("cache-control", "no-store");
285344
respondNotFound(res);
286345
return true;

0 commit comments

Comments
 (0)