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