Repository navigation
Expand file tree
/
Copy pathclearBrowserCache.ts
More file actions
302 lines (269 loc) · 9.71 KB
/
Copy pathclearBrowserCache.ts
File metadata and controls
302 lines (269 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/**
* mcp/skills/clearBrowserCache.ts — clear_browser_cache skill
*
* Clears cache files for installed browsers (Chrome, Safari, Firefox, Edge).
* Can target a specific browser or all browsers. Use to free disk space or
* resolve browser performance issues.
*
* Platform strategy
* -----------------
* darwin ~/Library/Caches/{Google/Chrome,com.apple.Safari,Firefox,Microsoft Edge}
* win32 %LOCALAPPDATA%\{Google\Chrome,Mozilla\Firefox,Microsoft\Edge}\...\Cache
*
* Smoke test
* npx tsx -r dotenv/config mcp/skills/clearBrowserCache.ts
*/
import * as fsp from "fs/promises";
import * as os from "os";
import * as nodePath from "path";
import { z } from "zod";
// -- Meta ---------------------------------------------------------------------
export const meta = {
name: "clear_browser_cache",
description:
"Clears cache files for installed browsers (Chrome, Safari, Firefox, Edge). " +
"Can target a specific browser or all browsers. " +
"Use to free disk space or resolve browser performance issues.",
riskLevel: "medium",
destructive: false,
requiresConsent: false,
supportsDryRun: true,
affectedScope: ["user"],
auditRequired: true,
tccCategories: ["FullDiskAccess"],
footprint: {
kind: "sweep",
// Subtrees of the dirs clear_app_cache excludes (Google/com.apple.Safari/
// Firefox/Microsoft Edge on darwin; Google/Mozilla/Microsoft on win32), so
// the app-cache↔browser-cache overlap is excused by those excludes.
darwin: { roots: [
"~/Library/Caches/Google/Chrome",
"~/Library/Caches/com.apple.Safari",
"~/Library/Caches/Firefox",
"~/Library/Caches/Microsoft Edge",
] },
win32: { roots: [
"%LOCALAPPDATA%/Google/Chrome/User Data/Default/Cache",
"%LOCALAPPDATA%/Mozilla/Firefox/Profiles",
"%LOCALAPPDATA%/Microsoft/Edge/User Data/Default/Cache",
] },
},
outputKeys: ["platform","dryRun","browsers","totalSizeMb","freedMb","error"],
schema: {
browser: z
.enum(["chrome", "safari", "firefox", "edge", "all"])
.nullable().optional()
.describe("Target browser. Default: all"),
dryRun: z
.boolean()
.nullable().optional()
.describe("If true, report sizes without deleting. Default: true"),
},
} as const;
// -- Types --------------------------------------------------------------------
interface BrowserCacheResult {
name: string;
cachePath: string;
sizeMb: number;
cleared: boolean;
/**
* Set when the clear operation reported success but post-clear size
* confirms the data is still there — typically a TCC denial on a
* protected cache directory. Includes actionable remediation text.
*/
error?: string;
}
// -- Helpers ------------------------------------------------------------------
async function getDirSizeMb(dirPath: string): Promise<number> {
try {
const entries = await fsp.readdir(dirPath, { recursive: true, withFileTypes: true });
let totalBytes = 0;
await Promise.allSettled(
entries
.filter((e) => !e.isDirectory())
.map(async (e) => {
try {
const parentPath = (e as unknown as { parentPath?: string; path?: string }).parentPath
?? (e as unknown as { path?: string }).path
?? dirPath;
const fullPath = nodePath.join(parentPath, e.name);
const stat = await fsp.stat(fullPath);
totalBytes += stat.size;
} catch {
// skip
}
}),
);
// SI/decimal MB to match _shared/formatBytes.ts + Finder.
return Math.round((totalBytes / 1_000_000) * 100) / 100;
} catch {
return 0;
}
}
function isSafePath(target: string, allowedRoot: string): boolean {
const rel = nodePath.relative(allowedRoot, target);
return !rel.startsWith("..") && !nodePath.isAbsolute(rel);
}
async function processCachePath(
name: string,
cachePath: string,
dryRun: boolean,
safeRoot: string,
): Promise<BrowserCacheResult> {
// Check if path exists
try {
await fsp.access(cachePath);
} catch {
return { name, cachePath, sizeMb: 0, cleared: false };
}
const sizeMb = await getDirSizeMb(cachePath);
if (dryRun || !isSafePath(cachePath, safeRoot)) {
return { name, cachePath, sizeMb, cleared: false };
}
try {
const entries = await fsp.readdir(cachePath);
await Promise.allSettled(
entries.map((entry) =>
fsp.rm(nodePath.join(cachePath, entry), { recursive: true, force: true }),
),
);
// ── Silent-failure detection ──────────────────────────────────────────────
// The rm loop reports success (Promise.allSettled never throws), but
// individual removes may have been denied silently. Re-measure after
// the clear: if size barely changed, the cache wasn't actually cleared
// — almost always a TCC denial on a protected browser cache directory.
const sizeAfterMb = await getDirSizeMb(cachePath);
if (sizeMb > 0 && sizeAfterMb >= sizeMb * 0.9) {
return {
name, cachePath, sizeMb,
cleared: false,
error:
`Could not clear ${name} cache (${sizeMb} MB still present after ` +
`the operation). Full Disk Access is required to remove protected ` +
`browser cache files. Open System Settings → Privacy & Security → ` +
`Full Disk Access, enable AI Support Agent, then quit and relaunch.`,
};
}
return { name, cachePath, sizeMb, cleared: true };
} catch (err) {
const code = (err as { code?: string }).code;
if (code === "EPERM" || code === "EACCES") {
return {
name, cachePath, sizeMb,
cleared: false,
error:
`Could not clear ${name} cache — macOS denied access. ` +
`Open System Settings → Privacy & Security → Full Disk Access, ` +
`enable AI Support Agent, then quit and relaunch.`,
};
}
return { name, cachePath, sizeMb, cleared: false };
}
}
// -- darwin implementation ----------------------------------------------------
async function clearBrowserCacheDarwin(
browser: string,
dryRun: boolean,
): Promise<BrowserCacheResult[]> {
const home = os.homedir();
const cacheRoot = nodePath.join(home, "Library", "Caches");
const browserDefs: { key: string; name: string; path: string }[] = [
{
key: "chrome",
name: "Chrome",
path: nodePath.join(cacheRoot, "Google", "Chrome"),
},
{
key: "safari",
name: "Safari",
path: nodePath.join(cacheRoot, "com.apple.Safari"),
},
{
key: "firefox",
name: "Firefox",
path: nodePath.join(cacheRoot, "Firefox"),
},
{
key: "edge",
name: "Edge",
path: nodePath.join(cacheRoot, "Microsoft Edge"),
},
];
const targets = browser === "all"
? browserDefs
: browserDefs.filter((b) => b.key === browser);
return Promise.all(
targets.map((b) => processCachePath(b.name, b.path, dryRun, cacheRoot)),
);
}
// -- win32 implementation -----------------------------------------------------
async function clearBrowserCacheWin32(
browser: string,
dryRun: boolean,
): Promise<BrowserCacheResult[]> {
const localAppData = process.env["LOCALAPPDATA"]
?? nodePath.join(os.homedir(), "AppData", "Local");
const browserDefs: { key: string; name: string; path: string }[] = [
{
key: "chrome",
name: "Chrome",
path: nodePath.join(localAppData, "Google", "Chrome", "User Data", "Default", "Cache"),
},
{
key: "firefox",
name: "Firefox",
path: nodePath.join(localAppData, "Mozilla", "Firefox", "Profiles"),
},
{
key: "edge",
name: "Edge",
path: nodePath.join(localAppData, "Microsoft", "Edge", "User Data", "Default", "Cache"),
},
// Safari is not available on Windows
];
const targets = browser === "all" || browser === "safari"
? browserDefs.filter((b) => browser === "all" || b.key === browser)
: browserDefs.filter((b) => b.key === browser);
if (browser === "safari") {
return [{ name: "Safari", cachePath: "N/A", sizeMb: 0, cleared: false }];
}
return Promise.all(
targets.map((b) => processCachePath(b.name, b.path, dryRun, localAppData)),
);
}
// -- Exported run function ----------------------------------------------------
export async function run({
browser = "all",
dryRun = true,
}: {
browser?: "chrome" | "safari" | "firefox" | "edge" | "all";
dryRun?: boolean;
} = {}) {
const platform = os.platform();
const browsers = platform === "win32"
? await clearBrowserCacheWin32(browser, dryRun)
: await clearBrowserCacheDarwin(browser, dryRun);
const totalSizeMb = Math.round(browsers.reduce((s, b) => s + b.sizeMb, 0) * 100) / 100;
const freedMb = Math.round(
browsers.filter((b) => b.cleared).reduce((s, b) => s + b.sizeMb, 0) * 100,
) / 100;
// Aggregate any per-browser TCC / silent-failure errors into a top-level
// error string so the soft-error pipeline (execution.ts → log.warn,
// summarizer → result bubble) surfaces them. Without this, only the
// per-browser entries carry the message and the user-facing summary
// typically loses the detail.
const failedBrowsers = browsers.filter((b) => b.error);
const error = failedBrowsers.length > 0
? failedBrowsers.map((b) => b.error).join(" ")
: undefined;
return {
platform, dryRun, browsers, totalSizeMb, freedMb,
...(error ? { error } : {}),
};
}
// -- CLI smoke test -----------------------------------------------------------
if (false) {
run({})
.then(r => console.log(JSON.stringify(r, null, 2)))
.catch((err: Error) => { console.error(err.message); process.exit(1); });
}