Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix: improve project favicon detection for monorepos #1024

Closedponbac(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/1024/headopened View on GitHub

The XXL tag seems a little weird for this PR? It is a net +288 LoC, excluding test files.

What Changed

Improve project favicon detection without introducing a broad recursive search. Closes https://github.com/pingdotgg/t3code/issues/1020.

Rules, in order:

  • Check well-known favicon paths in the requested project root. Example: /repo/favicon.svg or /repo/public/favicon.ico.
  • If none exist, look for <link rel="icon" ... href="..."> tags or object-style { href, rel: "icon" } declarations in a small set of common source files, then resolve that target. Example: /repo/index.html points to /brand/logo.svg, so the route first tries /repo/public/brand/logo.svg and then /repo/brand/logo.svg.
  • If still nothing is found, repeat the same checks for first-level children of apps/ and packages/, plus other top-level directories in the requested root, using the same non-git directory ignore rules as workspaceEntries. Example: /repo/apps/web/public/favicon.png or /repo/frontend/public/favicon.png is found when the cwd is /repo.
  • Prefer a root match over nested workspace matches. Example: /repo/favicon.svg wins over /repo/apps/web/public/favicon.ico.
  • Fall back to the existing generated SVG when nothing is found.

I also extracted the shared gitignore probing into apps/server/src/gitIgnore.ts so both workspaceEntries and projectFaviconRoute use the same chunked git check-ignore --no-index -z --stdin filtering. I also extracted the shared workspace directory ignore policy into apps/server/src/workspaceIgnore.ts, so projectFaviconRoute now uses the same non-git skip rules as workspaceEntries when scanning nested roots instead of keeping a separate ignore list.

Why

The current behavior misses common monorepo layouts where the favicon lives under an app directory instead of the repo root.

There was already an earlier PR for this in the upstream repo: https://github.com/pingdotgg/t3code/pull/690. That version was larger and messier. This keeps the rules simple on purpose, leaving more extensive changes to project icons for trusted maintainers.

UI Changes

Not applicable.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • I included before/after screenshots for any UI changes
  • I included a video for animation/interaction changes

Note

Improve project favicon detection to support monorepos with gitignore filtering

  • Rewrites ProjectFaviconResolver.resolvePath to search nested apps/, packages/, and top-level child directories when no root favicon is found, enabling monorepo support.
  • Adds gitignore-aware filtering via new gitIgnore.ts utilities (filterGitIgnoredPaths, isInsideGitWorkTree) that stream candidates to git check-ignore in 256 KiB chunks.
  • Introduces workspaceIgnore.ts to skip well-known directories (.git, node_modules, .next, dist, etc.) during directory traversal.
  • Adds workspaceEntries.ts for a cacheable, git-backed or filesystem-fallback workspace index with fuzzy-ranked search.
  • Fixes a missing FileSystem service injection in the static file handler in wsServer.ts that previously caused runtime errors.
  • Behavioral Change: resolver now fails open on filesystem or git errors (treats unreadable paths as misses) rather than throwing.
📊 Macroscope summarized c01d2ee. 6 files reviewed, 4 issues evaluated, 1 issue filtered, 2 comments posted

🗂️ Filtered Issues

apps/server/src/workspaceEntries.ts — 1 comment posted, 3 evaluated, 1 filtered
  • line 427: Race condition in clearWorkspaceIndexCache: deleting from inFlightWorkspaceIndexBuilds does not cancel the in-flight promise. When that promise completes, its .then() handler will call workspaceIndexCache.set(cwd, next), re-populating the cache with potentially stale data after it was intentionally cleared. This defeats the purpose of clearing the cache. [ Already posted ]
>

Note

Medium Risk Modifies server-side favicon resolution and adds git-driven ignore filtering/search across workspace roots, which could affect file discovery performance and edge cases around path/permission handling. Git/process failures are handled fail-open, reducing risk of hiding files but still changing behavior.

Overview Project favicon resolution is expanded to better support monorepos. The resolver now checks well-known favicon paths and icon metadata in common source files in the requested root, then repeats the same checks across first-level apps/, packages/, and other top-level directories (skipping ignored workspace dirs), preferring root matches before falling back to the generated SVG.

Gitignore-aware filtering is added and shared. New gitIgnore.ts provides isInsideGitWorkTree and chunked filterGitIgnoredPaths (git check-ignore --no-index -z --stdin) with fail-open behavior; both the favicon resolver and the new workspaceEntries.ts use this to avoid considering gitignored candidates.

Testing and wiring updates. New unit tests cover gitignore chunking/fail-open and expanded favicon route scenarios (nested roots, unreadable files, gitignored root/app/source cases), and wsServer.ts now provides FileSystem to the static-file handler Effect pipeline.

Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 7404ccc6eaac85417693ba4996d2973b7f9cbd02. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: ff59c0e1-1c65-4d1d-85b1-5fb6ba5d773b

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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.

      • Generate code and open pull requests
      • Plan features and break down work
      • Investigate incidents and troubleshoot customer tickets together
      • Automate recurring tasks and respond to alerts with triggers
      • Summarize progress and report instantly

      Built for teams:

      • Shared memory across your entire org—no repeating context
      • Per-thread sandboxes to safely plan and execute work
      • Governance built-in—scoped access, auditability, and budget controls

      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
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. 💡 Codex Review

      Here are some automated review suggestions for this pull request.

      Reviewed commit: a4a8d330eb

      ℹ️ About Codex in GitHub

      Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

      • Open a pull request for review
      • Mark a draft as ready
      • Comment "@codex review".

      If Codex has suggestions, it will comment; otherwise it will react with 👍.

      Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    4. My 2c

      getIgnore.ts should be separated into individual commands for isInsideGitWorkTree, filterGitIgnoredPaths. You've done the right think pulling it out, but it could go further.

      I would add unit tests for this file rather than relying on integration tests.

      Since this is a new file, I would also add some solid docblocks to provide good human and AI context for the decisions being made. Hopefully the reviewers will pick that up and think it's a good idea for their code standards.

    5. ponbac(GitHub profile, opens in a new tab)commented

      My 2c

      getIgnore.ts should be separated into individual commands for isInsideGitWorkTree, filterGitIgnoredPaths. You've done the right think pulling it out, but it could go further.

      I would add unit tests for this file rather than relying on integration tests.

      Since this is a new file, I would also add some solid docblocks to provide good human and AI context for the decisions being made. Hopefully the reviewers will pick that up and think it's a good idea for their code standards.

      Not sure about separating them right now, but I also feel like isInsideGitWorkTree() should live somewhere else. It does not really have anything to do with .gitignore.

      I agree with the unit tests, added now.

      Also added an explanatory comment to the filterGitIgnoredPaths(). I should maybe add additional ones, but I am not sure what is preferred here.

    6. @@ -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 root
      164+ // 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));

      orElseSucceed cannot catch Effect.promise defects

      Low Severity

      Effect.promise converts promise rejections into defects (unchecked exceptions), but Effect.orElseSucceed only catches expected (typed) errors. The fallback () => uncachedRelativePaths is unreachable — if filterGitIgnoredPaths ever rejects, the defect propagates instead of gracefully falling back. Compare with the isInsideGitWorkTree call at line 392–393, which correctly uses .catch(() => false) on the promise itself before wrapping with Effect.promise. Using Effect.tryPromise here instead of Effect.promise would make orElseSucceed actually effective.

      Fix in Cursor Fix in Web
    7. @@ -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 {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/workspaceEntries.ts:425

      clearWorkspaceIndexCache deletes entries from workspaceIndexCache and inFlightWorkspaceIndexBuilds, but any in-flight buildWorkspaceIndex promise (already spawned before the clear) will still execute its .then() handler and repopulate workspaceIndexCache after the function returns. This means a caller who clears the cache to force a fresh rebuild may unexpectedly receive stale data from the completing in-flight build instead of a new index.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/workspaceEntries.ts around line 425:
      
      `clearWorkspaceIndexCache` deletes entries from `workspaceIndexCache` and `inFlightWorkspaceIndexBuilds`, but any in-flight `buildWorkspaceIndex` promise (already spawned before the clear) will still execute its `.then()` handler and repopulate `workspaceIndexCache` after the function returns. This means a caller who clears the cache to force a fresh rebuild may unexpectedly receive stale data from the completing in-flight build instead of a new index.
      
      Evidence trail:
      - apps/server/src/workspaceEntries.ts lines 408-421 (REVIEWED_COMMIT): Promise creation with `.then()` handler that unconditionally sets `workspaceIndexCache.set(cwd, next)`
      - apps/server/src/workspaceEntries.ts lines 425-428 (REVIEWED_COMMIT): `clearWorkspaceIndexCache` deletes from maps but cannot cancel the running promise
      - apps/server/src/workspaceEntries.ts lines 34-35 (REVIEWED_COMMIT): Cache definitions as module-level Maps
    8. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      There are 3 total unresolved issues (including 1 from previous review).

      Fix All in Cursor Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard?tab=bugbot).
      @@ -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+}

      Entire new file is dead code, never imported

      Medium Severity

      The entire 453-line workspaceEntries.ts file is dead code. Its exports clearWorkspaceIndexCache and searchWorkspaceEntries are not imported anywhere in the codebase. The file duplicates nearly all logic from apps/server/src/workspace/Layers/WorkspaceEntries.ts (the Effect-based service version) using raw async functions instead. All existing consumers continue to use WorkspaceEntriesLive from workspace/Layers/WorkspaceEntries.ts.

      Fix in Cursor Fix in Web
      @@ -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);

      Favicon probe reads entire file content unnecessarily

      Low Severity

      findFirstReadableFaviconPath calls readFileIfExists with readFile (full binary read) for each favicon candidate, but only uses the resulting path — the file content is discarded. Since resolveExistingPath already confirms the file exists via realPath and stat, the full content read is redundant. The route handler in projectFaviconRoute.ts then reads the same file again to serve it, doubling I/O for potentially large PNG/ICO files.

      Fix in Cursor Fix in Web
    9. @@ -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;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/workspaceEntries.ts:336

      Line 336 skips nested directories with ignored names by checking isPathInIgnoredWorkspaceDirectory(dirent.name) with only the directory name. This incorrectly excludes paths like src/node_modules because the check passes only "node_modules", and the function looks at the first segment of the input path. However, src/node_modules should be allowed since only the root-level directory is meant to be ignored. The filesystem fallback incorrectly filters these nested directories while buildWorkspaceIndexFromGit correctly includes them (it checks full paths). Consider using the full relativePath instead of dirent.name for the directory ignore check.

      -        if (dirent.isDirectory() && isPathInIgnoredWorkspaceDirectory(dirent.name)) {
      +        if (dirent.isDirectory() && isPathInIgnoredWorkspaceDirectory(relativePath)) {
      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/workspaceEntries.ts around lines 336-337:
      
      Line 336 skips nested directories with ignored names by checking `isPathInIgnoredWorkspaceDirectory(dirent.name)` with only the directory name. This incorrectly excludes paths like `src/node_modules` because the check passes only `"node_modules"`, and the function looks at the first segment of the input path. However, `src/node_modules` should be allowed since only the root-level directory is meant to be ignored. The filesystem fallback incorrectly filters these nested directories while `buildWorkspaceIndexFromGit` correctly includes them (it checks full paths). Consider using the full `relativePath` instead of `dirent.name` for the directory ignore check.
      
      Evidence trail:
      apps/server/src/workspaceEntries.ts lines 336 (checks `dirent.name` only), 343-345 (constructs `relativePath` after the early skip), 248 (git version uses full path), 256 (git version uses full directoryPath). apps/server/src/workspaceIgnore.ts lines 13-21 (function checks first segment only). Commit: REVIEWED_COMMIT
    10. @@ -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;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/workspaceEntries.ts:411

      The cache eviction loop uses !oldestKey to check for undefined, but !"" evaluates to true, so if cwd is an empty string the loop breaks early instead of deleting the entry. This allows the cache to exceed WORKSPACE_CACHE_MAX_KEYS. Consider using oldestKey === undefined instead.

      Suggested change
      411- while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
      412- const oldestKey = workspaceIndexCache.keys().next().value;
      413- if (!oldestKey) break;
      411+ if (oldestKey === undefined) break;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/workspaceEntries.ts around lines 411-413:
      
      The cache eviction loop uses `!oldestKey` to check for undefined, but `!""` evaluates to `true`, so if `cwd` is an empty string the loop breaks early instead of deleting the entry. This allows the cache to exceed `WORKSPACE_CACHE_MAX_KEYS`. Consider using `oldestKey === undefined` instead.
      
      Evidence trail:
      apps/server/src/workspaceEntries.ts lines 411-415 at REVIEWED_COMMIT - shows the cache eviction loop using `if (!oldestKey) break;` which would break on empty string since `!""` === `true`. The loop should use `oldestKey === undefined` to correctly detect when the iterator is exhausted.
    11. @@ -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+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🔴 Critical Layers/ProjectFaviconResolver.ts:76

      Errors from PlatformError.PlatformError are not caught by Effect.catchTag("PlatformError", ...) because the union type has concrete tags like "SystemError" and "BadArgument", not "PlatformError". When file system operations fail, the error propagates instead of returning Option.none(). Consider using Effect.catchAll or catching the specific error tags.

      -  return effect.pipe(
      -    Effect.map(Option.some),
      -    Effect.catchTag("PlatformError", () => Effect.succeed(Option.none<A>())),
      -  );
      +  return effect.pipe(
      +    Effect.map(Option.some),
      +    Effect.catchAll(() => Effect.succeed(Option.none<A>())),
      +  );
      🤖 Copy this AI Prompt to have your agent fix this:
      In file apps/server/src/project/Layers/ProjectFaviconResolver.ts around lines 76-83:
      
      Errors from `PlatformError.PlatformError` are not caught by `Effect.catchTag("PlatformError", ...)` because the union type has concrete tags like `"SystemError"` and `"BadArgument"`, not `"PlatformError"`. When file system operations fail, the error propagates instead of returning `Option.none()`. Consider using `Effect.catchAll` or catching the specific error tags.
      
      Evidence trail:
      1. apps/server/src/project/Layers/ProjectFaviconResolver.ts lines 72-78 (REVIEWED_COMMIT) - shows `platformErrorToNone` function using `Effect.catchTag("PlatformError", ...)`
      2. https://github.com/Effect-TS/effect/blob/main/packages/platform/src/Error.ts - shows `PlatformError = BadArgument | SystemError` union type, where `BadArgument` has `_tag: "BadArgument"` and `SystemError` has `_tag: "SystemError"` (neither has `_tag: "PlatformError"`)
      3. package.json shows effect version 4.0.0-beta.45
    12. Closing because current main already contains the well-known-path favicon resolver and its tests.

      This was closed as part of a large repo-wide maintenance sweep. If you think it's still relevant, please reopen.

    13. juliusmarminge closed this

Sign in to join this conversation.