feat(web): project icons can be chosen manually (#5775)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-08-08 22:13:16 -07:00
1 parent 05eb051184
commit 076e9048dc
48 files changed
+740 -45

No files matched your search

+1
View File
@@ -68,6 +68,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Customize a project icon](./docs/user/project-settings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
@@ -24,13 +24,18 @@ export function ProjectFavicon(props: {
readonly size?: number;
readonly projectTitle: string;
readonly workspaceRoot?: string | null;
readonly faviconPath?: string | null;
}) {
const size = props.size ?? 42;
const faviconUrl = useAssetUrl(
props.environmentId,
props.workspaceRoot === null || props.workspaceRoot === undefined
? null
: { _tag: "project-favicon", cwd: props.workspaceRoot },
: {
_tag: "project-favicon",
cwd: props.workspaceRoot,
...(props.faviconPath ? { path: props.faviconPath } : {}),
},
);
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
const cacheKey =
@@ -368,6 +368,7 @@ function ProjectGroupLabel(props: {
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
faviconPath={props.project.faviconPath}
projectTitle={props.project.title}
size={18}
workspaceRoot={props.project.workspaceRoot}
@@ -296,6 +296,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={scope.representative.environmentId}
faviconPath={scope.representative.faviconPath}
size={20}
projectTitle={scope.title}
workspaceRoot={scope.representative.workspaceRoot}
@@ -330,6 +331,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
>
<ProjectFavicon
environmentId={project.environmentId}
faviconPath={project.faviconPath}
size={18}
projectTitle={project.title}
workspaceRoot={project.workspaceRoot}
@@ -134,6 +134,7 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
>
<ProjectFavicon
environmentId={props.project.environmentId}
faviconPath={props.project.faviconPath}
open={!props.collapsed}
size={compact ? 22 : 18}
projectTitle={props.project.title}
@@ -230,6 +230,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
{props.project ? (
<ProjectFavicon
environmentId={pendingTask.message.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={projectTitle}
workspaceRoot={props.project.workspaceRoot}
@@ -630,6 +631,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
@@ -818,6 +820,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<View className="opacity-40">
<ProjectFavicon
environmentId={thread.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
+83 -1
View File
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
@@ -225,6 +225,7 @@ describe("AssetAccess", () => {
const faviconResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
expect(faviconResult.sourcePath).toBe("favicon.svg");
expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
expect(
yield* issueAssetUrl({
@@ -253,6 +254,7 @@ describe("AssetAccess", () => {
resource: { _tag: "project-favicon", cwd: root },
});
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
expect(fallbackResult.sourcePath).toBeUndefined();
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
expect(
@@ -264,6 +266,86 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues project favicon capabilities for a saved override", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-override-",
});
yield* fileSystem.makeDirectory(path.join(root, "brand"));
yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
const result = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
projectFaviconPath: "brand/custom.svg",
});
expect(result.sourcePath).toBe("brand/custom.svg");
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
}).pipe(Effect.provide(testLayer)),
);
it.effect("ignores a client favicon path hint", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-hint-",
});
yield* fileSystem.makeDirectory(path.join(root, "brand"));
yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
const result = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
projectFaviconPath: "brand/saved.svg",
});
expect(result.sourcePath).toBe("brand/saved.svg");
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
}).pipe(Effect.provide(testLayer)),
);
it.effect("keeps automatic favicon resolution separate from a saved override", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-automatic-",
});
yield* fileSystem.makeDirectory(path.join(root, "brand"));
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
const result = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
expect(result.sourcePath).toBe("favicon.svg");
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects a resolved project favicon with a non-image extension", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-type-",
});
yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
const error = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
projectFaviconPath: "secret.txt",
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
}).pipe(Effect.provide(testLayer)),
);
it.effect("buckets project favicon expiry after content hashing", () =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
+18 -9
View File
@@ -169,6 +169,7 @@ const resolveCanonicalWorkspaceFileForRequest = (input: {
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
readonly resource: AssetResource;
readonly workspaceRoot?: string;
readonly projectFaviconPath?: string;
}) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -176,6 +177,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
let claims: AssetClaims;
let fileName: string;
let sourcePath: string | undefined;
switch (input.resource._tag) {
case "workspace-file": {
@@ -287,16 +289,22 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
),
);
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconResolutionError({
resource: input.resource,
cause,
}),
),
);
const faviconPath = yield* faviconResolver
.resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
.pipe(
Effect.mapError(
(cause) =>
new AssetProjectFaviconResolutionError({
resource: input.resource,
cause,
}),
),
);
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
if (relativePath && !isWorkspaceImagePreviewPath(relativePath)) {
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
}
sourcePath = relativePath ?? undefined;
const canonicalFaviconPath = relativePath
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
Effect.mapError(
@@ -379,6 +387,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
return {
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
expiresAt,
...(sourcePath !== undefined ? { sourcePath } : {}),
};
});
@@ -2764,15 +2764,18 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5",
},
faviconPath: "brand/icon.svg",
});
const projectRows = yield* sql<{
readonly scriptsJson: string;
readonly defaultModelSelection: string;
readonly faviconPath: string | null;
}>`
SELECT
scripts_json AS "scriptsJson",
default_model_selection_json AS "defaultModelSelection"
default_model_selection_json AS "defaultModelSelection",
favicon_path AS "faviconPath"
FROM projection_projects
WHERE project_id = 'project-scripts'
`;
@@ -2781,6 +2784,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
scriptsJson:
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}',
faviconPath: "brand/icon.svg",
},
]);
}),
@@ -496,6 +496,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
workspaceRoot: event.payload.workspaceRoot,
defaultModelSelection: event.payload.defaultModelSelection,
defaultThreadEnvMode: null,
faviconPath: event.payload.faviconPath ?? null,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -522,6 +523,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: event.payload.defaultThreadEnvMode }
: {}),
...(event.payload.faviconPath !== undefined
? { faviconPath: event.payload.faviconPath }
: {}),
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
updatedAt: event.payload.updatedAt,
});
@@ -275,6 +275,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
faviconPath: null,
scripts: [
{
id: "script-1",
@@ -394,6 +395,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
faviconPath: null,
scripts: [
{
id: "script-1",
@@ -317,6 +317,7 @@ function mapProjectShellRow(
repositoryIdentity,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
faviconPath: row.faviconPath ?? null,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -393,6 +394,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -847,6 +849,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -870,6 +873,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -1547,6 +1551,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
faviconPath: row.faviconPath ?? null,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -1677,6 +1682,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
defaultThreadEnvMode: row.defaultThreadEnvMode,
faviconPath: row.faviconPath ?? null,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -2169,6 +2175,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
repositoryIdentity,
defaultModelSelection: option.value.defaultModelSelection,
defaultThreadEnvMode: option.value.defaultThreadEnvMode,
faviconPath: option.value.faviconPath ?? null,
scripts: option.value.scripts,
createdAt: option.value.createdAt,
updatedAt: option.value.updatedAt,
@@ -94,6 +94,47 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
}),
);
it.effect("propagates a project favicon path in project.meta.update", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const readModel = yield* projectEvent(createEmptyReadModel(now), {
sequence: 1,
eventId: asEventId("evt-project-create-favicon"),
aggregateKind: "project",
aggregateId: asProjectId("project-favicon"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-favicon"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-favicon"),
metadata: {},
payload: {
projectId: asProjectId("project-favicon"),
title: "Favicon",
workspaceRoot: "/tmp/favicon",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const result = yield* decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-favicon"),
projectId: asProjectId("project-favicon"),
faviconPath: "brand/icon.svg",
},
readModel,
});
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.meta-updated");
expect((event.payload as { faviconPath?: string }).faviconPath).toBe("brand/icon.svg");
}),
);
it.effect("rejects project.create for an active workspace root that already exists", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
+2
View File
@@ -250,6 +250,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
title: command.title,
workspaceRoot: command.workspaceRoot,
defaultModelSelection: command.defaultModelSelection ?? null,
faviconPath: null,
scripts: [],
createdAt: command.createdAt,
updatedAt: command.createdAt,
@@ -290,6 +291,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: command.defaultThreadEnvMode }
: {}),
...(command.faviconPath !== undefined ? { faviconPath: command.faviconPath } : {}),
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
updatedAt: occurredAt,
},
@@ -215,6 +215,7 @@ export function projectEvent(
workspaceRoot: payload.workspaceRoot,
defaultModelSelection: payload.defaultModelSelection,
defaultThreadEnvMode: null,
faviconPath: payload.faviconPath ?? null,
scripts: payload.scripts,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
@@ -250,6 +251,9 @@ export function projectEvent(
...(payload.defaultThreadEnvMode !== undefined
? { defaultThreadEnvMode: payload.defaultThreadEnvMode }
: {}),
...(payload.faviconPath !== undefined
? { faviconPath: payload.faviconPath }
: {}),
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
updatedAt: payload.updatedAt,
}
@@ -36,6 +36,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root,
default_model_selection_json,
default_thread_env_mode,
favicon_path,
scripts_json,
created_at,
updated_at,
@@ -47,6 +48,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.workspaceRoot},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${row.defaultThreadEnvMode},
${row.faviconPath ?? null},
${JSON.stringify(row.scripts)},
${row.createdAt},
${row.updatedAt},
@@ -58,6 +60,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root = excluded.workspace_root,
default_model_selection_json = excluded.default_model_selection_json,
default_thread_env_mode = excluded.default_thread_env_mode,
favicon_path = excluded.favicon_path,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
@@ -76,6 +79,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -96,6 +100,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_thread_env_mode AS "defaultThreadEnvMode",
favicon_path AS "faviconPath",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -52,6 +52,7 @@ import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
/**
* Migration loader with all migrations defined inline.
@@ -103,6 +104,7 @@ export const migrationEntries = [
[37, "ProjectionTurnsKeysetIndex", Migration0037],
[38, "ProjectionThreadsPinOrderKey", Migration0038],
[39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
[40, "ProjectionProjectFaviconPath", Migration0040],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,28 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("040_ProjectionProjectFaviconPath", (it) => {
it.effect("adds the nullable favicon path to project projections", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 39 });
yield* runMigrations({ toMigrationInclusive: 40 });
const columns = yield* sql<{ readonly name: string; readonly notnull: number }>`
PRAGMA table_info(projection_projects)
`;
const faviconPath = columns.find((column) => column.name === "favicon_path");
assert.equal(faviconPath?.name, "favicon_path");
assert.equal(faviconPath?.notnull, 0);
}),
);
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_projects)
`;
if (!columns.some((column) => column.name === "favicon_path")) {
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN favicon_path TEXT
`;
}
});
@@ -26,6 +26,7 @@ export const ProjectionProject = Schema.Struct({
workspaceRoot: Schema.String,
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultThreadEnvMode: Schema.NullOr(ThreadEnvMode),
faviconPath: Schema.optional(Schema.NullOr(Schema.String)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -77,6 +77,33 @@ it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
}),
);
it.effect("uses a saved project favicon override", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "brand/custom.svg", "<svg>custom</svg>");
yield* writeTextFile(cwd, "favicon.svg", "<svg>automatic</svg>");
const resolved = yield* resolver.resolvePath(cwd, "brand/custom.svg");
expect(resolved).not.toBeNull();
expect(resolved).toContain("brand/custom.svg");
}),
);
it.effect("falls back when a saved override is missing from a checkout", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "favicon.svg", "<svg>automatic</svg>");
const resolved = yield* resolver.resolvePath(cwd, "brand/missing.svg");
expect(resolved).not.toBeNull();
expect(resolved).toContain("favicon.svg");
}),
);
it.effect("falls back to well-known files when the t3.json iconPath does not exist", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
@@ -91,6 +91,7 @@ export class ProjectFaviconResolver extends Context.Service<
*/
readonly resolvePath: (
cwd: string,
faviconPath?: string,
) => Effect.Effect<string | null, ProjectFaviconResolutionError>;
}
>()("t3/project/ProjectFaviconResolver") {}
@@ -168,7 +169,7 @@ export const make = Effect.gen(function* () {
const resolvePath: ProjectFaviconResolver["Service"]["resolvePath"] = Effect.fn(
"ProjectFaviconResolver.resolvePath",
)(function* (cwd) {
)(function* (cwd, faviconPath) {
const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(
Effect.mapError(
(cause) =>
@@ -179,6 +180,15 @@ 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]);
if (existing) {
return existing;
}
}
// 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) {
@@ -245,7 +245,7 @@ export const make = Effect.gen(function* () {
});
return yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind);
return yield* searchIndex.search(normalizedQuery, input.limit, input.kind, input.imageOnly);
}).pipe(
Effect.provide(
workspaceSearchIndexes.get(
@@ -1,4 +1,10 @@
import { FileFinder, type GrepCursor, type GrepOptions, type GrepResult } from "@ff-labs/fff-node";
import {
FileFinder,
type FileItem,
type GrepCursor,
type GrepOptions,
type GrepResult,
} from "@ff-labs/fff-node";
import { afterEach, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
@@ -11,6 +17,54 @@ afterEach(() => {
vi.restoreAllMocks();
});
function fileItem(relativePath: string): FileItem {
return {
relativePath,
fileName: relativePath.slice(relativePath.lastIndexOf("/") + 1),
size: 1,
modified: 0,
accessFrecencyScore: 0,
modificationFrecencyScore: 0,
totalFrecencyScore: 0,
gitStatus: "clean",
};
}
it.effect("filters image searches before applying the result limit", () =>
Effect.scoped(
Effect.gen(function* () {
const items = [
...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)),
fileItem("public/icon.svg"),
];
const fileSearch = vi.fn(() => ({
ok: true as const,
value: {
items,
scores: [],
totalMatched: items.length,
totalFiles: items.length,
},
}));
const finder = {
destroy: vi.fn(),
waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })),
fileSearch,
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project");
const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true);
const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true);
expect(resultWithoutKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
expect(resultWithDirectoryKind.entries).toEqual([{ kind: "file", path: "public/icon.svg" }]);
expect(fileSearch).toHaveBeenCalledTimes(2);
expect(fileSearch).toHaveBeenCalledWith("", { pageSize: 25_002 });
}),
),
);
it.effect("preserves unexpected FileFinder creation failures", () =>
Effect.gen(function* () {
const cause = new Error("native initialization failed");
@@ -23,6 +23,7 @@ import type {
ProjectSearchContentsResult,
ProjectSearchEntriesResult,
} from "@t3tools/contracts";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
@@ -111,6 +112,7 @@ export class WorkspaceSearchIndex extends Context.Service<
query: string,
limit: number,
kind?: ProjectEntryKind,
imageOnly?: boolean,
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;
readonly searchContents: (
input: Omit<ProjectSearchContentsInput, "cwd">,
@@ -157,15 +159,18 @@ function toDirectoryEntry(item: DirItem): ProjectEntry | null {
return normalizedPath ? { path: normalizedPath, kind: "directory" } : null;
}
function mapFileSearchResult(result: SearchResult, limit: number): ProjectSearchEntriesResult {
function mapFileSearchResult(
result: SearchResult,
limit: number,
imageOnly = false,
): ProjectSearchEntriesResult {
const entries = result.items.flatMap((item) => {
const entry = toFileEntry(item);
return entry && (!imageOnly || isWorkspaceImagePreviewPath(entry.path)) ? [entry] : [];
});
return {
entries: result.items
.flatMap((item) => {
const entry = toFileEntry(item);
return entry ? [entry] : [];
})
.slice(0, limit),
truncated: result.totalMatched > limit,
entries: entries.slice(0, limit),
truncated: entries.length > limit || result.totalMatched > result.items.length,
};
}
@@ -445,13 +450,13 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (
const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn(
"WorkspaceSearchIndex.search",
)(function* (query, limit, kind) {
const pageSize = Math.max(1, limit + 1);
if (kind === "file") {
)(function* (query, limit, kind, imageOnly) {
const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1);
if (kind === "file" || imageOnly) {
const result = yield* runSearch(query, pageSize, "fileSearch", () =>
finder.fileSearch(query, { pageSize }),
);
return mapFileSearchResult(result, limit);
return mapFileSearchResult(result, limit, imageOnly);
}
if (kind === "directory") {
const result = yield* runSearch(query, pageSize, "directorySearch", () =>
+25 -1
View File
@@ -1763,9 +1763,33 @@ const makeWsRpcLayer = (
observeRpcEffect(
WS_METHODS.assetsCreateUrl,
Effect.gen(function* () {
if (input.resource._tag !== "workspace-file") {
if (input.resource._tag === "attachment") {
return yield* issueAssetUrl({ resource: input.resource });
}
if (input.resource._tag === "project-favicon") {
const project = yield* projectionSnapshotQuery
.getActiveProjectByWorkspaceRoot(input.resource.cwd)
.pipe(
Effect.mapError(
(cause) =>
new AssetWorkspaceContextResolutionError({
resource: input.resource,
cause,
}),
),
);
if (Option.isNone(project)) {
return yield* new AssetWorkspaceContextNotFoundError({
resource: input.resource,
});
}
return yield* issueAssetUrl({
resource: input.resource,
...(project.value.faviconPath
? { projectFaviconPath: project.value.faviconPath }
: {}),
});
}
const thread = yield* projectionSnapshotQuery
.getThreadShellById(input.resource.threadId)
.pipe(
+8 -2
View File
@@ -12,7 +12,7 @@ export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
export type AssetUrlState =
| { readonly _tag: "Loading" }
| { readonly _tag: "Failure" }
| { readonly _tag: "Success"; readonly url: string };
| { readonly _tag: "Success"; readonly url: string; readonly sourcePath?: string };
export function useAssetUrlState(
environmentId: EnvironmentId,
@@ -32,7 +32,13 @@ export function useAssetUrlState(
return { _tag: "Loading" };
}
const url = resolveAssetUrl(preparedConnection.value.httpBaseUrl, result.value.relativeUrl);
return url === null ? { _tag: "Failure" } : { _tag: "Success", url };
return url === null
? { _tag: "Failure" }
: {
_tag: "Success",
url,
...(result.value.sourcePath !== undefined ? { sourcePath: result.value.sourcePath } : {}),
};
}
export function useAssetUrl(environmentId: EnvironmentId, resource: AssetResource): string | null {
+1
View File
@@ -6048,6 +6048,7 @@ function ChatViewContent(props: ChatViewProps) {
changeRequestState={activeThreadPr?.state ?? null}
activeProjectName={activeProject?.title}
activeProjectCwd={activeProject?.workspaceRoot ?? null}
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
@@ -150,6 +150,7 @@ function projectFavicon(project: Project) {
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
faviconPath={project.faviconPath}
className={ITEM_ICON_CLASS}
/>
);
+5 -1
View File
@@ -2253,7 +2253,11 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}`}
/>
)}
<ProjectFavicon environmentId={project.environmentId} cwd={project.workspaceRoot} />
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
faviconPath={project.faviconPath}
/>
<span className="flex min-w-0 flex-1 items-center gap-2">
<span className="truncate text-sm font-medium text-sidebar-foreground/90">
{project.displayName}
@@ -4,6 +4,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
const testState = vi.hoisted(() => ({
faviconUrl: "https://environment.test/api/assets/token-a/v1-20-favicon.svg",
lastResource: null as unknown,
}));
const hooks = vi.hoisted(() => {
@@ -52,7 +53,10 @@ vi.mock("react", async (importOriginal) => {
vi.mock("react/compiler-runtime", () => ({ c: hooks.useMemoCache }));
vi.mock("../assets/assetUrls", () => ({
useAssetUrl: () => testState.faviconUrl,
useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
testState.lastResource = resource;
return { _tag: "Success", url: testState.faviconUrl };
},
}));
import { ProjectFavicon } from "./ProjectFavicon";
@@ -125,4 +129,18 @@ describe("ProjectFavicon", () => {
expect(afterDisplayedError[0]).not.toBeNull();
expect(afterDisplayedError[1]).toBeNull();
});
it("requests a saved favicon path when one is set", () => {
ProjectFavicon({
environmentId: "environment-test" as EnvironmentId,
cwd: "/workspace-test",
faviconPath: "brand/icon.svg",
});
expect(testState.lastResource).toEqual({
_tag: "project-favicon",
cwd: "/workspace-test",
path: "brand/icon.svg",
});
});
});
+16 -5
View File
@@ -6,7 +6,7 @@ import {
import { FolderIcon } from "lucide-react";
import type { ComponentType } from "react";
import { useState } from "react";
import { useAssetUrl } from "../assets/assetUrls";
import { useAssetUrlState } from "../assets/assetUrls";
import { cn } from "~/lib/utils";
const loadedProjectFaviconSrcs = new Map<string, string>();
@@ -14,13 +14,12 @@ const loadedProjectFaviconSrcs = new Map<string, string>();
export function ProjectFavicon(input: {
environmentId: EnvironmentId;
cwd: string;
faviconPath?: string | null | undefined;
className?: string | undefined;
fallbackIcon?: ComponentType<{ className?: string }>;
}) {
const src = useAssetUrl(input.environmentId, {
_tag: "project-favicon",
cwd: input.cwd,
});
const state = useProjectFaviconAsset(input);
const src = state._tag === "Success" ? state.url : null;
const FallbackIcon = input.fallbackIcon ?? FolderIcon;
if (!src || isProjectFaviconFallbackUrl(src)) {
@@ -40,6 +39,18 @@ export function ProjectFavicon(input: {
);
}
export function useProjectFaviconAsset(input: {
readonly environmentId: EnvironmentId;
readonly cwd: string;
readonly faviconPath?: string | null | undefined;
}) {
return useAssetUrlState(input.environmentId, {
_tag: "project-favicon",
cwd: input.cwd,
...(input.faviconPath ? { path: input.faviconPath } : {}),
});
}
function ProjectFaviconFallback({
className,
icon: Icon,
+34
View File
@@ -236,6 +236,7 @@ function SidebarThreadTooltip({
thread,
projectTitle,
projectCwd,
projectFaviconPath,
environmentLabel,
driverKind,
modelInstanceId,
@@ -247,6 +248,7 @@ function SidebarThreadTooltip({
thread: SidebarThreadSummary;
projectTitle: string | null;
projectCwd: string | null;
projectFaviconPath: string | null;
environmentLabel: string | null;
driverKind: ProviderInstanceEntry["driverKind"] | null;
modelInstanceId: string;
@@ -276,6 +278,7 @@ function SidebarThreadTooltip({
<ProjectFavicon
environmentId={thread.environmentId}
cwd={projectCwd ?? ""}
faviconPath={projectFaviconPath}
className="size-3 shrink-0 stroke-muted-foreground"
/>
<div className="min-w-0 truncate text-foreground/75">{projectTitle}</div>
@@ -423,6 +426,7 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
composer: ComposerThreadDraftState;
projectTitle: string | null;
projectCwd: string | null;
projectFaviconPath: string | null;
isActive: boolean;
onNavigate: (draftId: DraftId) => void;
onDiscard: (draftId: DraftId) => void;
@@ -487,6 +491,7 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
<ProjectFavicon
environmentId={session.environmentId}
cwd={props.projectCwd ?? ""}
faviconPath={props.projectFaviconPath}
className="size-4 shrink-0"
/>
<span className="min-w-0 flex-1 truncate text-xs font-medium text-secondary-label">
@@ -524,6 +529,7 @@ interface SidebarDraftRowData {
const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
projectDisplayNameByKey: ReadonlyMap<string, string>;
projectCwdByKey: ReadonlyMap<string, string>;
projectFaviconPathByKey: ReadonlyMap<string, string | null | undefined>;
scopedProjectKeys: ReadonlySet<string> | null;
routeDraftId: string | null;
onNavigateToDraft: (draftId: DraftId) => void;
@@ -618,6 +624,7 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
composer={composer}
projectTitle={props.projectDisplayNameByKey.get(projectKey) ?? null}
projectCwd={props.projectCwdByKey.get(projectKey) ?? null}
projectFaviconPath={props.projectFaviconPathByKey.get(projectKey) ?? null}
isActive={draftId === props.routeDraftId}
onNavigate={props.onNavigateToDraft}
onDiscard={handleDiscard}
@@ -667,6 +674,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
currentEnvironmentId: string | null;
environmentLabel: string | null;
projectCwd: string | null;
projectFaviconPath: string | null;
projectTitle: string | null;
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
timestampFormat: TimestampFormat;
@@ -857,6 +865,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
thread={thread}
projectTitle={props.projectTitle}
projectCwd={props.projectCwd}
projectFaviconPath={props.projectFaviconPath}
environmentLabel={props.environmentLabel}
driverKind={driverKind}
modelInstanceId={modelInstanceId}
@@ -1122,6 +1131,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
<ProjectFavicon
environmentId={thread.environmentId}
cwd={props.projectCwd ?? ""}
faviconPath={props.projectFaviconPath}
className="size-4"
fallbackIcon={MessageSquareIcon}
/>
@@ -1261,6 +1271,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
<ProjectFavicon
environmentId={thread.environmentId}
cwd={props.projectCwd ?? ""}
faviconPath={props.projectFaviconPath}
className="size-4 shrink-0"
/>
{props.projectTitle ? (
@@ -1454,6 +1465,7 @@ function latestTurnDiff(
const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
thread: SidebarThreadSummary;
projectCwd: string | null;
projectFaviconPath: string | null;
projectTitle: string | null;
environmentLabel: string | null;
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
@@ -1526,6 +1538,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
<ProjectFavicon
environmentId={thread.environmentId}
cwd={props.projectCwd ?? ""}
faviconPath={props.projectFaviconPath}
className="size-4 shrink-0"
fallbackIcon={MessageSquareIcon}
/>
@@ -1538,6 +1551,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
thread={thread}
projectTitle={props.projectTitle}
projectCwd={props.projectCwd}
projectFaviconPath={props.projectFaviconPath}
environmentLabel={props.environmentLabel}
driverKind={driverKind}
modelInstanceId={modelInstanceId}
@@ -1714,6 +1728,13 @@ export default function Sidebar() {
),
[projects],
);
const projectFaviconPathByKey = useMemo(
() =>
new Map(
projects.map((project) => [`${project.environmentId}:${project.id}`, project.faviconPath]),
),
[projects],
);
const projectDisplayNameByKey = useMemo(
() =>
new Map(
@@ -3230,6 +3251,7 @@ export default function Sidebar() {
<ProjectFavicon
environmentId={scopedProjectGroup.environmentId}
cwd={scopedProjectGroup.workspaceRoot}
faviconPath={scopedProjectGroup.faviconPath}
className="size-4 shrink-0"
/>
) : (
@@ -3267,6 +3289,7 @@ export default function Sidebar() {
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
faviconPath={project.faviconPath}
className="size-4 shrink-0"
/>
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
@@ -3339,6 +3362,11 @@ export default function Sidebar() {
projectCwd={
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
}
projectFaviconPath={
projectFaviconPathByKey.get(
`${thread.environmentId}:${thread.projectId}`,
) ?? null
}
projectTitle={
projectDisplayNameByKey.get(
`${thread.environmentId}:${thread.projectId}`,
@@ -3442,6 +3470,11 @@ export default function Sidebar() {
projectCwd={
projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
}
projectFaviconPath={
projectFaviconPathByKey.get(
`${thread.environmentId}:${thread.projectId}`,
) ?? null
}
projectTitle={
projectDisplayNameByKey.get(
`${thread.environmentId}:${thread.projectId}`,
@@ -3480,6 +3513,7 @@ export default function Sidebar() {
key="draft-sessions"
projectDisplayNameByKey={projectDisplayNameByKey}
projectCwdByKey={projectCwdByKey}
projectFaviconPathByKey={projectFaviconPathByKey}
scopedProjectKeys={scopedProjectKeys}
routeDraftId={routeDraftIdForRows}
onNavigateToDraft={navigateToDraft}
@@ -49,6 +49,7 @@ interface ChatHeaderProps {
changeRequestState: ChangeRequestStateLike | null;
activeProjectName: string | undefined;
activeProjectCwd: string | null;
activeProjectFaviconPath: string | null;
openInCwd: string | null;
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
preferredScriptId: string | null;
@@ -101,6 +102,7 @@ export const ChatHeader = memo(function ChatHeader({
changeRequestState,
activeProjectName,
activeProjectCwd,
activeProjectFaviconPath,
openInCwd,
activeProjectScripts,
preferredScriptId,
@@ -229,6 +231,7 @@ export const ChatHeader = memo(function ChatHeader({
<ProjectFavicon
environmentId={activeThreadEnvironmentId}
cwd={activeProjectCwd ?? ""}
faviconPath={activeProjectFaviconPath}
className="size-3.5"
/>
<span className="max-w-40 truncate text-sm font-medium">{activeProjectName}</span>
@@ -150,10 +150,19 @@ export function useProjectFilePickerQuery(
cwd: string,
query: string,
limit: number,
options?: { readonly imageOnly?: boolean },
) {
const search = useProjectPathSearch({ environmentId, cwd, query, kind: "file" }, limit, {
allowEmptyQuery: true,
});
const search = useProjectPathSearch(
{
environmentId,
cwd,
query,
kind: "file",
...(options?.imageOnly ? { imageOnly: true } : {}),
},
limit,
{ allowEmptyQuery: true },
);
return {
entries: search.isPending ? [] : search.entries,
@@ -0,0 +1,104 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { useMemo, useState } from "react";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { useTheme } from "~/hooks/useTheme";
import { CommandPaletteContent } from "../CommandPaletteContent";
import type { CommandPaletteActionItem } from "../CommandPalette.logic";
import { CommandPaletteResults } from "../CommandPaletteResults";
import { PierreEntryIcon } from "../chat/PierreEntryIcon";
import {
getProjectFilePickerMatches,
PROJECT_FILE_PICKER_RESULT_LIMIT,
} from "../files/ProjectFilePicker.logic";
import { useProjectFilePickerQuery } from "../files/projectFilesQueryState";
import { CommandDialog, CommandDialogPopup } from "../ui/command";
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 ProjectFaviconPickerDialog(props: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly onOpenChange: (open: boolean) => void;
readonly onSelect: (path: string) => void;
readonly open: boolean;
readonly projectName: string;
}) {
const [query, setQuery] = useState("");
const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
const result = useProjectFilePickerQuery(
props.environmentId,
props.cwd,
query,
PROJECT_FILE_PICKER_RESULT_LIMIT,
{ imageOnly: true },
);
const { resolvedTheme } = useTheme();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const items = useMemo<CommandPaletteActionItem[]>(
() =>
getProjectFilePickerMatches(result.entries, result.matchedQuery).map((match) => ({
kind: "action",
value: `project-favicon:${match.path}`,
searchTerms: [match.name, match.path],
title: match.name,
description: match.path,
icon: <PierreEntryIcon pathValue={match.path} kind="file" theme={resolvedTheme} />,
run: async () => props.onSelect(match.path),
})),
[props.onSelect, resolvedTheme, result.entries, result.matchedQuery],
);
return (
<CommandDialog open={props.open} onOpenChange={props.onOpenChange}>
{props.open ? (
<CommandDialogPopup
aria-label="Choose project icon"
className="overflow-hidden p-0"
onBackdropPointerDown={() => props.onOpenChange(false)}
>
<CommandPaletteContent
aria-label="Choose project icon"
autoHighlight="always"
escapeLabel="Close"
footerActionLabel="Select icon"
inputProps={{ placeholder: "Search image files…" }}
mode="none"
onItemHighlighted={(value) => {
setHighlightedItemValue(typeof value === "string" ? value : null);
}}
onValueChange={(value) => {
setHighlightedItemValue(null);
setQuery(value);
}}
panelClassName="max-h-[min(34rem,76vh)]"
testId="project-favicon-picker"
value={query}
>
<CommandPaletteResults
groups={
items.length > 0
? [{ value: "project-favicon-files", label: props.projectName, items }]
: []
}
highlightedItemValue={highlightedItemValue}
isActionsOnly={false}
keybindings={keybindings}
onExecuteItem={(item) => {
if (item.kind !== "action") return;
props.onOpenChange(false);
void item.run();
}}
emptyStateMessage={emptyMessage(query, result.error, result.isPending)}
/>
</CommandPaletteContent>
</CommandDialogPopup>
) : null}
</CommandDialog>
);
}
@@ -86,6 +86,7 @@ import {
SettingsRow,
SettingsSection,
} from "./settingsLayout";
import { ProjectFaviconPickerDialog } from "./ProjectFaviconPickerDialog";
export const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = {
repository: "Group by repository",
@@ -221,6 +222,7 @@ export function ProjectSettingsPanel({
<ProjectFavicon
environmentId={group.environmentId}
cwd={group.workspaceRoot}
faviconPath={group.faviconPath}
className="size-4 shrink-0"
/>
<span className="min-w-0 flex-1 truncate">{group.displayName}</span>
@@ -295,6 +297,7 @@ function ProjectDetail({
group.memberProjects.find(
(member) => member.environmentId === group.environmentId && member.id === group.id,
) ?? group.memberProjects[0]!;
const faviconPath = representative.faviconPath ?? null;
const threadCountByMember = useMemo(() => {
const counts = new Map<string, number>();
@@ -328,6 +331,7 @@ function ProjectDetail({
input: Partial<{
defaultModelSelection: ModelSelection | null;
defaultThreadEnvMode: ThreadEnvMode | null;
faviconPath: string | null;
scripts: ReadonlyArray<ReturnType<typeof buildProjectScript>>;
}>,
failureTitle: string,
@@ -391,6 +395,25 @@ function ProjectDetail({
[updateAllMembers],
);
// ----- favicon -----
const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);
const [isSavingFavicon, setIsSavingFavicon] = useState(false);
const savingFaviconRef = useRef(false);
const setFaviconPath = useCallback(
async (faviconPath: string | null) => {
if (savingFaviconRef.current) return;
savingFaviconRef.current = true;
setIsSavingFavicon(true);
try {
await updateAllMembers({ faviconPath }, "Failed to update project icon");
} finally {
savingFaviconRef.current = false;
setIsSavingFavicon(false);
}
},
[updateAllMembers],
);
// ----- scripts -----
const scripts = representative.scripts;
const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
@@ -692,6 +715,7 @@ function ProjectDetail({
<ProjectFavicon
environmentId={group.environmentId}
cwd={group.workspaceRoot}
faviconPath={group.faviconPath}
className="size-8 shrink-0"
/>
<div className="min-w-0 flex-1">
@@ -723,6 +747,43 @@ function ProjectDetail({
</Select>
</div>
<SettingsSection title="Appearance">
<SettingsRow
id="project-favicon"
title="Project icon"
description={faviconPath ?? "Automatic"}
resetAction={
faviconPath !== null ? (
<SettingResetButton
label="project icon"
disabled={isSavingFavicon}
onClick={() => void setFaviconPath(null)}
/>
) : null
}
control={
<div className="flex items-center gap-2">
<ProjectFavicon
environmentId={representative.environmentId}
cwd={representative.workspaceRoot}
faviconPath={faviconPath}
className="size-6"
/>
<Button
size="xs"
variant="outline"
type="button"
aria-label="Choose a project icon file"
disabled={isSavingFavicon}
onClick={() => setFaviconPickerOpen(true)}
>
Choose file
</Button>
</div>
}
/>
</SettingsSection>
<SettingsSection title="Model">
<SettingsRow
id="project-default-model"
@@ -1068,6 +1129,15 @@ function ProjectDetail({
onDelete={deleteScript}
onClose={() => setEditorRequest(null)}
/>
<ProjectFaviconPickerDialog
key={`${representative.environmentId}:${representative.workspaceRoot}:${faviconPickerOpen}`}
cwd={representative.workspaceRoot}
environmentId={representative.environmentId}
onOpenChange={setFaviconPickerOpen}
onSelect={(path) => void setFaviconPath(path)}
open={faviconPickerOpen}
projectName={group.displayName}
/>
</SettingsPageContainer>
);
}
@@ -2258,6 +2258,7 @@ export function ArchivedThreadsPanel() {
environmentId,
name: project.title,
cwd: project.workspaceRoot,
faviconPath: project.faviconPath,
},
] as const,
),
@@ -2379,7 +2380,13 @@ export function ArchivedThreadsPanel() {
key={project.id}
id={index === 0 ? searchableSetting("archive").id : undefined}
title={project.name}
icon={<ProjectFavicon environmentId={project.environmentId} cwd={project.cwd} />}
icon={
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.cwd}
faviconPath={project.faviconPath}
/>
}
>
{projectThreads.map((thread) => (
<SettingsRow
@@ -199,7 +199,15 @@ export function SettingsRow({
);
}
export function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
export function SettingResetButton({
label,
disabled = false,
onClick,
}: {
label: string;
disabled?: boolean;
onClick: () => void;
}) {
return (
<Tooltip>
<TooltipTrigger
@@ -208,6 +216,7 @@ export function SettingResetButton({ label, onClick }: { label: string; onClick:
size="icon-xs"
variant="ghost"
aria-label={`Reset ${label} to default`}
disabled={disabled}
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
onClick={(event) => {
event.stopPropagation();
+2 -1
View File
@@ -10,7 +10,7 @@ describe("areProjectPathSearchTargetsEqual", () => {
query: "index",
};
it("requires the environment, workspace, query, and entry kind to match", () => {
it("requires the environment, workspace, query, entry kind, and image filter to match", () => {
expect(areProjectPathSearchTargetsEqual(target, target)).toBe(true);
expect(
areProjectPathSearchTargetsEqual(target, {
@@ -21,5 +21,6 @@ describe("areProjectPathSearchTargetsEqual", () => {
expect(areProjectPathSearchTargetsEqual(target, { ...target, cwd: "/project-b" })).toBe(false);
expect(areProjectPathSearchTargetsEqual(target, { ...target, query: "readme" })).toBe(false);
expect(areProjectPathSearchTargetsEqual(target, { ...target, kind: "file" })).toBe(false);
expect(areProjectPathSearchTargetsEqual(target, { ...target, imageOnly: true })).toBe(false);
});
});
+6 -2
View File
@@ -236,6 +236,7 @@ export function usePaginatedBranches(target: VcsRefTarget) {
type ProjectPathSearchTarget = ComposerPathSearchTarget & {
readonly kind?: ProjectEntryKind | undefined;
readonly imageOnly?: boolean | undefined;
};
export function areProjectPathSearchTargetsEqual(
@@ -246,7 +247,8 @@ export function areProjectPathSearchTargetsEqual(
left.environmentId === right.environmentId &&
left.cwd === right.cwd &&
left.query === right.query &&
left.kind === right.kind
left.kind === right.kind &&
left.imageOnly === right.imageOnly
);
}
@@ -262,8 +264,9 @@ export function useProjectPathSearch(
cwd: target.cwd,
query: target.query == null ? null : target.query.trim(),
kind: target.kind,
imageOnly: target.imageOnly,
}),
[target.cwd, target.environmentId, target.kind, target.query],
[target.cwd, target.environmentId, target.imageOnly, target.kind, target.query],
);
const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS);
const result = useEnvironmentQuery(
@@ -278,6 +281,7 @@ export function useProjectPathSearch(
query: debouncedTarget.query,
limit,
...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}),
...(debouncedTarget.imageOnly ? { imageOnly: true } : {}),
},
})
: null,
+1
View File
@@ -6,6 +6,7 @@
- [Permission modes](./user/permission-modes.md)
- [Keyboard shortcuts](./user/keybindings.md)
- [Organizing threads](./user/thread-sidebar.md)
- [Customize a project icon](./user/project-settings.md)
- [Remote access](./user/remote-access.md)
- [Keeping app and server in sync](./user/updating.md)
- [Source control integrations](./user/source-control.md)
+16
View File
@@ -0,0 +1,16 @@
# Customize a project icon
T3 Code selects a project icon automatically. It checks `t3.json`, common favicon and app icon
paths, and icon links in project HTML files.
To choose a different icon:
1. Open **Settings** and select **Projects**.
2. Select the project.
3. Under **Appearance**, select **Choose a project file**.
4. Search for an image file and select it.
T3 Code supports SVG, PNG, ICO, JPEG, GIF, AVIF, and WebP files. The selected path applies to
each checkout in the project group and appears on your connected clients.
To use automatic detection again, select **Automatic**.
@@ -72,6 +72,18 @@ describe("createAssetEnvironmentAtoms", () => {
},
}),
).not.toBe(assets.createUrl(originalTarget));
expect(
assets.createUrl({
environmentId,
input: {
resource: {
_tag: "project-favicon",
cwd: "/repo/original",
path: "brand/icon.svg",
},
},
}),
).not.toBe(assets.createUrl(originalTarget));
expect(
assets.createUrl({
environmentId: EnvironmentId.make("environment-2"),
+7
View File
@@ -1,6 +1,7 @@
import * as Schema from "effect/Schema";
import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { ProjectFaviconPath } from "./orchestration.ts";
const ASSET_PATH_MAX_LENGTH = 1024;
@@ -14,6 +15,9 @@ export const AssetResource = Schema.Union([
}),
Schema.TaggedStruct("project-favicon", {
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
// A cache-key hint only. The server reads the authoritative path from the
// project projection before it issues the signed URL.
path: Schema.optional(ProjectFaviconPath),
}),
]);
export type AssetResource = typeof AssetResource.Type;
@@ -26,6 +30,9 @@ export type AssetCreateUrlInput = typeof AssetCreateUrlInput.Type;
export const AssetCreateUrlResult = Schema.Struct({
relativeUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
expiresAt: Schema.Number,
sourcePath: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
),
});
export type AssetCreateUrlResult = typeof AssetCreateUrlResult.Type;
@@ -913,3 +913,25 @@ it.effect("ModelSelection rejects malformed instance ids", () =>
assert.strictEqual(result._tag, "Failure");
}),
);
it.effect("project favicon overrides accept only supported image files", () =>
Effect.gen(function* () {
const valid = yield* decodeOrchestrationCommand({
type: "project.meta.update",
commandId: "cmd-project-favicon",
projectId: "project-1",
faviconPath: "brand/icon.svg",
});
assert.strictEqual(valid.type, "project.meta.update");
const invalid = yield* Effect.exit(
decodeOrchestrationCommand({
type: "project.meta.update",
commandId: "cmd-project-secret",
projectId: "project-1",
faviconPath: ".env",
}),
);
assert.strictEqual(invalid._tag, "Failure");
}),
);
+14
View File
@@ -211,6 +211,12 @@ export const ProjectScript = Schema.Struct({
});
export type ProjectScript = typeof ProjectScript.Type;
export const ProjectFaviconPath = TrimmedNonEmptyString.check(
Schema.isMaxLength(1024),
Schema.isPattern(/\.(?:avif|gif|ico|jpe?g|png|svg|webp)$/i),
);
export type ProjectFaviconPath = typeof ProjectFaviconPath.Type;
export const OrchestrationProject = Schema.Struct({
id: ProjectId,
title: TrimmedNonEmptyString,
@@ -220,6 +226,8 @@ export const OrchestrationProject = Schema.Struct({
// Per-project override for where new threads start. Null/absent means
// "no override": clients fall back to t3.json, then the global setting.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
// Optional on the wire so cached snapshots from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -415,6 +423,8 @@ export const OrchestrationProjectShell = Schema.Struct({
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
// Optional on the wire so cached snapshots from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -629,6 +639,7 @@ const ProjectMetaUpdateCommand = Schema.Struct({
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
// Absent = leave unchanged; null = clear the override.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
});
@@ -1073,6 +1084,8 @@ export const ProjectCreatedPayload = Schema.Struct({
workspaceRoot: TrimmedNonEmptyString,
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
// Optional so persisted events from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -1085,6 +1098,7 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
faviconPath: Schema.optional(Schema.NullOr(ProjectFaviconPath)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
updatedAt: IsoDateTime,
});
+1
View File
@@ -21,6 +21,7 @@ export const ProjectSearchEntriesInput = Schema.Struct({
query: TrimmedString.check(Schema.isMaxLength(256)),
limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)),
kind: Schema.optional(ProjectEntryKind),
imageOnly: Schema.optional(Schema.Boolean),
});
export type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;