feat(desktop): choose external project icons (#7823)

This commit is contained in:
Bilal Bakr authored and GitHub committed 2026-08-21 18:08:10 -04:00
1 parent b381fdb12c
commit 44e4a7071d
19 files changed
+485 -64

No files matched your search

@@ -53,6 +53,34 @@ describe("ElectronDialog", () => {
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens a single-file picker when multiple selections are disabled", () =>
Effect.gen(function* () {
showOpenDialogMock.mockResolvedValue({
canceled: false,
filePaths: ["/pictures/icon.png"],
});
const dialog = yield* ElectronDialog.ElectronDialog;
const paths = yield* dialog.pickFiles({
owner: Option.none(),
defaultPath: Option.some("/project"),
filters: [{ name: "Images", extensions: ["png"] }],
multiple: false,
});
assert.deepEqual(paths, ["/pictures/icon.png"]);
assert.deepEqual(showOpenDialogMock.mock.calls, [
[
{
defaultPath: "/project",
filters: [{ name: "Images", extensions: ["png"] }],
properties: ["openFile"],
},
],
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
+2 -1
View File
@@ -84,6 +84,7 @@ export interface ElectronDialogPickFilesInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
readonly filters: readonly Electron.FileFilter[];
readonly multiple: boolean;
}
export class ElectronDialog extends Context.Service<
@@ -144,7 +145,7 @@ export const make = ElectronDialog.of({
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = {
properties: ["openFile", "multiSelections"],
properties: input.multiple ? ["openFile", "multiSelections"] : ["openFile"],
filters: [...input.filters],
...(defaultPath === null ? {} : { defaultPath }),
};
@@ -39,6 +39,7 @@ import {
openExternal,
probeRemoteEditors,
pickFolder,
pickProjectFavicon,
pickThemeFiles,
setTheme,
showContextMenu,
@@ -82,6 +83,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
yield* ipc.handle(pickProjectFavicon);
yield* ipc.handle(pickThemeFiles);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
+1
View File
@@ -1,4 +1,5 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon";
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
+42 -1
View File
@@ -2,13 +2,19 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { vi } from "vite-plus/test";
import type * as Electron from "electron";
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import { getLocalEnvironmentBootstraps, getWindowFullscreenState } from "./window.ts";
import {
getLocalEnvironmentBootstraps,
getWindowFullscreenState,
pickProjectFavicon,
} from "./window.ts";
const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "wsl.exe",
@@ -146,3 +152,38 @@ describe("getWindowFullscreenState", () => {
);
});
});
describe("pickProjectFavicon", () => {
it.effect("opens a single-image picker from the project directory", () =>
Effect.gen(function* () {
const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"]));
const result = yield* pickProjectFavicon.handler("/project").pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }),
Layer.mock(ElectronWindow.ElectronWindow)({
focusedMainOrFirst: Effect.succeed(Option.none()),
}),
),
),
);
assert.strictEqual(result, "/pictures/icon.png");
assert.deepEqual(pickFiles.mock.calls, [
[
{
owner: Option.none(),
defaultPath: Option.some("/project"),
multiple: false,
filters: [
{
name: "Images",
extensions: ["avif", "gif", "ico", "jpeg", "jpg", "png", "svg", "webp"],
},
],
},
],
]);
}),
);
});
+24
View File
@@ -12,6 +12,7 @@ import {
type DesktopEnvironmentBootstrap,
type PickedThemeFile,
} from "@t3tools/contracts";
import { WORKSPACE_IMAGE_PREVIEW_EXTENSIONS } from "@t3tools/shared/filePreview";
import { isCommandAvailable } from "@t3tools/shared/shell";
import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
@@ -234,6 +235,28 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
}),
});
export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
payload: Schema.UndefinedOr(Schema.String),
result: Schema.NullOr(Schema.String),
handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const paths = yield* dialog.pickFiles({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: Option.fromNullishOr(initialPath),
multiple: false,
filters: [
{
name: "Images",
extensions: WORKSPACE_IMAGE_PREVIEW_EXTENSIONS.map((extension) => extension.slice(1)),
},
],
});
return paths[0] ?? null;
}),
});
export const setTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
@@ -323,6 +346,7 @@ export const pickThemeFiles = DesktopIpc.makeIpcMethod({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
filters: [{ name: "JSON", extensions: ["json"] }],
multiple: true,
});
if (paths.length === 0) {
return null;
+2
View File
@@ -101,6 +101,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
pickProjectFavicon: (initialPath) =>
ipcRenderer.invoke(IpcChannels.PICK_PROJECT_FAVICON_CHANNEL, initialPath),
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
@@ -287,6 +287,44 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-workspace-",
});
const pictures = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-pictures-",
});
const externalPath = path.join(pictures, "custom.png");
const siblingPath = path.join(pictures, "sibling.png");
yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
const canonicalPath = yield* fileSystem.realPath(externalPath);
const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
const result = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
projectFaviconPath: externalPath,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
expect(result.sourcePath).toBe(externalPath);
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
expect(
yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
).toEqual({ kind: "file", path: canonicalPath });
const tamperedSuffixResult = yield* resolveAsset(
suffix.slice(0, separatorIndex),
"sibling.png",
);
expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
}).pipe(Effect.provide(testLayer)),
);
it.effect("ignores a client favicon path hint", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+75 -24
View File
@@ -88,6 +88,12 @@ const AssetClaimsSchema = Schema.Union([
relativePath: Schema.NullOr(Schema.String),
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("project-favicon-external"),
filePath: Schema.String,
expiresAt: Schema.Number,
}),
]);
type AssetClaims = typeof AssetClaimsSchema.Type;
@@ -124,6 +130,17 @@ const optionOnNotFound = <A, R>(
}),
);
const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
filePath: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const canonicalFile = yield* optionOnNotFound(fileSystem.realPath(filePath));
if (Option.isNone(canonicalFile)) return null;
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
});
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
const fileSystem = yield* FileSystem.FileSystem;
@@ -300,13 +317,24 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}),
),
);
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
if (relativePath && !isWorkspaceImagePreviewPath(relativePath)) {
const isExternalOverride =
faviconPath !== null &&
input.projectFaviconPath !== undefined &&
path.isAbsolute(input.projectFaviconPath) &&
path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
const relativePath =
faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
if (sourceFaviconPath && !isWorkspaceImagePreviewPath(sourceFaviconPath)) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
}
sourcePath = relativePath ?? undefined;
const canonicalFaviconPath = relativePath
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
sourcePath = sourceFaviconPath ?? undefined;
const canonicalFaviconPath = sourceFaviconPath
? yield* (
isExternalOverride
? resolveCanonicalFile(sourceFaviconPath)
: resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
).pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconInspectionError({
@@ -316,27 +344,35 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
),
)
: null;
if (relativePath && !canonicalFaviconPath) {
if (sourceFaviconPath && !canonicalFaviconPath) {
return yield* new AssetProjectFaviconNotFoundError({
resource: input.resource,
});
}
claims = {
version: 1,
kind: "project-favicon",
workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceResolutionError({
resource: input.resource,
cause,
}),
),
),
relativePath,
expiresAt,
};
if (relativePath && canonicalFaviconPath) {
claims =
isExternalOverride && canonicalFaviconPath
? {
version: 1,
kind: "project-favicon-external",
filePath: canonicalFaviconPath,
expiresAt,
}
: {
version: 1,
kind: "project-favicon",
workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceResolutionError({
resource: input.resource,
cause,
}),
),
),
relativePath,
expiresAt,
};
if (sourceFaviconPath && canonicalFaviconPath) {
const crypto = yield* Crypto.Crypto;
const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
Effect.mapError(
@@ -357,7 +393,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}),
),
);
fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(relativePath)}`;
fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
} else {
fileName = PROJECT_FAVICON_FALLBACK_MARKER;
}
@@ -375,7 +411,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
}),
),
);
if (claims.kind === "project-favicon") {
if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
const issuedAt = yield* Clock.currentTimeMillis;
expiresAt =
(Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
@@ -441,6 +477,21 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
}
if (claims.kind === "project-favicon-external") {
const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to resolve canonical asset path.", {
filePath: claims.filePath,
cause,
}),
),
Effect.orElseSucceed(() => null),
);
return faviconPath === claims.filePath
? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset)
: null;
}
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
@@ -91,6 +91,21 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
}),
);
it.effect("uses a saved project favicon outside the workspace", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
const pictures = yield* makeTempDir;
yield* writeTextFile(pictures, "custom.png", "image");
const externalPath = path.join(pictures, "custom.png");
const resolved = yield* resolver.resolvePath(cwd, externalPath);
expect(resolved).toBe(externalPath);
}),
);
it.effect("falls back when a saved override is missing from a checkout", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
@@ -137,22 +137,25 @@ export const make = Effect.gen(function* () {
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
projectCwd: string,
relativeCandidates: ReadonlyArray<string>,
candidateScope: "workspace" | "filesystem",
): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {
for (const relativePath of relativeCandidates) {
const candidate = yield* workspacePaths
.resolveRelativePathWithinRoot({
workspaceRoot: projectCwd,
relativePath,
})
.pipe(
Effect.map(Option.some),
Effect.catchTags({
WorkspacePathOutsideRootError: () =>
Effect.succeed(
Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
),
}),
);
const candidate = yield* (
candidateScope === "filesystem" && path.isAbsolute(relativePath)
? Effect.succeed({ absolutePath: relativePath, relativePath })
: workspacePaths.resolveRelativePathWithinRoot({
workspaceRoot: projectCwd,
relativePath,
})
).pipe(
Effect.map(Option.some),
Effect.catchTags({
WorkspacePathOutsideRootError: () =>
Effect.succeed(
Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),
),
}),
);
if (Option.isNone(candidate)) {
continue;
}
@@ -191,7 +194,7 @@ export const make = Effect.gen(function* () {
// A grouped project's saved path can be absent from one checkout. Use it
// where it exists and retain automatic discovery for the other checkouts.
if (faviconPath !== undefined) {
const existing = yield* findExistingFile(projectCwd, [faviconPath]);
const existing = yield* findExistingFile(projectCwd, [faviconPath], "filesystem");
if (existing) {
return existing;
}
@@ -200,14 +203,18 @@ export const make = Effect.gen(function* () {
// A t3.json iconPath takes precedence over the well-known locations.
const projectFile = yield* projectFileLoader.load(projectCwd);
if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {
const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);
const existing = yield* findExistingFile(
projectCwd,
[projectFile.value.iconPath],
"workspace",
);
if (existing) {
return existing;
}
}
for (const candidate of FAVICON_CANDIDATES) {
const existing = yield* findExistingFile(projectCwd, [candidate]);
const existing = yield* findExistingFile(projectCwd, [candidate], "workspace");
if (existing) {
return existing;
}
@@ -251,7 +258,7 @@ export const make = Effect.gen(function* () {
if (!href) {
continue;
}
const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));
const existing = yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace");
if (existing) {
return existing;
}
+10 -17
View File
@@ -95,7 +95,13 @@ import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";
import { cn, isMacPlatform, isWindowsPlatform, newProjectId } from "../lib/utils";
import {
cn,
getLocalFileManagerName,
isMacPlatform,
isWindowsPlatform,
newProjectId,
} from "../lib/utils";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import {
@@ -147,7 +153,7 @@ import {
type ProviderInstanceEntry,
} from "../providerInstances";
import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";
import { CommandDialog, CommandDialogPopup } from "./ui/command";
import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "./ui/command";
import { Button } from "./ui/button";
import { Kbd, KbdGroup } from "./ui/kbd";
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -175,16 +181,6 @@ function projectFavicon(project: Project) {
);
}
function getLocalFileManagerName(platform: string): string {
if (isMacPlatform(platform)) {
return "Finder";
}
if (isWindowsPlatform(platform)) {
return "Explorer";
}
return "Files";
}
function getEnvironmentBrowsePlatform(os: string | null | undefined): string {
if (os === "windows") {
return "Win32";
@@ -2418,17 +2414,14 @@ function OpenCommandPaletteDialog(props: {
: undefined;
const footerTrailing = canOpenProjectFromFileManager ? (
<Button
variant="ghost"
size="xs"
className="h-auto px-2 text-muted-foreground text-xs hover:bg-transparent hover:text-foreground"
<CommandFooterAction
disabled={isPickingProjectFolder}
onClick={() => {
void handleOpenProjectFromFileManager();
}}
>
{`Open in ${fileManagerName}`}
</Button>
</CommandFooterAction>
) : null;
return (
@@ -0,0 +1,125 @@
import { EnvironmentId } from "@t3tools/contracts";
import type { ReactElement } from "react";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { visitElements } from "../../test/reactElementTree";
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
vi.mock("react", async (importOriginal) => {
const actual = await importOriginal<typeof import("react")>();
const { reactHookHarness } = await import("../../test/reactHookHarness");
return {
...actual,
useMemo: reactHookHarness.useMemo,
useState: reactHookHarness.useState,
};
});
vi.mock("react/compiler-runtime", async () => {
const { reactHookHarness } = await import("../../test/reactHookHarness");
return { c: reactHookHarness.useMemoCache };
});
vi.mock("@effect/atom-react", () => ({
useAtomValue: () => ({}),
}));
vi.mock("~/state/server", () => ({
primaryServerKeybindingsAtom: Symbol("keybindings"),
}));
vi.mock("~/hooks/useTheme", () => ({
useTheme: () => ({ resolvedTheme: "dark" }),
}));
vi.mock("../files/projectFilesQueryState", () => ({
useProjectFilePickerQuery: () => ({
entries: [],
error: null,
isPending: false,
matchedQuery: "",
}),
}));
vi.mock("../ui/toast", () => ({
toastManager: { add: vi.fn() },
}));
import { toastManager } from "../ui/toast";
import {
canPickExternalProjectFavicon,
ProjectFaviconPickerDialog,
} from "./ProjectFaviconPickerDialog";
describe("ProjectFaviconPickerDialog", () => {
beforeEach(() => {
hooks.reset();
vi.stubGlobal("navigator", { platform: "MacIntel" });
});
it("selects an image from the native file picker", async () => {
const onOpenChange = vi.fn();
const onPickExternal = vi.fn().mockResolvedValue("/Users/me/Pictures/icon.png");
const onSelect = vi.fn();
hooks.beginRender();
const picker = ProjectFaviconPickerDialog({
cwd: "/Users/me/project",
environmentId: EnvironmentId.make("local"),
onOpenChange,
onPickExternal,
onSelect,
open: true,
projectName: "Project",
} as Parameters<typeof ProjectFaviconPickerDialog>[0] & {
readonly onPickExternal: () => Promise<string | null>;
}) as ReactElement<Record<string, unknown>>;
const button = visitElements(picker, (element) => element.props.children === "Open in Finder");
expect(button).not.toBeNull();
(button?.props.onClick as (() => void) | undefined)?.();
await Promise.resolve();
await Promise.resolve();
expect(onPickExternal).toHaveBeenCalledTimes(1);
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");
});
it("hides the native picker for WSL project paths", () => {
expect(canPickExternalProjectFavicon("/home/me/project", "Win32")).toBe(false);
expect(canPickExternalProjectFavicon("C:\\Users\\me\\project", "Win32")).toBe(true);
});
it("keeps the dialog open when the native picker fails", async () => {
const onOpenChange = vi.fn();
const onSelect = vi.fn();
const props = {
cwd: "/Users/me/project",
environmentId: EnvironmentId.make("local"),
onOpenChange,
onPickExternal: vi.fn().mockRejectedValue(new Error("picker failed")),
onSelect,
open: true,
projectName: "Project",
} as Parameters<typeof ProjectFaviconPickerDialog>[0] & {
readonly onPickExternal: () => Promise<string | null>;
};
hooks.beginRender();
const picker = ProjectFaviconPickerDialog(props) as ReactElement<Record<string, unknown>>;
const button = visitElements(picker, (element) => element.props.children === "Open in Finder");
(button?.props.onClick as (() => void) | undefined)?.();
await Promise.resolve();
await Promise.resolve();
expect(onOpenChange).not.toHaveBeenCalled();
expect(onSelect).not.toHaveBeenCalled();
expect(toastManager.add).toHaveBeenCalledWith({
type: "error",
title: "Could not open image picker",
description: "picker failed",
});
});
});
@@ -1,9 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { isWindowsAbsolutePath } from "@t3tools/shared/path";
import { useMemo, useState } from "react";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { useTheme } from "~/hooks/useTheme";
import { getLocalFileManagerName, isWindowsPlatform } from "~/lib/utils";
import { CommandPaletteContent } from "../CommandPaletteContent";
import type { CommandPaletteActionItem } from "../CommandPalette.logic";
import { CommandPaletteResults } from "../CommandPaletteResults";
@@ -13,24 +15,30 @@ import {
PROJECT_FILE_PICKER_RESULT_LIMIT,
} from "../files/ProjectFilePicker.logic";
import { useProjectFilePickerQuery } from "../files/projectFilesQueryState";
import { CommandDialog, CommandDialogPopup } from "../ui/command";
import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "../ui/command";
import { toastManager } from "../ui/toast";
function emptyMessage(query: string, error: string | null, isPending: boolean): string {
if (error) return error;
if (isPending) return query.trim() ? "Searching project files…" : "Indexing project files…";
return query.trim() ? "No matching image files." : "No image files found.";
}
export function canPickExternalProjectFavicon(cwd: string, platform: string): boolean {
return !isWindowsPlatform(platform) || isWindowsAbsolutePath(cwd);
}
export function ProjectFaviconPickerDialog(props: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly onOpenChange: (open: boolean) => void;
readonly onPickExternal?: () => Promise<string | null>;
readonly onSelect: (path: string) => void;
readonly open: boolean;
readonly projectName: string;
}) {
const [query, setQuery] = useState("");
const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
const [isPickingExternal, setIsPickingExternal] = useState(false);
const result = useProjectFilePickerQuery(
props.environmentId,
props.cwd,
@@ -40,6 +48,10 @@ export function ProjectFaviconPickerDialog(props: {
);
const { resolvedTheme } = useTheme();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const pickExternal = props.onPickExternal;
const fileManagerName = getLocalFileManagerName(
typeof navigator === "undefined" ? "" : navigator.platform,
);
const items = useMemo<CommandPaletteActionItem[]>(
() =>
getProjectFilePickerMatches(result.entries, result.matchedQuery).map((match) => ({
@@ -67,6 +79,33 @@ export function ProjectFaviconPickerDialog(props: {
autoHighlight="always"
escapeLabel="Close"
footerActionLabel="Select icon"
footerTrailing={
pickExternal ? (
<CommandFooterAction
disabled={isPickingExternal}
onClick={() => {
setIsPickingExternal(true);
void pickExternal()
.then((path) => {
if (!path) return;
props.onOpenChange(false);
props.onSelect(path);
})
.catch((error: unknown) => {
toastManager.add({
type: "error",
title: "Could not open image picker",
description:
error instanceof Error ? error.message : "An error occurred.",
});
})
.finally(() => setIsPickingExternal(false));
}}
>
{`Open in ${fileManagerName}`}
</CommandFooterAction>
) : null
}
inputProps={{ placeholder: "Search image files…" }}
mode="none"
onItemHighlighted={(value) => {
@@ -108,7 +108,10 @@ import {
SettingsRow,
SettingsSection,
} from "./settingsLayout";
import { ProjectFaviconPickerDialog } from "./ProjectFaviconPickerDialog";
import {
canPickExternalProjectFavicon,
ProjectFaviconPickerDialog,
} from "./ProjectFaviconPickerDialog";
export const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = {
repository: "Group by repository",
@@ -286,6 +289,7 @@ export function ProjectSettingsPanel({ projectKey }: { projectKey: string }) {
function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
const navigate = useNavigate();
const primaryEnvironmentId = usePrimaryEnvironmentId();
const settings = usePrimarySettings();
const updateClientSettings = useUpdateClientSettings();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
@@ -319,6 +323,15 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
(member) => member.environmentId === group.environmentId && member.id === group.id,
) ?? group.memberProjects[0]!;
const faviconPath = representative.faviconPath ?? null;
const pickProjectFavicon =
typeof window !== "undefined" &&
group.memberProjects.every(
(member) =>
member.environmentId === primaryEnvironmentId &&
canPickExternalProjectFavicon(member.workspaceRoot, navigator.platform),
)
? window.desktopBridge?.pickProjectFavicon
: undefined;
const threadCountByMember = useMemo(() => {
const counts = new Map<string, number>();
@@ -1166,6 +1179,9 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
cwd={representative.workspaceRoot}
environmentId={representative.environmentId}
onOpenChange={setFaviconPickerOpen}
{...(pickProjectFavicon
? { onPickExternal: () => pickProjectFavicon(representative.workspaceRoot) }
: {})}
onSelect={(path) => void setFaviconPath(path)}
open={faviconPickerOpen}
projectName={group.displayName}
+16
View File
@@ -16,6 +16,7 @@ import {
AutocompleteSeparator,
} from "~/components/ui/autocomplete";
import { DIALOG_BACKDROP_CLASS, DIALOG_POPUP_CLASS } from "~/components/ui/dialog-styles";
import { Button } from "~/components/ui/button";
const CommandDialog = CommandDialogPrimitive.Root;
@@ -225,6 +226,20 @@ function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
);
}
function CommandFooterAction({
className,
...props
}: Omit<React.ComponentProps<typeof Button>, "size" | "variant">) {
return (
<Button
{...props}
variant="ghost-muted"
size="xs"
className={cn("h-auto px-2 text-xs hover:bg-transparent", className)}
/>
);
}
export {
CommandCreateHandle,
Command,
@@ -234,6 +249,7 @@ export {
CommandDialogTrigger,
CommandEmpty,
CommandFooter,
CommandFooterAction,
CommandGroup,
CommandGroupLabel,
CommandInput,
+11 -1
View File
@@ -1,5 +1,15 @@
import { describe, assert, it } from "vite-plus/test";
import { isWindowsPlatform } from "./utils";
import { getLocalFileManagerName, isWindowsPlatform } from "./utils";
describe("getLocalFileManagerName", () => {
it.each([
["MacIntel", "Finder"],
["Win32", "Explorer"],
["Linux", "Files"],
])("uses the %s file manager name", (platform, expected) => {
assert.strictEqual(getLocalFileManagerName(platform), expected);
});
});
describe("isWindowsPlatform", () => {
it("matches Windows platform identifiers", () => {
+10
View File
@@ -20,6 +20,16 @@ export function isLinuxPlatform(platform: string): boolean {
return /linux/i.test(platform);
}
export function getLocalFileManagerName(platform: string): string {
if (isMacPlatform(platform)) {
return "Finder";
}
if (isWindowsPlatform(platform)) {
return "Explorer";
}
return "Files";
}
export function randomHex(byteLength: number): string {
return Encoding.encodeHex(globalThis.crypto.getRandomValues(new Uint8Array(byteLength)));
}
+2
View File
@@ -1110,6 +1110,8 @@ export interface DesktopBridge {
setWslDistro: (distro: string | null) => Promise<DesktopWslState>;
setWslOnly: (enabled: boolean) => Promise<DesktopWslState>;
pickFolder: (options?: PickFolderOptions) => Promise<string | null>;
/** Optional while older desktop shells can host a newer web client. */
pickProjectFavicon?: (initialPath?: string) => Promise<string | null>;
/**
* Multi-select JSON file picker that opens in the VS Code extensions
* directory when one exists. Optional: older desktop builds lack it, and