diff --git a/packages/core/src/project.ts b/packages/core/src/project.ts index 2fe4d6d9941..19de343a69d 100644 --- a/packages/core/src/project.ts +++ b/packages/core/src/project.ts @@ -1,6 +1,6 @@ export * as Project from "./project.js" -import { Context, Duration, Effect, Layer, Schedule, Schema } from "effect" +import { Context, Duration, Effect, Layer, Schedule, Schema, Scope } from "effect" import { ChildProcess } from "effect/process" import { and, asc, desc, eq, gte, isNotNull, isNull, lt, lte, ne, sql } from "drizzle-orm" import path from "path" @@ -15,6 +15,7 @@ import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Hash } from "@opencode/util/hash" import { ProjectSchema } from "./project/schema.js" import { ProjectTable, upsertProject } from "./project/sql.js" +import { ProjectIcon } from "./project/icon.js" import { WorktreeTable } from "./worktree/sql.js" export const ID = ProjectSchema.ID @@ -112,6 +113,7 @@ const layer = Layer.effect( const proc = yield* AppProcess.Service const bus = yield* Bus.Service const db = (yield* Database.Service).db + const scope = yield* Scope.Scope const announcing = new Set() const persist = Effect.fnUntraced(function* (project: Resolved) { @@ -144,6 +146,11 @@ const layer = Layer.effect( : undefined const changed = replaced ?? unarchived if (changed) yield* bus.publish(ProjectSchema.Event.Updated, fromRow(changed)) + yield* ProjectIcon.refresh(fs, db, project.id).pipe( + Effect.flatMap((row) => (row ? bus.publish(ProjectSchema.Event.Updated, fromRow(row)) : Effect.void)), + Effect.ignoreCause, + Effect.forkIn(scope), + ) if (!project.vcs) return project const directories: Array<{ projectID: ID; directory: AbsolutePath; strategy?: string }> = [ { projectID: project.id, directory: project.canonical }, diff --git a/packages/core/src/project/icon.ts b/packages/core/src/project/icon.ts new file mode 100644 index 00000000000..36d73fcde33 --- /dev/null +++ b/packages/core/src/project/icon.ts @@ -0,0 +1,66 @@ +export * as ProjectIcon from "./icon.js" + +import path from "path" +import { Effect } from "effect" +import { eq } from "drizzle-orm" +import { FSUtil } from "@opencode/util/fs-util" +import { Hash } from "@opencode/util/hash" +import type { EffectDrizzleSqlite } from "../database/drizzle.js" +import { ProjectTable } from "./sql.js" +import type { ProjectSchema } from "./schema.js" + +const IMAGES = new Set([".svg", ".png", ".ico", ".jpg", ".jpeg", ".webp"]) +const CANDIDATES = [ + "Assets.xcassets/AppIcon.appiconset", + "ios/App/Assets.xcassets/AppIcon.appiconset", + ...[ + "assets/app-icon", + "build/icon", + "src-tauri/icons/icon", + "resources/icon", + "icons/icon", + "extension/icons/icon", + ].flatMap((b) => [`${b}.svg`, `${b}.png`]), + ...["favicon.svg", "icon.svg", "favicon.png", "apple-touch-icon.png", "icon.png", "favicon.ico"].flatMap((f) => + ["public/", "app/", "src/app/", "site/public/", ""].map((d) => `${d}${f}`), + ), + ...["assets/icon", "assets/logo", "public/logo", "logo"].flatMap((b) => [`${b}.svg`, `${b}.png`]), +] + +export const refresh = Effect.fn("ProjectIcon.refresh")(function* ( + fs: FSUtil.Interface, + db: EffectDrizzleSqlite.EffectSQLiteDatabase, + id: ProjectSchema.ID, +) { + const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get() + if (!project || id === "global") return + const root = yield* fs.realPath(project.worktree) + for (const name of CANDIDATES) { + const candidate = yield* fs.realPath(path.join(root, name)).pipe(Effect.orElseSucceed(() => undefined)) + if (!candidate || candidate === root || !FSUtil.contains(root, candidate)) continue + const entries = name.endsWith(".appiconset") + ? yield* fs.readDirectoryEntries(candidate).pipe(Effect.orElseSucceed(() => [])) + : undefined + const files = entries + ?.flatMap((e) => (e.type === "file" && IMAGES.has(path.extname(e.name).toLowerCase()) ? [e.name] : [])) + .toSorted() + const picked = files ? (files.find((n) => /128|256/.test(n)) ?? files[0]) : undefined + const file = entries + ? picked + ? yield* fs.realPath(path.join(candidate, picked)).pipe(Effect.orElseSucceed(() => undefined)) + : undefined + : candidate + if (!file || file === root || !FSUtil.contains(root, file) || !IMAGES.has(path.extname(file).toLowerCase())) + continue + const info = yield* fs.stat(file).pipe(Effect.orElseSucceed(() => undefined)) + if (!info || info.type !== "File" || !Number(info.size) || Number(info.size) > 64 * 1024) continue + const bytes = yield* fs.readFile(file).pipe(Effect.orElseSucceed(() => undefined)) + if (!bytes?.byteLength || bytes.byteLength > 64 * 1024) continue + const mime = path.extname(file).toLowerCase() === ".ico" ? "image/x-icon" : FSUtil.mimeType(file) + const url = `data:${mime};base64,${Buffer.from(bytes).toString("base64")}` + if (url.length > 64 * 1024) continue + // The stored data URL is the content fingerprint; no separate hash column or cache is needed. + if (project.icon_url && Hash.fast(project.icon_url) === Hash.fast(url)) return + return yield* db.update(ProjectTable).set({ icon_url: url }).where(eq(ProjectTable.id, id)).returning().get() + } +}) diff --git a/packages/core/test/project-icon.test.ts b/packages/core/test/project-icon.test.ts new file mode 100644 index 00000000000..3671f60b28f --- /dev/null +++ b/packages/core/test/project-icon.test.ts @@ -0,0 +1,80 @@ +import { expect } from "bun:test" +import path from "path" +import fs from "fs/promises" +import { Effect, Fiber, Stream } from "effect" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Project } from "@opencode/core/project" +import { ProjectIcon } from "@opencode/core/project/icon" +import { ProjectSchema } from "@opencode/core/project/schema" +import { ProjectTable } from "@opencode/core/project/sql" +import { Database } from "@opencode/core/database/database" +import { Bus } from "@opencode/core/bus" +import { AbsolutePath } from "@opencode/core/schema" +import { FSUtil } from "@opencode/util/fs-util" +import { tmpdirScoped } from "./fixture/tmpdir" +import { testEffect } from "./lib/effect" + +const it = testEffect(AppNodeBuilder.build(LayerNode.group([Project.node, Database.node, Bus.node, FSUtil.node]))) +const svg = '' +const url = `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}` + +for (const kind of ["ranked appiconset", "escaping symlink", "oversized file"] as const) { + it.live(`discovers the expected icon with a ${kind}`, () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const root = path.join(tmp.path, "project") + const filesystem = yield* FSUtil.Service + const db = (yield* Database.Service).db + const id = Project.ID.make("icons") + yield* Effect.promise(() => Bun.write(path.join(root, "public/favicon.svg"), svg)) + if (kind === "ranked appiconset") { + yield* Effect.promise(() => Bun.write(path.join(root, "Assets.xcassets/AppIcon.appiconset/000.png"), "other")) + yield* Effect.promise(() => + Bun.write(path.join(root, "Assets.xcassets/AppIcon.appiconset/icon256.svg"), svg + " "), + ) + } + if (kind === "escaping symlink") { + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "outside.svg"), "outside")) + yield* Effect.promise(() => fs.mkdir(path.join(root, "assets"))) + yield* Effect.promise(() => + fs.symlink(path.join(tmp.path, "outside.svg"), path.join(root, "assets/app-icon.svg")), + ) + } + if (kind === "oversized file") + yield* Effect.promise(() => Bun.write(path.join(root, "assets/app-icon.svg"), "x".repeat(64 * 1024 + 1))) + yield* db + .insert(ProjectTable) + .values({ id, worktree: AbsolutePath.make(root), sandboxes: [] }) + .run() + const row = yield* ProjectIcon.refresh(filesystem, db, id) + expect(row?.icon_url).toBe( + kind === "ranked appiconset" ? `data:image/svg+xml;base64,${Buffer.from(svg + " ").toString("base64")}` : url, + ) + }), + ) +} + +it.live("resolves in the background, preserves overrides, and only writes changed content", () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const project = yield* Project.Service + const bus = yield* Bus.Service + const filesystem = yield* FSUtil.Service + const db = (yield* Database.Service).db + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "favicon.svg"), svg)) + const updated = yield* bus + .subscribe(ProjectSchema.Event.Updated) + .pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped({ startImmediately: true })) + const resolved = yield* project.resolve(AbsolutePath.make(tmp.path)) + expect((yield* Fiber.join(updated))[0]?.data.icon?.url).toBe(url) + yield* project.update({ projectID: resolved.id, icon: { override: "my-icon", color: "blue" } }) + const before = (yield* project.list())[0] + expect(yield* ProjectIcon.refresh(filesystem, db, resolved.id)).toBeUndefined() + expect((yield* project.list())[0]).toEqual(before) + yield* Effect.promise(() => Bun.write(path.join(tmp.path, "favicon.svg"), svg + " ")) + const changed = yield* ProjectIcon.refresh(filesystem, db, resolved.id) + expect(changed?.icon_url).not.toBe(url) + expect(changed).toMatchObject({ icon_url_override: "my-icon", icon_color: "blue" }) + }), +)