fix: improve project favicon detection for monorepos #1024
main fromrefs/pull/1024/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- apps/server/src/projectFaviconRoute.ts lines 79 to 80OutdatedResolvedby ponbac(GitHub profile, opens in a new tab)@@ -61,5 +63,18 @@63+ projectRoot: string;64+ filterAllowedPaths: (candidatePaths: readonly string[]) => Effect.Effect<string[]>;65+}66+67+function extractIconHref(source: string): Option.Option<string> {68+ return Option.firstSomeOf([69+ Option.fromNullishOr(source.match(LINK_ICON_HTML_RE)?.[1]),70+ Option.fromNullishOr(source.match(LINK_ICON_OBJ_RE)?.[1]),71+ ]);6172 }627363-function resolveIconHref(projectCwd: string, href: string): string[] {64- const clean = href.replace(/^\//, "");65- return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];74+function notFoundToNone<A, R>(75+ effect: Effect.Effect<A, PlatformError.PlatformError, R>,76+): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> {77+ return effect.pipe(78+ Effect.map(Option.some),79+ Effect.catchTag("PlatformError", (error) =>80+ error.reason._tag === "NotFound" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -0,0 +1,20 @@1+import { runProcess } from "./processRunner";2+3+const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;4+5+/**6+ * Shared git-ignore helpers for server-side workspace scans.7+ *8+ * Both callers use these helpers as an optimization and a consistency layer, not9+ * as a hard dependency. If git is unavailable, slow, or returns an unexpected10+ * result, we intentionally fail open so the UI keeps working and avoids hiding11+ * files unpredictably.12+ */13+14+function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {15+ const parts = input.split("\0");16+ if (truncated && parts[parts.length - 1]?.length) {17+ parts.pop();18+ }19+ return parts.filter((value) => value.length > 0);20+}
- @@ -93,0 +147,21 @@147+ return (candidatePaths: readonly string[]) =>148+ Effect.gen(function* () {149+ if (!shouldFilterWithGitIgnore || candidatePaths.length === 0) {150+ return [...candidatePaths];151+ }152+153+ const uncachedRelativePaths = Array.dedupe(154+ candidatePaths.flatMap((candidatePath) =>155+ Option.match(toProjectRelativePath(projectRoot, candidatePath), {156+ onNone: () => [],157+ onSome: (relativePath) => (gitIgnorePathCache.has(relativePath) ? [] : [relativePath]),158+ }),159+ ),160+ );161+162+ if (uncachedRelativePaths.length > 0) {163+ // Cache git-ignore decisions by normalized relative path so repeated root164+ // and nested scans only hit `git check-ignore` once per candidate.165+ const allowedRelativePaths = yield* Effect.promise(() =>166+ filterGitIgnoredPaths(projectRoot, uncachedRelativePaths),167+ ).pipe(Effect.orElseSucceed(() => uncachedRelativePaths));
- @@ -0,0 +405,21 @@405+ return inFlight;406+ }407+408+ const nextPromise = buildWorkspaceIndex(cwd)409+ .then((next) => {410+ workspaceIndexCache.set(cwd, next);411+ while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {412+ const oldestKey = workspaceIndexCache.keys().next().value;413+ if (!oldestKey) break;414+ workspaceIndexCache.delete(oldestKey);415+ }416+ return next;417+ })418+ .finally(() => {419+ inFlightWorkspaceIndexBuilds.delete(cwd);420+ });421+ inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);422+ return nextPromise;423+}424+425+export function clearWorkspaceIndexCache(cwd: string): void {
- @@ -0,0 +433,21 @@433+ const index = await getWorkspaceIndex(input.cwd);434+ const normalizedQuery = normalizeQuery(input.query);435+ const limit = Math.max(0, Math.floor(input.limit));436+ const rankedEntries: RankedWorkspaceEntry[] = [];437+ let matchedEntryCount = 0;438+439+ for (const entry of index.entries) {440+ const score = scoreEntry(entry, normalizedQuery);441+ if (score === null) {442+ continue;443+ }444+445+ matchedEntryCount += 1;446+ insertRankedEntry(rankedEntries, { entry, score }, limit);447+ }448+449+ return {450+ entries: rankedEntries.map((candidate) => candidate.entry),451+ truncated: index.truncated || matchedEntryCount > limit,452+ };453+}@@ -83,0 +177,21 @@177+ Option.match(toProjectRelativePath(projectRoot, candidatePath), {178+ onNone: () => true,179+ onSome: (relativePath) => gitIgnorePathCache.get(relativePath) !== false,180+ }),181+ );182+ });183+}184+185+function findFirstReadableFaviconPath(186+ lookup: FaviconLookupServices,187+ candidatePaths: readonly string[],188+) {189+ return Effect.gen(function* () {190+ const allowedCandidatePaths = yield* lookup.filterAllowedPaths(candidatePaths);191+192+ for (const candidatePath of allowedCandidatePaths) {193+ const fileOption = yield* readFileIfExists(lookup, candidatePath, (resolvedPath) =>194+ lookup.fileSystem.readFile(resolvedPath),195+ );196+ if (Option.isSome(fileOption)) {197+ return Option.some(fileOption.value.path);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +317,21 @@317+ `Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,318+ { cause: error },319+ );320+ }321+ return { relativeDir, dirents: null };322+ }323+ },324+ );325+326+ const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {327+ const { relativeDir, dirents } = directoryEntry;328+ if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;329+330+ dirents.sort((left, right) => left.name.localeCompare(right.name));331+ const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];332+ for (const dirent of dirents) {333+ if (!dirent.name || dirent.name === "." || dirent.name === "..") {334+ continue;335+ }336+ if (dirent.isDirectory() && isPathInIgnoredWorkspaceDirectory(dirent.name)) {337+ continue;apps/server/src/projectFaviconRoute.test.ts lines 77 to 85OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+ ),66+ ),67+ ).catch((error) => {68+ if (!res.headersSent) {69+ res.writeHead(500, { "Content-Type": "text/plain" });70+ }71+ if (!res.writableEnded) {72+ res.end(error instanceof Error ? error.message : "Unhandled error");73+ }74+ });75+ });76+77+ await new Promise<void>((resolve, reject) => {78+ server.listen(0, "127.0.0.1", (error?: Error) => {79+ if (error) {80+ reject(error);81+ return;82+ }83+ resolve();84+ });85+ });
- @@ -0,0 +393,21 @@393+ truncated,394+ };395+}396+397+async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {398+ const cached = workspaceIndexCache.get(cwd);399+ if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {400+ return cached;401+ }402+403+ const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);404+ if (inFlight) {405+ return inFlight;406+ }407+408+ const nextPromise = buildWorkspaceIndex(cwd)409+ .then((next) => {410+ workspaceIndexCache.set(cwd, next);411+ while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {412+ const oldestKey = workspaceIndexCache.keys().next().value;413+ if (!oldestKey) break;
- @@ -66,13 +76,8 @@66-67- const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => {68- const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));69- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));70- };71-72- const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (73- projectCwd: string,74- candidates: ReadonlyArray<string>,75- ): Effect.fn.Return<string | null> {76- for (const candidate of candidates) {77- if (!isPathWithinProject(projectCwd, candidate)) {78- continue;76+function platformErrorToNone<A, R>(77+ effect: Effect.Effect<A, PlatformError.PlatformError, R>,78+): Effect.Effect<Option.Option<A>, never, R> {79+ return effect.pipe(80+ Effect.map(Option.some),81+ Effect.catchTag("PlatformError", () => Effect.succeed(Option.none<A>())),82+ );83+}
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
ff59c0e1-1c65-4d1d-85b1-5fb6ba5d773bYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Tip
💬 Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack.
👉 Get started
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share