Open History to see the last commit
1import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
2import * as Cache from "effect/Cache";
3import * as Cause from "effect/Cause";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Clock from "effect/Clock";
7import * as Context from "effect/Context";
8import * as Duration from "effect/Duration";
9import * as Exit from "effect/Exit";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as PlatformError from "effect/PlatformError";
15import * as Semaphore from "effect/Semaphore";
16import * as Hex from "effect/encoding/Hex";
17import { ChildProcess, ChildProcessSpawner } from "effect/process";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19
20import * as ServerConfig from "../config.ts";
21
22const ICON_SIZE = 64;
23const COMMAND_TIMEOUT = "5 seconds";
24const RESOLUTION_CACHE_TTL = Duration.hours(1);
25const RESOLUTION_CACHE_MAX_ENTRIES = 256;
26
27export class NativeAppIconResolver extends Context.Service<
28 NativeAppIconResolver,
29 {
30 readonly resolve: (app: ToolActivityNativeAppReference) => Effect.Effect<string | null>;
31 }
32>()("t3/assets/NativeAppIconResolver") {}
33
34function appCacheKey(app: ToolActivityNativeAppReference): string {
35 return JSON.stringify(app);
36}
37
38function appFromCacheKey(key: string): ToolActivityNativeAppReference {
39 return JSON.parse(key) as ToolActivityNativeAppReference;
40}
41
42const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
43 const fileSystem = yield* FileSystem.FileSystem;
44 const info = yield* fileSystem.stat(filePath).pipe(
45 Effect.asSome,
46 Effect.catchTags({
47 PlatformError: (error) =>
48 error.reason._tag === "NotFound" ? Effect.succeedNone : Effect.fail(error),
49 }),
50 );
51 return Option.isSome(info) && info.value.type === "File" ? filePath : null;
52});
53
54const commandOutput = Effect.fn("NativeAppIconResolver.commandOutput")(function* (
55 command: string,
56 args: ReadonlyArray<string>,
57) {
58 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
59 return yield* spawner
60 .string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }))
61 .pipe(Effect.timeout(COMMAND_TIMEOUT));
62});
63
64const plistValue = Effect.fn("NativeAppIconResolver.plistValue")(function* (
65 infoPlistPath: string,
66 key: string,
67) {
68 return yield* commandOutput("/usr/bin/plutil", [
69 "-extract",
70 key,
71 "raw",
72 "-o",
73 "-",
74 infoPlistPath,
75 ]).pipe(
76 Effect.map((value) => value.trim()),
77 Effect.orElseSucceed(() => ""),
78 );
79});
80
81function escapeSpotlightString(value: string): string {
82 return value.replace(/([\\'*?])/gu, "\\$1");
83}
84
85function containsControlCharacter(value: string): boolean {
86 return [...value].some((character) => {
87 const codePoint = character.codePointAt(0) ?? 0;
88 return codePoint <= 31 || codePoint === 127;
89 });
90}
91
92const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
93 app: ToolActivityNativeAppReference,
94) {
95 const path = yield* Path.Path;
96 const query =
97 app._tag === "app-id"
98 ? `kMDItemCFBundleIdentifier == '${app.appId}'`
99 : `kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '${escapeSpotlightString(app.displayName)}'`;
100 const spotlightOutput = yield* commandOutput("/usr/bin/mdfind", [query]);
101 const candidates = spotlightOutput
102 .split(/\r?\n/u)
103 .map((value) => value.trim())
104 .filter((value) => value.endsWith(".app"));
105 const matchingCandidates =
106 app._tag === "app-id"
107 ? candidates
108 : candidates.filter(
109 (value) =>
110 path.basename(value, ".app").toLocaleLowerCase() ===
111 app.displayName.toLocaleLowerCase(),
112 );
113 const rankedCandidates = matchingCandidates.length > 0 ? matchingCandidates : candidates;
114 let mostRecentlyUsed: { readonly path: string; readonly lastUsed: string } | null = null;
115 for (const candidate of rankedCandidates) {
116 const lastUsed = yield* commandOutput("/usr/bin/mdls", [
117 "-raw",
118 "-name",
119 "kMDItemLastUsedDate",
120 candidate,
121 ]).pipe(
122 Effect.map((value) => value.trim()),
123 Effect.orElseSucceed(() => ""),
124 );
125 if (!mostRecentlyUsed || lastUsed > mostRecentlyUsed.lastUsed) {
126 mostRecentlyUsed = { path: candidate, lastUsed };
127 }
128 }
129 return mostRecentlyUsed?.path ?? null;
130});
131
132const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
133 app: ToolActivityNativeAppReference,
134) {
135 const fileSystem = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const config = yield* ServerConfig.ServerConfig;
138 const appPath = yield* resolveApplicationPath(app);
139 if (!appPath) return null;
140
141 const canonicalAppPath = yield* fileSystem.realPath(appPath);
142 const infoPlistPath = path.join(canonicalAppPath, "Contents", "Info.plist");
143 const resourcesDirectory = path.join(canonicalAppPath, "Contents", "Resources");
144 const iconName =
145 (yield* plistValue(infoPlistPath, "CFBundleIconFile")) ||
146 (yield* plistValue(infoPlistPath, "CFBundleIconName"));
147 if (iconName && path.basename(iconName) !== iconName) return null;
148 const iconFileName = iconName ? (path.extname(iconName) ? iconName : `${iconName}.icns`) : null;
149 const resourceEntries = yield* fileSystem
150 .readDirectory(resourcesDirectory)
151 .pipe(Effect.orElseSucceed(() => []));
152 const sourceIconCandidate =
153 (iconFileName ? yield* existingFile(path.join(resourcesDirectory, iconFileName)) : null) ??
154 (yield* existingFile(path.join(resourcesDirectory, "AppIcon.icns"))) ??
155 (resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))
156 ? yield* existingFile(
157 path.join(
158 resourcesDirectory,
159 resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))!,
160 ),
161 )
162 : null);
163 if (!sourceIconCandidate) return null;
164 const sourceIconPath = yield* fileSystem.realPath(sourceIconCandidate);
165 const relativeSource = path.relative(resourcesDirectory, sourceIconPath);
166 if (
167 relativeSource === ".." ||
168 relativeSource.startsWith(`..${path.sep}`) ||
169 path.isAbsolute(relativeSource)
170 ) {
171 return null;
172 }
173
174 const appVersion =
175 (yield* plistValue(infoPlistPath, "CFBundleVersion")) ||
176 (yield* plistValue(infoPlistPath, "CFBundleShortVersionString"));
177 const crypto = yield* Crypto.Crypto;
178 const cacheKey = yield* crypto
179 .digest(
180 "SHA-256",
181 new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`),
182 )
183 .pipe(Effect.map(Hex.encode), Effect.orDie);
184 const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
185 const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
186 if (yield* existingFile(cachePath)) return cachePath;
187
188 yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
189 const temporaryPath = path.join(
190 cacheDirectory,
191 `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* crypto.randomUUIDv4().pipe(Effect.orDie)}.png`,
192 );
193 yield* commandOutput("/usr/bin/sips", [
194 "-z",
195 String(ICON_SIZE),
196 String(ICON_SIZE),
197 "-s",
198 "format",
199 "png",
200 sourceIconPath,
201 "--out",
202 temporaryPath,
203 ]).pipe(
204 Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)),
205 Effect.ensuring(
206 fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })),
207 ),
208 );
209 return yield* existingFile(cachePath);
210});
211
212/** @public Service construction is part of the canonical Effect module API. */
213export const make = Effect.gen(function* () {
214 const fileSystem = yield* FileSystem.FileSystem;
215 const hostPlatform = yield* HostProcess.Platform;
216 const resolutionSemaphore = yield* Semaphore.make(2);
217 const resolutionCache: Cache.Cache<
218 string,
219 string | null,
220 PlatformError.PlatformError | Cause.TimeoutError
221 > = yield* Cache.makeWith(
222 (key: string) =>
223 resolutionSemaphore.withPermits(1)(resolveNativeAppIconUncached(appFromCacheKey(key))),
224 {
225 capacity: RESOLUTION_CACHE_MAX_ENTRIES,
226 timeToLive: Exit.match({
227 onSuccess: () => RESOLUTION_CACHE_TTL,
228 onFailure: () => Duration.zero,
229 }),
230 },
231 );
232
233 const cachedFileExists = (filePath: string) =>
234 fileSystem.stat(filePath).pipe(
235 Effect.map((info) => info.type === "File"),
236 Effect.catchTags({
237 PlatformError: (error) =>
238 error.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(error),
239 }),
240 );
241
242 const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
243 app: ToolActivityNativeAppReference,
244 ) {
245 if (
246 hostPlatform !== "darwin" ||
247 (app._tag === "display-name" && containsControlCharacter(app.displayName))
248 ) {
249 return null;
250 }
251
252 const key = appCacheKey(app);
253 const cached = yield* Cache.get(resolutionCache, key);
254 if (cached === null) return null;
255 if (yield* cachedFileExists(cached)) return cached;
256
257 yield* Cache.invalidate(resolutionCache, key);
258 return yield* Cache.get(resolutionCache, key);
259 });
260
261 const resolve: NativeAppIconResolver["Service"]["resolve"] = (app) =>
262 resolveAttempt(app).pipe(
263 Effect.tapError((cause) =>
264 Effect.logDebug("Failed to resolve native application icon.", { app, cause }),
265 ),
266 Effect.orElseSucceed(() => null),
267 );
268
269 return NativeAppIconResolver.of({ resolve });
270});
271
272export const layer = Layer.effect(NativeAppIconResolver, make);