Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import type { ToolActivityNativeAppReference } from "@t3tools/contracts";
3import * as Cache from "effect/Cache";
4import * as Cause from "effect/Cause";
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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
17import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
18
19import * as ServerConfig from "../config.ts";
20
21const ICON_SIZE = 64;
22const COMMAND_TIMEOUT = "5 seconds";
23const RESOLUTION_CACHE_TTL = Duration.hours(1);
24const RESOLUTION_CACHE_MAX_ENTRIES = 256;
25
26/** Resolves and caches macOS application icons without exposing host paths to clients. */
27export class NativeAppIconResolver extends Context.Service<
28 NativeAppIconResolver,
29 {
30 /** Returns a cached PNG path for the application, or `null` when no icon is available. */
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.map(Option.some),
47 Effect.catchTags({
48 PlatformError: (error) =>
49 error.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : 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 cacheKey = NodeCrypto.createHash("sha256")
179 .update(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`)
180 .digest("hex");
181 const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
182 const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
183 if (yield* existingFile(cachePath)) return cachePath;
184
185 yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
186 const temporaryPath = path.join(
187 cacheDirectory,
188 `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID()}.png`,
189 );
190 yield* commandOutput("/usr/bin/sips", [
191 "-z",
192 String(ICON_SIZE),
193 String(ICON_SIZE),
194 "-s",
195 "format",
196 "png",
197 sourceIconPath,
198 "--out",
199 temporaryPath,
200 ]).pipe(
201 Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)),
202 Effect.ensuring(
203 fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })),
204 ),
205 );
206 return yield* existingFile(cachePath);
207});
208
209/** @public Service construction is part of the canonical Effect module API. */
210export const make = Effect.gen(function* () {
211 const fileSystem = yield* FileSystem.FileSystem;
212 const hostPlatform = yield* HostProcessPlatform;
213 const resolutionSemaphore = yield* Semaphore.make(2);
214 const resolutionCache: Cache.Cache<
215 string,
216 string | null,
217 PlatformError.PlatformError | Cause.TimeoutError
218 > = yield* Cache.makeWith(
219 (key: string) =>
220 resolutionSemaphore.withPermits(1)(resolveNativeAppIconUncached(appFromCacheKey(key))),
221 {
222 capacity: RESOLUTION_CACHE_MAX_ENTRIES,
223 timeToLive: Exit.match({
224 onSuccess: () => RESOLUTION_CACHE_TTL,
225 onFailure: () => Duration.zero,
226 }),
227 },
228 );
229
230 const cachedFileExists = (filePath: string) =>
231 fileSystem.stat(filePath).pipe(
232 Effect.map((info) => info.type === "File"),
233 Effect.catchTags({
234 PlatformError: (error) =>
235 error.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(error),
236 }),
237 );
238
239 const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
240 app: ToolActivityNativeAppReference,
241 ) {
242 if (
243 hostPlatform !== "darwin" ||
244 (app._tag === "display-name" && containsControlCharacter(app.displayName))
245 ) {
246 return null;
247 }
248
249 const key = appCacheKey(app);
250 const cached = yield* Cache.get(resolutionCache, key);
251 if (cached === null) return null;
252 if (yield* cachedFileExists(cached)) return cached;
253
254 yield* Cache.invalidate(resolutionCache, key);
255 return yield* Cache.get(resolutionCache, key);
256 });
257
258 const resolve: NativeAppIconResolver["Service"]["resolve"] = (app) =>
259 resolveAttempt(app).pipe(
260 Effect.tapError((cause) =>
261 Effect.logDebug("Failed to resolve native application icon.", { app, cause }),
262 ),
263 Effect.orElseSucceed(() => null),
264 );
265
266 return NativeAppIconResolver.of({ resolve });
267});
268
269export const layer = Layer.effect(NativeAppIconResolver, make);