Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

Merge pull request #3726 from horizon554/codex/ios-simulator-delete-device

GaoWei Liu2a039176935c
diff --cc apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 8dfad77e02,07e726d9d4..6c7ff3bd6c
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@@ -130,309 -118,9 +131,311 @@@ const DEFAULT_DEVICE_LIVENESS_INTERVAL_
const MAX_WDA_VIEWER_FRAMES_PER_SECOND = 20;
const MAX_NATIVE_H264_VIEWER_FRAMES_PER_SECOND = 60;
const MAX_INSTANCES_PER_SESSION = 4;
+const MAX_ARTIFACTS_PER_INSTANCE = 4;
+const IOS_SIMULATOR_BUILD_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+const IOS_SIMULATOR_BUILD_CACHE_LAST_USED_FILE = '.cindy-last-used';
+const IOS_SIMULATOR_BUILD_CACHE_PRUNE_CONCURRENCY = 4;
+const UUID_V4_PATTERN_SOURCE =
+ '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
+const MANAGED_BUILD_CACHE_KEY_PATTERN = /^[0-9a-f]{20}$/i;
+const MANAGED_BUILD_CACHE_TRASH_PATTERN = new RegExp(
+ `^\\.trash-[0-9a-f]{20}-${UUID_V4_PATTERN_SOURCE}$`,
+ 'i',
+);
+const MANAGED_ARTIFACT_COPY_PATTERN = new RegExp(`^${UUID_V4_PATTERN_SOURCE}\\.app$`, 'i');
+const ARTIFACT_COPY_TRASH_PREFIX = '.trash-artifact-';
+const MANAGED_ARTIFACT_COPY_TRASH_PATTERN = new RegExp(
+ `^\\.trash-artifact-${UUID_V4_PATTERN_SOURCE}\\.app-${UUID_V4_PATTERN_SOURCE}$`,
+ 'i',
+);
+
+/**
+ * Record the last time this cache key was admitted or finished a build.
+ * Xcode writes DerivedData/SPM descendants and does not refresh the cache-key
+ * directory mtime, so opportunistic 7-day reclaim must not use that mtime.
+ */
+export async function touchIOSSimulatorBuildCacheLastUsed(
+ cacheDir: string,
+ now: () => number = Date.now,
+): Promise<void> {
+ await mkdir(cacheDir, { recursive: true });
+ await writeFile(
+ path.join(cacheDir, IOS_SIMULATOR_BUILD_CACHE_LAST_USED_FILE),
+ `${now()}\n`,
+ 'utf8',
+ );
+}
+
+function isPathInside(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return (
+ relative === '' ||
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+ );
+}
+
+/**
+ * An immutable app copy must not retain a symlink into mutable DerivedData,
+ * the worktree, or any other external location. Validate links without
+ * traversing them: real directories are walked once, while each link's final
+ * target must resolve inside the copied `.app` tree. Dangling links fail too.
+ */
+async function assertIOSSimulatorArtifactSymlinksContained(appPath: string): Promise<void> {
+ let root: string;
+ try {
+ root = await realpath(appPath);
+ } catch {
+ throw new IOSSimulatorInstanceError(
+ 'APP_ARTIFACT_INVALID',
+ 'The immutable app artifact could not be inspected.',
+ );
+ }
+ const pending = [root];
+ while (pending.length > 0) {
+ const directory = pending.pop()!;
+ let entries: Dirent[];
+ try {
+ entries = await readdir(directory, { withFileTypes: true });
+ } catch {
+ throw new IOSSimulatorInstanceError(
+ 'APP_ARTIFACT_INVALID',
+ 'The immutable app artifact could not be inspected.',
+ );
+ }
+ for (const entry of entries) {
+ const entryPath = path.join(directory, entry.name);
+ if (entry.isSymbolicLink()) {
+ let linkTargetPath: string;
+ let target: string;
+ try {
+ const rawTarget = await readlink(entryPath);
+ linkTargetPath = path.resolve(path.dirname(entryPath), rawTarget);
+ target = await realpath(entryPath);
+ } catch {
+ throw new IOSSimulatorInstanceError(
+ 'APP_ARTIFACT_INVALID',
+ 'The immutable app artifact contains a dangling symbolic link.',
+ );
+ }
+ if (!isPathInside(root, linkTargetPath) || !isPathInside(root, target)) {
+ throw new IOSSimulatorInstanceError(
+ 'APP_ARTIFACT_INVALID',
+ 'The immutable app artifact contains a symbolic link outside its copy.',
+ );
+ }
+ } else if (entry.isDirectory()) {
+ pending.push(entryPath);
+ }
+ }
+ }
+}
+
+async function readIOSSimulatorBuildCacheLastUsedMs(cacheDir: string): Promise<number | null> {
+ try {
+ const raw = await readFile(
+ path.join(cacheDir, IOS_SIMULATOR_BUILD_CACHE_LAST_USED_FILE),
+ 'utf8',
+ );
+ const parsed = Number.parseInt(raw.trim(), 10);
+ return Number.isFinite(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Opportunistic cold-cache reclaim for per-worktree DerivedData + SPM
+ * checkouts. This is a 7-day unused TTL, not a disk quota: it cannot cap
+ * total size. Age comes from the explicit last-used marker, not the
+ * cache-key directory mtime. Because an in-flight build does not keep that
+ * parent mtime fresh, `isSkip` must answer live (not from a snapshot)
+ * whether a key is actively used, so a build admitted mid-sweep is never
+ * removed. Best-effort: a read/stat/rm failure on one entry never blocks a
+ * build.
+ */
+export async function pruneStaleIOSSimulatorBuildCaches(
+ roots: readonly string[],
+ maxAgeMs: number,
+ now: () => number = Date.now,
+ isSkip?: (name: string) => boolean,
+): Promise<void> {
+ const deadline = now() - maxAgeMs;
+ for (const root of roots) {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(root, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ const candidates = entries.filter((entry) => {
+ if (!entry.isDirectory()) return false;
+ if (MANAGED_BUILD_CACHE_TRASH_PATTERN.test(entry.name)) return true;
+ return MANAGED_BUILD_CACHE_KEY_PATTERN.test(entry.name) && !isSkip?.(entry.name);
+ });
+ let cursor = 0;
+ const pruneNext = async (): Promise<void> => {
+ while (cursor < candidates.length) {
+ const entry = candidates[cursor++]!;
+ const full = path.join(root, entry.name);
+ try {
+ // A crash or force-quit may interrupt deletion after the atomic
+ // rename. Trash names are never cache keys, so resume them without
+ // another seven-day wait.
+ if (MANAGED_BUILD_CACHE_TRASH_PATTERN.test(entry.name)) {
+ await rm(full, { recursive: true, force: true }).catch(() => undefined);
+ continue;
+ }
+ const lastUsedMs = await readIOSSimulatorBuildCacheLastUsedMs(full);
+ const info = lastUsedMs === null ? await stat(full) : null;
+ // Re-check after the await: another build may have admitted this
+ // key while the marker/stat was in flight. The sync check-then-rename
+ // below is atomic (no yield), so a key admitted after this point
+ // cannot be removed under an active build.
+ if (isSkip?.(entry.name)) continue;
+ const ageSourceMs = lastUsedMs ?? info?.mtimeMs;
+ if (ageSourceMs === undefined || ageSourceMs >= deadline) continue;
+ // Atomically move the key aside before the (async, slow) recursive
+ // delete. A build admitted during deletion recreates the original key
+ // instead of racing the in-progress rm.
+ const trash = path.join(root, `.trash-${entry.name}-${randomUUID()}`);
+ try {
+ renameSync(full, trash);
+ } catch {
+ // Losing the atomic rename (ENOENT from a concurrent sweep, or any
+ // transient error) abandons this prune attempt. Never remove the
+ // original path here: a build admitted during the failed rename may
+ // already be using the directory, and a sibling rename cannot be
+ // cross-device.
+ continue;
+ }
+ await rm(trash, { recursive: true, force: true }).catch(() => undefined);
+ } catch {
+ // Best-effort per entry.
+ }
+ }
+ };
+ await Promise.all(
+ Array.from(
+ {
+ length: Math.min(IOS_SIMULATOR_BUILD_CACHE_PRUNE_CONCURRENCY, candidates.length),
+ },
+ () => pruneNext(),
+ ),
+ );
+ }
+}
+
+/**
+ * Reclaim immutable app copies left behind by a crashed/force-quit Host.
+ *
+ * App handles are intentionally process-local, so a new Host cannot rebuild
+ * the in-memory registry that normally protects those copies from eviction.
+ * Treat each UUID-shaped copy as independently TTL-managed instead of using
+ * the parent cache key's last-used marker: a later build can keep that key
+ * fresh forever while old copies remain unreachable. The final live check and
+ * synchronous rename make the slow recursive delete safe against a build or
+ * artifact operation admitted during the scan.
+ *
+ * Returns false when a filesystem operation should be retried on a later
+ * ownership reconciliation pass. Missing paths and benign races count as
+ * complete because another actor already performed the cleanup.
+ */
+export async function reconcileOrphanedIOSSimulatorArtifactCopies(
+ projectsRoot: string,
+ maxAgeMs: number,
+ now: () => number = Date.now,
+ isSkip?: (cacheKey: string, artifactPath: string) => boolean,
+): Promise<boolean> {
+ const deadline = now() - maxAgeMs;
+ let complete = true;
+ let projectEntries: Dirent[];
+ try {
+ projectEntries = await readdir(projectsRoot, { withFileTypes: true });
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT';
+ }
+
+ const cacheEntries = projectEntries.filter(
+ (entry) => entry.isDirectory() && !entry.name.startsWith('.trash-'),
+ );
+ let cursor = 0;
+ const reconcileNext = async (): Promise<void> => {
+ while (cursor < cacheEntries.length) {
+ const cacheEntry = cacheEntries[cursor++]!;
+ const cacheKey = cacheEntry.name;
+ const artifactsRoot = path.join(projectsRoot, cacheKey, 'artifacts');
+ try {
+ // Never follow a user-created `artifacts` symlink while cleaning up.
+ // The build path is a real directory created by this module; a
+ // symlink here could otherwise redirect recursive rm outside the
+ // managed projects root.
+ const artifactsRootMetadata = await lstat(artifactsRoot);
+ if (!artifactsRootMetadata.isDirectory()) continue;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;
+ continue;
+ }
+ let artifactEntries: Dirent[];
+ try {
+ artifactEntries = await readdir(artifactsRoot, { withFileTypes: true });
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT') complete = false;
+ continue;
+ }
+
+ for (const artifactEntry of artifactEntries) {
+ if (!artifactEntry.isDirectory()) continue;
+ const artifactPath = path.join(artifactsRoot, artifactEntry.name);
+ if (MANAGED_ARTIFACT_COPY_TRASH_PATTERN.test(artifactEntry.name)) {
+ await rm(artifactPath, { recursive: true, force: true }).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;
+ });
+ continue;
+ }
+ if (!MANAGED_ARTIFACT_COPY_PATTERN.test(artifactEntry.name)) continue;
+ try {
+ if (isSkip?.(cacheKey, artifactPath)) continue;
+ const metadata = await stat(artifactPath);
+ if (!metadata.isDirectory() || metadata.mtimeMs >= deadline) continue;
+ // The copy may have become live while stat() was in flight. The
+ // check must happen immediately before the synchronous rename.
+ if (isSkip?.(cacheKey, artifactPath)) continue;
+ const trashPath = path.join(
+ artifactsRoot,
+ `${ARTIFACT_COPY_TRASH_PREFIX}${artifactEntry.name}-${randomUUID()}`,
+ );
+ try {
+ renameSync(artifactPath, trashPath);
+ } catch (error) {
+ // A concurrent cleanup/build may have won the rename. Do not
+ // remove the original path after losing that atomic race.
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;
+ continue;
+ }
+ await rm(trashPath, { recursive: true, force: true }).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;
+ });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;
+ }
+ }
+ }
+ };
+
+ await Promise.all(
+ Array.from(
+ {
+ length: Math.min(IOS_SIMULATOR_BUILD_CACHE_PRUNE_CONCURRENCY, cacheEntries.length),
+ },
+ () => reconcileNext(),
+ ),
+ );
+ return complete;
+}
+ type IOSSimulatorHostToolName = IOSSimulatorMcpToolName | IOSSimulatorRendererToolName;
+
interface IOSSimulatorSessionSnapshot {
id: string;
workDir: string;