Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge branch 'main' (9bcf7bd1a) into redo/plugin-approval-receipt-migration
Yuewei-LLce113f03336a
diff --cc apps/desktop/src/main/cindy-brain/GhostManager.tsindex bf682c6774,9c4f8c67fa..b99a14bd99--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@@ -11,11 -9,10 +11,12 @@@ importGHOST_LOCALE_MAX_BYTES,GHOST_ICON_MAX_BYTES,GHOST_INSTALL_MANIFEST_MAX_BYTES,+ GHOST_SLOTS,GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,+ ghostInstallApprovalToken,ghostIconMimeType,+ isOfficialGhostId,isValidGhostId,resolveGhostManifestLocale,validateGhostManifest,@@@ -52,51 -34,7 +53,46 @@@ importexport const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;export const MAX_NODE_CINDY_FILE_BYTES = 128 * 1024 * 1024;/** 身份卡本身只应是小 JSON;先限流读取,避免在识别包类型前被单文件撑爆内存。 */-const MAX_GHOST_MANIFEST_BYTES = GHOST_INSTALL_MANIFEST_MAX_BYTES;+const MAX_GHOST_MANIFEST_BYTES = GHOST_MANIFEST_MAX_BYTES;++async function readRegularFileStableWithLimit(+ filePath: string,+ maxBytes: number,+): Promise<Buffer> {+ // 顶层 .cindy 路径允许是用户选择的 symlink;确认前后由整包 sha256 对账,+ // 单次读取则始终绑定同一个已打开句柄,避免 stat/read 的二次解析窗口。+ const handle = await fs.promises.open(+ filePath,+ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0),+ );+ try {+ const opened = await handle.stat();+ if (!opened.isFile()) {+ throw new Error('source is not a regular file');+ }+ if (opened.size > maxBytes) {+ throw new Error(`source exceeds ${maxBytes} bytes`);+ }+ const bytes = Buffer.allocUnsafe(opened.size);+ let offset = 0;+ while (offset < bytes.byteLength) {+ const { bytesRead } = await handle.read(bytes, offset, bytes.byteLength - offset, null);+ if (bytesRead === 0) throw new Error('source file shrank while being read');+ offset += bytesRead;+ }+ const after = await handle.stat();+ const sameIdentity = after.isFile() &&+ after.size === opened.size &&+ after.mtimeMs === opened.mtimeMs &&+ after.ctimeMs === opened.ctimeMs &&+ ((opened.dev === 0 && opened.ino === 0) ||+ (after.dev === opened.dev && after.ino === opened.ino));+ if (!sameIdentity) throw new Error('source file changed while being read');+ return bytes;+ } finally {+ await handle.close().catch(() => undefined);+ }+}- /**- * icon 文件大小上限。icon 以 data URL 形态随 ghosts:list(sendSync)下发,- * 上限同时保护装载与首帧同步 IPC 的载荷体积。- */- const MAX_GHOST_ICON_BYTES = 512 * 1024; // 512 KB/** 解压后总大小/条目数上限;Node 包允许携带已打包 CLI,但仍有硬闸。 */export const MAX_BASIC_UNCOMPRESSED_BYTES = 32 * 1024 * 1024;export const MAX_NODE_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;@@@ -208,253 -124,39 +205,278 @@@ export type InstallRejectionexport type UninstallRejection =| { code: 'invalid-id'; reason: string }| { code: 'not-installed'; reason: string }+ | { code: 'approval-required'; reason: string }| { code: 'io'; reason: string };+export type UninstallResult = { ok: true } | { rejection: UninstallRejection };++export interface GhostUninstallOptions {+ notify?: boolean;+ /**+ * User-initiated removal records a builtin tombstone by default. Host+ * reconciliation may explicitly skip it when removing a currently ineligible+ * seed; that is lifecycle cleanup, not a durable user uninstall decision.+ */+ recordBuiltinTombstone?: boolean;+}++interface InstalledReapprovalProjection {+ manifest: GhostManifest;+ trust: GhostTrustInfo;+ localeResources: Record<string, GhostManifestLocaleResource>;+ iconDataUrl?: string;+ skillContentSha256: Record<string, string>;+}++export interface LegacyGhostApprovalProjection {+ manifest: GhostManifest;+ enabled: boolean;+ trust: GhostTrustInfo;+ localeResources: Record<string, GhostManifestLocaleResource>;+ iconDataUrl?: string;+ skillContentSha256: Record<string, string>;+}++export function hashLegacyGhostApprovalProjection(+ projection: LegacyGhostApprovalProjection,+): string {+ return crypto+ .createHash('sha256')+ .update(+ JSON.stringify({+ version: 1,+ manifest: projection.manifest,+ enabled: projection.enabled,+ trust: projection.trust,+ localeResources: projection.localeResources,+ iconDataUrl: projection.iconDataUrl ?? null,+ skillContentSha256: projection.skillContentSha256,+ }),+ )+ .digest('hex');+}++function sameLegacyApprovalDirectoryIdentity(expected: fs.Stats, current: fs.Stats): boolean {+ if (!current.isDirectory() || current.isSymbolicLink()) return false;+ if (expected.dev !== 0 || expected.ino !== 0 || current.dev !== 0 || current.ino !== 0) {+ return expected.dev === current.dev && expected.ino === current.ino;+ }+ return expected.birthtimeMs === current.birthtimeMs && expected.ctimeMs === current.ctimeMs;+}++function sameLegacyApprovalCanonicalPath(left: string, right: string): boolean {+ const fold = (value: string): string =>+ process.platform === 'win32' ? value.toLowerCase() : value;+ return fold(path.resolve(left)) === fold(path.resolve(right));+}++function assertStableLegacyApprovalDirectory(+ dir: string,+ expectedStats: fs.Stats,+ expectedRealPath: string,+): void {+ const currentStats = fs.lstatSync(dir);+ const currentRealPath = fs.realpathSync(dir);+ if (+ !sameLegacyApprovalDirectoryIdentity(expectedStats, currentStats) ||+ !sameLegacyApprovalCanonicalPath(expectedRealPath, currentRealPath)+ ) {+ throw new Error('legacy approval directory changed while reading');+ }+}++function readLegacyDisabledMarkerForApproval(dir: string): boolean {+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ try {+ const kind = classifyGhostDirEntrySync(marker);+ if (kind === 'file') return true;+ throw new Error('legacy disabled marker is not a regular file');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+}++function readLegacyLocaleResourcesForApproval(+ dir: string,+ realDir: string,+ manifest: GhostManifest,+): Record<string, GhostManifestLocaleResource> {+ const resources: Record<string, GhostManifestLocaleResource> = {};+ for (const localePath of Object.values(manifest.locales ?? {})) {+ if (!localePath) continue;+ const absPath = resolveGhostContentPathSync(dir, localePath, {+ expect: 'file',+ label: 'legacy locale',+ });+ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {+ containWithin: realDir,+ });+ if (bytes === null) throw new Error(`legacy locale missing or oversized: ${localePath}`);+ let raw: unknown;+ try {+ raw = JSON.parse(bytes.toString('utf8'));+ } catch (error) {+ throw new Error(+ `legacy locale is not valid JSON: ${localePath}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ }+ const validated = validateGhostManifestLocaleResource(raw, manifest);+ if (!validated.ok) throw new Error(`legacy locale invalid: ${localePath}`);+ resources[localePath] = validated.resource;+ }+ return resources;+}++function readLegacyIconDataUrlForApproval(+ dir: string,+ realDir: string,+ manifest: GhostManifest,+): string | undefined {+ if (manifest.icon === undefined) return undefined;+ try {+ const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {+ expect: 'file',+ label: 'legacy icon',+ });- const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {++ const bytes = readBoundedFileNoFollowSync(iconPath, GHOST_ICON_MAX_BYTES, {+ containWithin: realDir,+ });+ if (bytes === null) return undefined;+ return buildIconDataUrl(manifest.icon, bytes) ?? undefined;+ } catch {+ // Icon data is presentation-only. A broken optional icon must not make an+ // otherwise valid legacy approval ineligible for zero-operation migration.+ return undefined;+ }+}++/**+ * Read the complete legacy approval fact once. Recovery freezes only its digest,+ * then both the pre-rename gate and receipt backfill re-read this same projection.+ */+export async function readLegacyGhostApprovalProjection(+ dir: string,+ id: string,+): Promise<{ projection: LegacyGhostApprovalProjection; sha256: string }> {+ const dirStats = fs.lstatSync(dir);+ if (!dirStats.isDirectory() || dirStats.isSymbolicLink()) {+ throw new Error('legacy approval source is not a real directory');+ }+ const realDir = fs.realpathSync(dir);+ assertStableLegacyApprovalDirectory(dir, dirStats, realDir);+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {+ expect: 'file',+ label: 'legacy manifest',+ });+ const rawBytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {+ containWithin: realDir,+ });+ if (rawBytes === null) throw new Error('legacy manifest is missing or oversized');+ let raw: unknown;+ try {+ raw = JSON.parse(rawBytes.toString('utf8'));+ } catch (error) {+ throw new Error(`invalid manifest JSON: ${error instanceof Error ? error.message : String(error)}`);+ }+ const validated = validateGhostManifest(raw);+ if (!validated.ok) throw new Error(`invalid manifest: ${validated.reason}`);+ if (validated.manifest.id !== id) throw new Error('manifest id != install dir name');++ const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ };+ const projection: LegacyGhostApprovalProjection = {+ manifest: validated.manifest,+ enabled: !readLegacyDisabledMarkerForApproval(dir),+ trust,+ localeResources: readLegacyLocaleResourcesForApproval(dir, realDir, validated.manifest),+ skillContentSha256: await hashApprovedSkillContent(validated.manifest, dir),+ };+ const iconDataUrl = readLegacyIconDataUrlForApproval(dir, realDir, validated.manifest);+ if (iconDataUrl !== undefined) projection.iconDataUrl = iconDataUrl;+ assertStableLegacyApprovalDirectory(dir, dirStats, realDir);+ return { projection, sha256: hashLegacyGhostApprovalProjection(projection) };+}++function hashInstalledReapprovalProjection(+ projection: InstalledReapprovalProjection,+): string {+ return crypto+ .createHash('sha256')+ .update(+ JSON.stringify({+ version: 1,+ manifest: projection.manifest,+ trust: projection.trust,+ localeResources: projection.localeResources,+ iconDataUrl: projection.iconDataUrl ?? null,+ skillContentSha256: projection.skillContentSha256,+ }),+ )+ .digest('hex');+}++/**+ * `runExclusiveMutation` 回调内唯一可用的嵌套 mutation capability。+ * capability 在回调结束后立即失效,避免调用者绕过串行 lane 或复用旧 owner 上下文。+ */+export interface GhostExclusiveMutation {+ writeDisabledMarker(id: string): void;+ publishTrustedBundledSeed(+ id: string,+ sourceDir: string,+ options: {+ disabled: boolean;+ trust?: typeof CINDY_OFFICIAL_GHOST_TRUST;+ },+ ): Promise<void>;+ approveTrustedBundledInstall(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean>;+ removeInstallApproval(id: string): Promise<boolean>;+ uninstall(id: string, options?: GhostUninstallOptions): Promise<UninstallResult>;+}++ /**+ * 区分“包本身坏了”和“包使用了更新版 Cindy 才认识的契约”。+ *+ * 这里只收窄识别两个可证明是 Host 版本差异的形状:未来 schemaVersion,或+ * 字符串形态的未知 capability slot。其它畸形输入仍交给完整 manifest 校验,+ * 不能借友好提示放松安装安全边界。+ */+ export function ghostManifestHostUnsupportedReason(raw: unknown): string | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const record = raw as Record<string, unknown>;+ if (+ typeof record.schemaVersion === 'number' &&+ Number.isInteger(record.schemaVersion) &&+ record.schemaVersion > 2+ ) {+ return `插件使用了更新的清单格式(schemaVersion ${record.schemaVersion})`;+ }+ if (!Array.isArray(record.slots)) return null;+ const supported = new Set<string>([...GHOST_SLOTS, 'model']);+ const unknown = [+ ...new Set(record.slots.filter((slot): slot is string => typeof slot === 'string')),+ ].filter((slot) => !supported.has(slot));+ return unknown.length > 0 ? `插件需要当前 Cindy 尚不支持的能力:${unknown.join(' / ')}` : null;+ }+/**- * 意识仓库的 main 端管理者:一个意识一个子目录(rootDir/<id>/),目录即事实。+ * 插件仓库的 main 端管理者:一个插件一个内容目录(rootDir/<id>/),Host+ * receipt 才是 manifest / trust / enabled / revision 的授权事实。** 设计要点:- * - **目录即注册表**:没有额外的 DB / 索引文件,list() 每次实扫磁盘 ——- * 装了什么打开文件夹一目了然,坏一个目录只影响那一个意识(跳过 + warn);+ * - **目录只证明在装**:list() 实扫内容目录,但批准状态来自安装根之外的+ * receipt;旧安装没有 receipt 时保持不可运行,更新需完整重新确认;* - **装载先落 staging 再切正式**(对齐 skillhub/installService 的做法):* 解压全程发生在 `.cindy-installing-*` 临时目录,校验全过才 rename 到* rootDir/<id>,任何一步失败都不会留下半截安装;@@@ -2234,15 -310,12 +2256,15 @@@ export class GhostManager*/private readInstalledIconDataUrl(dir: string, manifest: GhostManifest): string | null {if (manifest.icon === undefined) return null;- const iconPath = path.join(dir, ...manifest.icon.split('/'));try {- // statSync 后再 readFileSync 是两次独立打开:并发方可在其间把 icon 换成- // 指向宿主任意文件的链接,字节会被包成 dataURL 经 IPC 送进 Renderer。- // 单句柄限量闸拒链接、限大小;containWithin 堵中间目录链接。+ // 逐段 no-follow 解析(拒符号链接段,判据与技能目录 / locale 同源)+ 单句柄限量读:+ // stat 后再 readFileSync 是两次独立打开,并发方可在其间把 icon 换成指向宿主任意+ // 文件的链接,字节会被包成 dataURL 经 IPC 送进 Renderer。containWithin 堵中间目录链接。+ const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {+ expect: 'file',+ label: 'ghost icon',+ });- const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {+ const bytes = readBoundedFileNoFollowSync(iconPath, GHOST_ICON_MAX_BYTES, {containWithin: fs.realpathSync(dir),});if (bytes === null) {diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex e384693ca0,c1938dcfc2..38265647ee--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@@ -165,3807 -90,428 +165,3821 @@@ async function expectRejectionexpect((result as { rejection: { code: string } }).rejection.code).toBe(code);}-describe('GhostManager · install', () => {- it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {- const manifest = {- ...goodManifest(),- name: 'Base name',- description: 'Base description',- locales: {- en: 'locales/en.json',- 'zh-CN': 'locales/zh-CN.json',- },- };- const locale = (name: string, description: string, toolDescription: string) =>- JSON.stringify({- name,- description,- tools: { do_thing: { description: toolDescription } },- });- const cindy = await makeCindy('localized.cindy', manifest, {- 'locales/en.json': locale('English name', 'English description', 'English tool'),- 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),- });- const result = await manager.install(cindy);- expect(result).toMatchObject({- ghost: {- manifest: {- name: '中文名称',- description: '中文说明',- resolvedLocale: 'zh-CN',- tools: [{ name: 'do_thing', description: '中文工具' }],- },- },- });-- hostLocale = 'ja';- expect(manager.list()[0].manifest).toMatchObject({- name: 'English name',- description: 'English description',- resolvedLocale: 'ja',- tools: [{ name: 'do_thing', description: 'English tool' }],- });- hostLocale = 'fr-FR';- expect(manager.list()[0].manifest).toMatchObject({- name: 'English name',- resolvedLocale: 'en',- });+async function updateGhost(+ cindyPath: string,+ id = 'hello',+): ReturnType<GhostManager['update']> {+ const installed = manager.list().find((ghost) => ghost.manifest.id === id);+ return manager.update(cindyPath, {+ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),});+}- it('已安装 locale 或其父目录被替换为目录外软链时拒绝读取并回退基础清单', async () => {- hostLocale = 'en';- const manifest = {- ...goodManifest(),- name: 'Base name',- locales: { en: 'locales/en.json' },- };- const locale = (name: string) =>- JSON.stringify({- name,- tools: { do_thing: { description: 'Localized tool' } },- });- const cindy = await makeCindy('localized-symlink.cindy', manifest, {- 'locales/en.json': locale('Packaged name'),+describe('hashApprovedSkillContent · item.dir 路径段校验', () => {+ it('rejects a link in an intermediate path segment instead of hashing bytes from outside', async () => {+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成软链 / junction 时 OS 会静默穿透,+ // 对最终段 lstat 报的是"真目录、非链接",于是指纹从技能目录之外取字节。首次批准+ // 那条路径的指纹是现算的,外部内容会被钉成"批准字节"再复制成快照,而 frontmatter+ // 一致性校验只看 name/description(manifest 里公开可抄),拦不住。所以这里必须抛错,+ // 不能返回一个哈希。+ const validated = validateGhostManifest({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },});- await manager.install(cindy);- const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');- const outsidePath = path.join(workDir, 'outside-locale.json');- await fs.promises.writeFile(outsidePath, locale('Outside name'));- await fs.promises.rm(localePath);+ if (!validated.ok) throw new Error(validated.reason);++ const base = path.join(workDir, 'plugin');+ const evil = path.join(workDir, 'evil');+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });+ await fs.promises.mkdir(path.join(evil, 'demo'), { recursive: true });+ await fs.promises.writeFile(+ path.join(base, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ );+ await fs.promises.writeFile(+ path.join(evil, 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 正常结构先能算出来,确认用例本身走到了目标代码。+ await expect(hashApprovedSkillContent(validated.manifest, base)).resolves.toHaveProperty(+ 'skills/demo',+ );++ // 把**中间段** skills 换成指向外部的链接。+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });try {- await fs.promises.symlink(outsidePath, localePath, 'file');+ await fs.promises.symlink(+ evil,+ path.join(base, 'skills'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );} catch {- return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。}- expect(manager.list()[0].manifest).toMatchObject({- name: 'Base name',- resolvedLocale: 'en',- tools: [{ name: 'do_thing', description: '做点事' }],- });-- const localesDir = path.dirname(localePath);- const outsideLocalesDir = path.join(workDir, 'outside-locales');- await fs.promises.rm(localesDir, { recursive: true, force: true });- await fs.promises.mkdir(outsideLocalesDir);- await fs.promises.writeFile(- path.join(outsideLocalesDir, 'en.json'),- locale('Outside parent name'),- );- await fs.promises.symlink(- outsideLocalesDir,- localesDir,- process.platform === 'win32' ? 'junction' : 'dir',+ await expect(hashApprovedSkillContent(validated.manifest, base)).rejects.toThrow(+ /path segment is a link/,);- expect(manager.list()[0].manifest).toMatchObject({- name: 'Base name',- resolvedLocale: 'en',+ });+});++describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {+ /** 带 skill 槽的旧布局清单 + 配套 SKILL.md(frontmatter 与声明逐字一致)。 */+ const legacySkillManifest = (id = 'skilled'): Record<string, unknown> => ({+ ...goodManifest(id),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ });+ const legacySkillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('市场/本地旧安装无感迁移:升级后仍启用、列 approved、写下迁移台账', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 迁移前:没有 receipt → 一律 fail closed(这正是 #1080 被回滚的现场)。+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'legacy-unapproved' } });++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ // 迁移后:用户什么都没做,插件照旧可用。+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },});+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);});- it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {- const manifest = {- ...goodManifest(),- locales: { en: 'locales/en.json' },+ it('未批准或 receipt 损坏的插件不展示可变 trust 镜像', async () => {+ const forgedTrust = {+ level: 'cindy-official' as const,+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ publisherName: 'Forged publisher',+ reviewerName: 'Forged reviewer',};- const missing = await makeCindy('locale-missing.cindy', manifest);- await expectRejection(await manager.install(missing), 'file-invalid');+ await writeLegacyInstall('legacy', goodManifest('legacy'), { trust: forgedTrust });+ await writeLegacyInstall('invalid', goodManifest('invalid'), { trust: forgedTrust });+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ path.join(workDir, 'ghosts-install-state', 'invalid.json'),+ JSON.stringify({ schemaVersion: 1, id: 'invalid' }),+ );- const invalid = await makeCindy('locale-invalid.cindy', manifest, {- 'locales/en.json': '{ nope',+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));+ expect(byId.legacy).toMatchObject({+ approval: { state: 'legacy-unapproved' },+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },});- await expectRejection(await manager.install(invalid), 'file-invalid');-- const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {- 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),+ expect(byId.invalid).toMatchObject({+ approval: { state: 'invalid' },+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },});- await expectRejection(await manager.install(unknownTool), 'file-invalid');+ expect(byId.legacy.trust).not.toHaveProperty('publisherName');+ expect(byId.invalid.trust).not.toHaveProperty('reviewerName');+ });- // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。- hostLocale = 'en';- const partial = await makeCindy('locale-partial.cindy', manifest, {- 'locales/en.json': JSON.stringify({ name: 'English partial' }),+ it('旧安装的停用态被保留:.disabled 镜像 → receipt.enabled=false', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ await manager.migrateLegacyApprovalsOnce();+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },});- expect(await manager.install(partial)).toMatchObject({- ghost: {- manifest: {- name: 'English partial',- resolvedLocale: 'en',- tools: [{ name: 'do_thing', description: '做点事' }],- },+ });++ it('信任镜像被保留;缺失时保守降级为 unverified 而不是让迁移失败', async () => {+ await writeLegacyInstall('trusted', goodManifest('trusted'), {+ trust: {+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: false,+ publisherName: 'Acme',},});+ await writeLegacyInstall('bare', goodManifest('bare'), { trust: 'omit' });+ await manager.migrateLegacyApprovalsOnce();+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g]));+ expect(byId.trusted.trust).toMatchObject({ level: 'verified-publisher', publisherName: 'Acme' });+ expect(byId.trusted.enabled).toBe(true);+ // 信任文件缺失不阻断迁移:插件照旧可用,只是展示为 unverified(旧模型读同一文件也如此)。+ expect(byId.bare.trust).toMatchObject({ level: 'unverified' });+ expect(byId.bare.enabled).toBe(true);+ });- const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {- 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),+ it('skill 槽旧安装迁移后:快照建好、字节指纹钉住、对账认可挂链', async () => {+ await writeLegacyInstall('skilled', legacySkillManifest(), { files: legacySkillFiles() });+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['skilled']);+ const ghost = manager.list()[0];+ expect(ghost).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(ghost.approvedSkillRoot).toBeTruthy();+ // 迁移出的快照必须能被技能对账认可(字节与 receipt 指纹逐字节对上),否则技能链断。+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);+ });++ it('全局一次性:台账落地后,新出现的无 receipt 目录不再被迁移(fail closed)', async () => {+ await writeLegacyInstall('first', goodManifest('first'));+ await manager.migrateLegacyApprovalsOnce();+ expect(manager.list().find((g) => g.manifest.id === 'first')?.approval.state).toBe('approved');++ // 台账已在。此后再冒出一个没有 receipt 的目录(可能是删了 receipt 想骗迁移,或+ // 真的新拷进来的旧目录)——迁移不再触发,它保持 fail closed。删 receipt 想"从可变+ // 安装目录重建授权"这条路被这道门堵死。+ await writeLegacyInstall('second', goodManifest('second'));+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list().find((g) => g.manifest.id === 'second')?.approval.state).toBe(+ 'legacy-unapproved',+ );+ });++ it('迁移绝不改动安装目录三文件(回滚到旧客户端仍按安装目录判定,§5 兜底第 4 条)', async () => {+ const dir = await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const before = {+ manifest: await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'),+ disabled: fs.existsSync(path.join(dir, '.disabled')),+ trust: await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8'),+ };+ await manager.migrateLegacyApprovalsOnce();+ expect(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8')).toBe(before.manifest);+ expect(fs.existsSync(path.join(dir, '.disabled'))).toBe(before.disabled);+ expect(await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8')).toBe(before.trust);+ });++ it('manifest 不合法的旧目录不迁移,保持 fail closed,不写出坏 receipt', async () => {+ const dir = path.join(rootDir, 'broken');+ await fs.promises.mkdir(dir, { recursive: true });+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), '{ not valid json');+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.failed).toEqual(['broken']);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'broken.json'))).toBe(false);+ });++ it('随包种子 id 跳过迁移(交给 provisioning 的逐字节对账补批准)', async () => {+ const seededManager = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ isTrustedBundledId: (id) => id === 'hello',});- await expectRejection(await manager.install(aliasedManifest), 'file-invalid');+ await writeLegacyInstall('hello', goodManifest());+ const outcome = await seededManager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });+ // 没有替它写 receipt:provisioning 才是随包插件的批准入口。+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);});- it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {- const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- const { ghost } = result as { ghost: InstalledGhost };- expect(ghost.manifest.id).toBe('hello');- expect(ghost.dir).toBe(path.join(rootDir, 'hello'));- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);+ it('瞬时状态根 IO 不封门:台账停在 in-progress,下次启动自动续跑治愈', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 第一轮:receipt 落盘的 rename 吃一次 EACCES(模拟杀软/句柄占用的环境抖动)。+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}hello.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });+ const first = await manager.migrateLegacyApprovalsOnce();+ // 瞬时错不算"内容无效":不进 failed(那会写进 completed 台账永久封门),+ // 记 retryPending、台账停在 in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(ledger.state).toBe('in-progress');+ expect(ledger.pendingIds).toEqual(['hello']);- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);+ // 第二轮(下次启动):环境恢复,自动续跑治愈,不需要用户操作。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ const finalLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string };+ expect(finalLedger.state).toBe('completed');});- it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {- const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));- const localResult = await manager.install(local);- expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });- await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });+ it('读 legacy ghost.json 的瞬时 IO(EACCES)判瞬时、不永久封门(P1 回归)', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const realOpenSync = fs.openSync;+ // 只让 <root>/hello/ghost.json 的单句柄安全读取吃一次 EACCES(模拟杀软/句柄占用),+ // 其余照常。+ const spy = vi+ .spyOn(fs, 'openSync')+ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {+ if (typeof p === 'string' && p.endsWith(path.join('hello', 'ghost.json'))) {+ spy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);+ }) as typeof fs.openSync);- const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });- expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });- const receipt = JSON.parse(- await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),- ) as { level?: unknown };- expect(receipt.level).toBe('cindy-official');- expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);- expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ const first = await manager.migrateLegacyApprovalsOnce();+ // 修复前:readFileSync 的错被包成无 code 的 new Error → 误判确定性 failed →+ // 写进 completed 台账永久封门。修复后:保留 errno → 判瞬时 → retryPending + in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);+ const ledger = JSON.parse(fs.readFileSync(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ };+ expect(ledger.state).toBe('in-progress');++ // 下轮环境恢复:自动续跑治愈,不需要用户重新确认。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });});- it('残缺的官方 receipt 不会被投影为可用的官方 trust', async () => {- const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));- await manager.install(local, { trustOverride: 'cindy-official' });- const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;- delete metadata.publisherName;- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ it('legacy .disabled marker IO errors stay pending instead of becoming disabled', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const markerPath = path.join(rootDir, 'hello', '.disabled');+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {+ if (path.resolve(String(target)) === path.resolve(markerPath)) {+ spy.mockRestore();+ throw Object.assign(new Error('EIO: marker temporarily unreadable'), { code: 'EIO' });+ }+ return realLstatSync(target, options as never);+ });++ const first = await manager.migrateLegacyApprovalsOnce();+ expect(first).toMatchObject({ migrated: [], failed: [], retryPending: ['hello'] });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'in-progress',+ pendingIds: ['hello'],+ });+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'legacy-unapproved' } });- expect(manager.list()[0]?.trust).toBeUndefined();+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });});- it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {- const cindy = await makeCindy('at-resource.cindy', atResourceManifest());- const installed = await manager.install(cindy);+ it('已有 receipt 瞬时不可读时不从可变安装目录重铸,保留原批准并持久重试', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');+ // 模拟 #1080 历史状态没有 ledger;receipt 本身只是在本轮被 AV/权限瞬时锁住。+ await fs.promises.rm(migrationLedgerPath());+ const realOpenSync = fs.openSync;+ const openSpy = vi.spyOn(fs, 'openSync');+ openSpy.mockImplementation((target, ...args) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {+ openSpy.mockRestore();+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);+ });- const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<- string,- unknown- >;+ const first = await manager.migrateLegacyApprovalsOnce();- delete metadata.approvedAtResourceProvider;- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.tools).toEqual([{ name: 'do_thing', description: '做点事' }]);+ expect(first).toEqual({ migrated: [], skipped: [], failed: [], retryPending: ['hello'] });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });- metadata.approvedAtResourceProvider = { tool: 'other_tool' };- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ await manager.migrateLegacyApprovalsOnce();+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })+ .state,+ ).toBe('completed');});- it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {- const cindy = await makeCindy('hello.cindy', goodManifest());- const result = await manager.install(cindy, { initiallyEnabled: false });- expect('ghost' in result).toBe(true);- expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);- // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);- // 重新启用即撕掉标记。- await manager.setEnabled('hello', true);- expect(manager.list()[0].enabled).toBe(true);+ it('首轮迁移治愈损坏/旧 schema 的 receipt(格式升级不落到用户重新确认)', async () => {+ // issue #1243 验收第 4 条的实现形态:schema/编码 bump 后的旧 receipt 判 invalid,+ // 但**首轮迁移**会把它当"已判损坏"从安装目录 backfill 重建 —— 一次内部格式变更+ // 不变成用户重新确认。v1 receipt 从未随任何构建发布,所以不需要专门的 v1 读取器;+ // 未来的 bump 走 §5 的「按旧编码核对 → 原地升级」,见规则文档。+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ // 一份 schemaVersion 过时的 receipt(读取器判 invalid)。+ await fs.promises.writeFile(+ path.join(stateDir, 'hello.json'),+ JSON.stringify({ schemaVersion: 1, id: 'hello', legacy: true }),+ );+ expect(manager.list()[0].approval.state).toBe('invalid');++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ // 治愈后为有效批准;用户的停用决定(.disabled)照旧保留。+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });});- it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {- const zip = new JSZip();- zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));- zip.file('hello-pack/assets/a.txt', 'a');- const out = path.join(workDir, 'wrapped.cindy');- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ it('修复 #1080 历史 mixed 状态:有效 receipt 不封死其余 legacy/旧 schema 插件', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest('approved')));+ const approvedReceiptPath = path.join(workDir, 'ghosts-install-state', 'approved.json');+ const approvedReceiptBefore = await fs.promises.readFile(approvedReceiptPath, 'utf8');- const result = await manager.install(out);- expect('ghost' in result).toBe(true);- // 包裹层被剥掉:内容直接落在 <root>/hello/ 下- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);+ // Fixture 模拟曾短暂合入后回滚的 #1080:部分插件已有 v2 receipt,但当时没有+ // legacy migration ledger;同 owner 下其余旧安装仍无 receipt。删除 ledger 只是+ // 构造这份历史状态,不代表安装根攻击者能操作状态根。+ await fs.promises.rm(migrationLedgerPath());+ await writeLegacyInstall('legacy', goodManifest('legacy'));+ await writeLegacyInstall('old-schema', goodManifest('old-schema'), { disabled: true });+ await fs.promises.writeFile(+ path.join(workDir, 'ghosts-install-state', 'old-schema.json'),+ JSON.stringify({ schemaVersion: 1, id: 'old-schema', legacy: true }),+ );++ const outcome = await manager.migrateLegacyApprovalsOnce();++ expect(outcome.migrated).toEqual(['legacy', 'old-schema']);+ expect(await fs.promises.readFile(approvedReceiptPath, 'utf8')).toBe(approvedReceiptBefore);+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));+ expect(byId.approved.approval.state).toBe('approved');+ expect(byId.legacy).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(byId['old-schema']).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });});- it('源文件不存在 → source-not-found', async () => {- await expectRejection(- await manager.install(path.join(workDir, 'nope.cindy')),- 'source-not-found',+ it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const before = await fs.promises.readFile(+ path.join(workDir, 'ghosts-install-state', 'hello.json'),+ 'utf8',+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual([]);+ expect(await fs.promises.readFile(path.join(workDir, 'ghosts-install-state', 'hello.json'), 'utf8')).toBe(+ before,+ );+ });++ it('声明的 locale 文件损坏 → fail closed(装入天然不含坏 locale,读到即装入后损坏)', async () => {+ hostLocale = 'en';+ await writeLegacyInstall(+ 'hello',+ { ...goodManifest(), name: 'Base', locales: { en: 'locales/en.json' } },+ { files: { 'locales/en.json': '{ broken json' } },);+ const outcome = await manager.migrateLegacyApprovalsOnce();+ // 装入流程逐个校验声明的 locale、不合格拒装,所以旧安装不会带坏 locale;迁移时+ // 读到坏 locale 只能是装入后损坏,属 §5 的"自相矛盾 → fail closed",不写坏 receipt。+ expect(outcome.failed).toEqual(['hello']);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });+});++describe('GhostManager · owner 受管根路径', () => {+ it('允许 userData 祖先通过 symlink/junction 重定位', async () => {+ const physicalUserData = path.join(workDir, 'physical-user-data');+ const linkedUserData = path.join(workDir, 'linked-user-data');+ await fs.promises.mkdir(path.join(physicalUserData, 'owners', 'owner-a'), { recursive: true });+ try {+ await fs.promises.symlink(+ physicalUserData,+ linkedUserData,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }++ const relocated = new GhostManager({+ getRootDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'cindy-brain'),+ getStateDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'ghost-install-state'),+ });++ expect(relocated.list()).toEqual([]);+ });++ it('允许全新 owner 的多层受管根尚未创建', () => {+ const freshOwner = path.join(workDir, 'owners', 'fresh-owner');+ const fresh = new GhostManager({+ getRootDir: () => path.join(freshOwner, 'cindy-brain'),+ getStateDir: () => path.join(freshOwner, 'ghost-install-state'),+ });++ expect(fresh.list()).toEqual([]);+ });++ it('仍拒绝受管根本身是 symlink/junction', async () => {+ const outside = path.join(workDir, 'outside-root');+ const linkedRoot = path.join(workDir, 'linked-root');+ await fs.promises.mkdir(outside, { recursive: true });+ try {+ await fs.promises.symlink(outside, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return;+ }++ expect(+ () =>+ new GhostManager({+ getRootDir: () => linkedRoot,+ getStateDir: () => path.join(workDir, 'state-root'),+ }),+ ).toThrow(/ghost content root is not a real directory/);+ });+});++describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {+ it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {+ // 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被+ // in-progress 台账挡住)、bbb 还没动笔时进程死掉。+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await writeLegacyInstall('bbb', goodManifest('bbb'));+ await manager.migrateLegacyApprovalsOnce();+ // 手工把状态倒回"崩溃时刻":台账退回 in-progress、bbb 的 receipt 消失。+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['aaa', 'bbb'],+ }),+ );+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'bbb.json'));++ const outcome = await manager.migrateLegacyApprovalsOnce();+ // bbb 被续跑补迁;aaa 已有 receipt,计入 migrated(它就是迁移铸出的)。+ expect(outcome.migrated).toEqual(['bbb']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId).toEqual({ aaa: 'approved', bbb: 'approved' });+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ migratedIds: string[];+ };+ expect(ledger.state).toBe('completed');+ expect(ledger.migratedIds).toEqual(['aaa', 'bbb']);+ });++ it('续跑只认动笔前钉死的清单:清单外的无 receipt 目录不被重铸', async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ // 迁移窗口期间新装再删 receipt 的插件(不在 pendingIds 里)骗不到续跑。+ await writeLegacyInstall('ccc', goodManifest('ccc'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['aaa'],+ }),+ );++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['aaa']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId.aaa).toBe('approved');+ expect(byId.ccc).toBe('legacy-unapproved');+ expect(+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })+ .state,+ ).toBe('completed');+ });++ it('receipt 首写的自动落账不覆盖 in-progress 台账(崩溃门不被焊死)', async () => {+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['zzz'],+ }),+ );+ // 迁移窗口内经正常装入流程写 receipt(内部有"缺台账即补写 completed"的守卫)。+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ };+ expect(ledger.state).toBe('in-progress');+ });++ it('台账存在但读不出:门保守关死,不迁也不重写', async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');+ });++ it.each([+ ['empty pendingIds', []],+ ['non-string pending id', [null]],+ ['path-traversal pending id', ['../x']],+ ['mixed valid and invalid pending ids', ['aaa', '../x']],+ ])('非法 in-progress 台账(%s)保守关门且不被重写成 completed', async (_label, pendingIds) => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });+ const raw = JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds,+ });+ await fs.promises.writeFile(migrationLedgerPath(), raw);++ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: [],+ failed: [],+ retryPending: [],+ });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe(raw);+ });++ it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。+ const marker = path.join(rootDir, 'hello', '.disabled');+ await fs.promises.writeFile(marker, '');+ expect(manager.list()[0].enabled).toBe(false);++ // receipt 落盘的 rename 失败(状态根抖动):启用必须整体失败且镜像原样放回。+ const realRename = fs.promises.rename;+ const spy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');+ return realRename(from, to);+ });+ try {+ const result = await manager.setEnabled('hello', true);+ expect('rejection' in result && result.rejection.code).toBe('io');+ } finally {+ spy.mockRestore();+ }+ expect(fs.existsSync(marker)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('进程内隔离按状态根命名空间:A 账号的隔离不污染 B,切回 A 仍生效', async () => {+ let stateDir = path.join(workDir, 'owner-a-state');+ const owned = new GhostManager({+ getRootDir: () => rootDir,+ getStateDir: () => stateDir,+ getLocale: () => hostLocale,+ });+ await owned.install(await makeCindy('a.cindy', goodManifest()));+ // 撤销失败 → A 的进程内隔离。+ const realRm = fs.promises.rm;+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, opts) => {+ if (String(target).endsWith('hello.json')) throw new Error('EACCES');+ return realRm(target as never, opts as never);+ });+ try {+ await owned.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }+ expect(owned.list()[0].approval.state).toBe('invalid');++ // 切到 B 账号(状态根变了):同 id 不被 A 的隔离污染 —— B 没有 receipt,+ // 如实是 legacy-unapproved 而不是 invalid。+ stateDir = path.join(workDir, 'owner-b-state');+ expect(owned.list()[0].approval.state).toBe('legacy-unapproved');++ // 切回 A:隔离仍在(盘上那份陈旧 receipt 不得复活)。+ stateDir = path.join(workDir, 'owner-a-state');+ expect(owned.list()[0].approval.state).toBe('invalid');+ });++ it('安装根下的 junction 不算已装插件:迁移不迁它,list 不列它', async () => {+ await writeLegacyInstall('real', goodManifest('real'));+ const outside = path.join(workDir, 'outside-plugin');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'ghost.json'), JSON.stringify(goodManifest('planted')));+ try {+ fs.symlinkSync(outside, path.join(rootDir, 'planted'), 'junction');+ } catch {+ return; // 环境建不了链接则跳过;判据逻辑平台无关。+ }++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['real']);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['real']);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'planted.json'))).toBe(false);+ });+});++describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {+ it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {+ // 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,+ // 本地包用户没有市场路线;第三条路必须能不找文件恢复。+ await writeLegacyInstall('hello', goodManifest());+ await manager.migrateLegacyApprovalsOnce();+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');++ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.manifest.id).toBe('hello');+ expect(inspected.manifestSha256).toMatch(/^[a-f0-9]{64}$/);++ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ // 启停镜像同步维护(回滚到旧客户端不错位)。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);+ });++ it('重新确认要求立即启用时,删除停用镜像失败必须拒绝且不提交批准', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const marker = path.join(rootDir, 'hello', '.disabled');+ const realRm = fs.promises.rm;+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(marker)) {+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });+ }+ return realRm(target, options);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ expect(fs.existsSync(marker)).toBe(true);+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('重新确认要求立即启用时,receipt 提交失败必须恢复原停用镜像', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const marker = path.join(rootDir, 'hello', '.disabled');+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');+ return realRename(from, to);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ expect(fs.existsSync(marker)).toBe(true);+ } finally {+ renameSpy.mockRestore();+ }+ });++ it('重新确认不跟随确认后被换成 junction 的安装目录写删停用镜像', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const dir = path.join(rootDir, 'hello');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-outside-'));+ const outsideMarker = path.join(outside, '.disabled');+ await fs.promises.writeFile(outsideMarker, 'sentinel');+ const probe = path.join(workDir, 'reapprove-junction-probe');+ try {+ await fs.promises.symlink(outside, probe, process.platform === 'win32' ? 'junction' : 'dir');+ await fs.promises.rm(probe, { force: true });+ } catch {+ await fs.promises.rm(outside, { recursive: true, force: true });+ return;+ }+ const realInspect = manager.inspectInstalledReapproval.bind(manager);+ const inspectSpy = vi.spyOn(manager, 'inspectInstalledReapproval').mockImplementation(async (ghostId) => {+ const result = await realInspect(ghostId);+ await fs.promises.rm(dir, { recursive: true, force: true });+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ return result;+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(await fs.promises.readFile(outsideMarker, 'utf8')).toBe('sentinel');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ } finally {+ inspectSpy.mockRestore();+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('重新确认 receipt 失败回滚前目录被换成 junction 时不得写入外部目标', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const dir = path.join(rootDir, 'hello');+ const displaced = path.join(rootDir, 'hello-displaced');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-rollback-'));+ let linkCreated = false;+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) {+ await realRename(dir, displaced);+ try {+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ linkCreated = true;+ } catch {+ await realRename(displaced, dir);+ }+ throw new Error('state root unwritable');+ }+ return realRename(from, to);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ if (linkCreated) expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);+ } finally {+ renameSpy.mockRestore();+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));++ // 攻击窗口:用户看的是权限集 A,confirm 落地前清单被换成声明更多权限的 B。+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({ ...goodManifest(), name: 'Changed after review' }),+ );+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it.each(['skill', 'locale', 'icon', 'trust'] as const)(+ '确认间隙 %s 批准投影被换 → 拒绝重新确认',+ async (kind) => {+ const manifest = {+ ...goodManifest(),+ author: 'Original author',+ icon: 'assets/icon.png',+ locales: { en: 'locales/en.json' },+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ };+ await writeLegacyInstall('hello', manifest, {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',+ },+ });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));++ if (kind === 'skill') {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',+ );+ } else if (kind === 'locale') {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'locales', 'en.json'),+ JSON.stringify({ name: 'Replaced name' }),+ );+ } else if (kind === 'icon') {+ await fs.promises.writeFile(path.join(rootDir, 'hello', 'assets', 'icon.png'), 'REPLACED ICON');+ } else {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ publisherName: 'Different publisher',+ }),+ );+ }++ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ },+ );++ it('随包插件拒走人工重新确认(由启动对账自动补批准)', async () => {+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ });+ await writeLegacyInstall('hello', goodManifest());+ const inspected = await guarded.inspectInstalledReapproval('hello');+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');+ });++ it('已是 approved 的插件拒重复确认(不给覆盖既有批准开口子)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const inspected = await manager.inspectInstalledReapproval('hello');+ expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');+ });++ it('信任镜像自称 cindy-official 一律封顶拒收(非随包目录不可能合法持有官方档)', async () => {+ await writeLegacyInstall('hello', goodManifest(), {+ trust: {+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ },+ });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.trust.level).toBe('unverified');+ });+});++describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {+ it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect(manager.list()[0].enabled).toBe(true);++ // 状态根不可写(AV/权限/磁盘故障):receipt 的 rename 提交失败。+ const realRename = fs.promises.rename;+ const renameSpy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).includes('ghosts-install-state')) {+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ try {+ // 停用必须永远能成功:镜像已落盘,如实返回 ok,而不是 io + 回滚镜像(fail open)。+ expect(await manager.setEnabled('hello', false)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(false);+ } finally {+ renameSpy.mockRestore();+ }+ // "重启"(新实例,内存态清零):镜像在盘上,停用不复活。+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(restarted.list()[0].enabled).toBe(false);+ // 启用方向照旧要求 receipt 写成功(此时状态根已恢复可写)。+ expect(await manager.setEnabled('hello', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('P0-5:嵌套 skill dir(祖先包含子项)装入/快照/校验全通,不撞 COPYFILE_EXCL', async () => {+ const nested = {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },+ ],+ },+ };+ const files = {+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',+ };+ const result = await manager.install(await makeCindy('nested.cindy', nested, files));+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));+ const ghost = manager.list()[0];+ expect(ghost.approval.state).toBe('approved');+ // 两个 item 的字节指纹都能对上(嵌套项的根就在祖先拷出的快照树里)。+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);+ });++ it('P0-5:嵌套 skill dir 的旧安装迁移同样成功(存量兼容红线)', async () => {+ await writeLegacyInstall(+ 'skilled',+ {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },+ ],+ },+ },+ {+ files: {+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',+ },+ },+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['skilled']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ });++ it('P0-2:安装根为空/未诞生时不落台账,legacy 恢复流程随后搬入仍可迁移', async () => {+ // 首轮:根目录还不存在(owner 命名空间刚建立,旧目录尚未被恢复流程搬入)。+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: [],+ failed: [],+ retryPending: [],+ });+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。+ await writeLegacyInstall('hello', goodManifest());+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ });++ it('P0-2:首个 receipt 写入即自动落台账 —— "装插件→删 receipt"骗不到迁移', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 新模型首次活动(装入写 receipt)时台账已经落了,不等下一轮 reconcile。+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ // 攻击:改写安装目录 manifest 扩权,再删掉 receipt,指望迁移按新 manifest 重铸批准。+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 's', name: 's', description: 's' }] },+ }),+ );+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('P0-2:首次批准先提交 migration ledger,落账失败时不留下有效 receipt', async () => {+ const renameTargets: string[] = [];+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ const target = String(to);+ renameTargets.push(target);+ if (target.endsWith('.legacy-migration.json')) {+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ try {+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect('rejection' in result && result.rejection.code).toBe('io');+ } finally {+ renameSpy.mockRestore();+ }++ expect(renameTargets.some((target) => target.endsWith('.legacy-migration.json'))).toBe(true);+ expect(renameTargets.some((target) => target.endsWith(`${path.sep}hello.json`))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ // Ledger commit failed before the receipt became visible, so the install+ // transaction rolls back the final directory as well; no ghost is listed.+ expect(manager.list()).toEqual([]);+ });++ it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {+ const finalDir = path.join(rootDir, 'hello');+ const pendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');+ const realRename = fs.promises.rename;+ const realRm = fs.promises.rm;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('.legacy-migration.json')) {+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EBUSY: installed directory locked'), { code: 'EBUSY' });+ }+ return realRm(target, options);+ });+ try {+ await expect(manager.install(await makeCindy('a.cindy', goodManifest()))).resolves.toMatchObject(+ { rejection: { code: 'io' } },+ );+ } finally {+ renameSpy.mockRestore();+ rmSpy.mockRestore();+ }++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);++ const migration = await manager.migrateLegacyApprovalsOnce();+ expect(migration.migrated).toEqual([]);+ expect(migration.skipped).toContain('hello');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(finalDir)).toBe(false);+ expect(fs.existsSync(pendingPath)).toBe(false);+ });++ it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const realReaddir = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, opts: never) => {+ if (String(dir) === rootDir) {+ throw Object.assign(new Error('EACCES: install root locked'), { code: 'EACCES' });+ }+ return realReaddir(dir, opts);+ }) as never);+ try {+ await expect(manager.migrateLegacyApprovalsOnce()).rejects.toThrow(/EACCES/);+ } finally {+ spy.mockRestore();+ }+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 环境恢复后下一轮照常迁移。+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ });++ it('P0-2:恢复旁路只补给定 id,台账门对其余目录照常生效', async () => {+ // 台账已落(首轮迁移空跑一个插件)。+ await writeLegacyInstall('first', goodManifest('first'));+ await manager.migrateLegacyApprovalsOnce();+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ // 恢复流程搬入两个目录,但只把 recovered 声明为其中一个。+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ await writeLegacyInstall('planted', goodManifest('planted'));+ const out = await manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ );+ expect(out.migrated).toEqual(['recovered']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId.recovered).toBe('approved');+ expect(byId.planted).toBe('legacy-unapproved');+ });++ it.each(['manifest', 'disabled', 'trust', 'locale', 'skill'] as const)(+ '恢复 backfill 在 %s 批准投影漂移时保持 fail closed',+ async (kind) => {+ const manifest = {+ ...goodManifest('recovered'),+ icon: 'assets/icon.png',+ locales: { en: 'locales/en.json' },+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ };+ await writeLegacyInstall('recovered', manifest, {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',+ },+ });+ const expected = await recoveredProjectionOptions('recovered');+ const dir = path.join(rootDir, 'recovered');+ if (kind === 'manifest') {+ await fs.promises.writeFile(+ path.join(dir, 'ghost.json'),+ JSON.stringify({+ ...manifest,+ tools: [+ { name: 'do_thing', description: '做点事' },+ { name: 'new_thing', description: 'New privileged tool' },+ ],+ }),+ );+ } else if (kind === 'disabled') {+ await fs.promises.writeFile(path.join(dir, '.disabled'), '');+ } else if (kind === 'trust') {+ await fs.promises.writeFile(+ path.join(dir, '.cindy-trust.json'),+ JSON.stringify({+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: false,+ }),+ );+ } else if (kind === 'locale') {+ await fs.promises.writeFile(+ path.join(dir, 'locales', 'en.json'),+ JSON.stringify({ name: 'Replaced name' }),+ );+ } else {+ await fs.promises.writeFile(+ path.join(dir, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',+ );+ }++ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ },+ );++ it('keeps legacy approval backfill eligible when the optional icon cannot be read', async () => {+ await writeLegacyInstall(+ 'recovered',+ {+ ...goodManifest('recovered'),+ icon: 'assets/icon.png',+ },+ {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ },+ },+ );+ const realOpenSync = fs.openSync;+ const spy = vi+ .spyOn(fs, 'openSync')+ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {+ if (+ typeof p === 'string' &&+ p.endsWith(path.join('recovered', 'assets', 'icon.png'))+ ) {+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);+ }) as typeof fs.openSync);++ try {+ const result = await readLegacyGhostApprovalProjection(path.join(rootDir, 'recovered'), 'recovered');+ expect(result.projection.iconDataUrl).toBeUndefined();+ } finally {+ spy.mockRestore();+ }+ });++ it('恢复 backfill 不跟随被换成 junction 的插件根目录', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const expected = await recoveredProjectionOptions('recovered');+ const installedDir = path.join(rootDir, 'recovered');+ const externalDir = path.join(workDir, 'external-recovered');+ await fs.promises.rename(installedDir, externalDir);+ await fs.promises.symlink(externalDir, installedDir, 'junction');++ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json'))).toBe(false);+ });++ it('closes the recovery ledger when a queued id is already approved', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['hello'],+ }),+ );++ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['hello'],+ { expectedApprovalProjectionSha256ById: {} },+ ),+ ).resolves.toEqual({+ migrated: [],+ failed: [],+ });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'completed',+ });+ });++ it('keeps a target-only legacy recovery without a frozen projection fail closed', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));++ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ { expectedApprovalProjectionSha256ById: {} },+ ),+ ).resolves.toEqual({+ migrated: [],+ failed: ['recovered'],+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');+ await fs.promises.rm(migrationLedgerPath());+ const realOpenSync = fs.openSync;+ const openSpy = vi.spyOn(fs, 'openSync');+ openSpy.mockImplementation((target, ...args) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {+ openSpy.mockRestore();+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });+ }+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);+ });++ expect(+ await manager.backfillRecoveredLegacyGhosts(+ ['hello'],+ await recoveredProjectionOptions('hello'),+ ),+ ).toEqual({+ migrated: [],+ failed: [],+ });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });+ });++ it('persists transient recovered-legacy backfill failures in the migration work queue', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}recovered.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });++ const expected = await recoveredProjectionOptions('recovered');+ const first = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(first).toEqual({ migrated: [], failed: [] });+ const pendingLedger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(pendingLedger.state).toBe('in-progress');+ expect(pendingLedger.pendingIds).toEqual(['recovered']);++ const second = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(second.migrated).toEqual(['recovered']);+ const completedLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string; pendingIds?: string[] };+ expect(completedLedger.state).toBe('completed');+ expect(completedLedger.pendingIds).toBeUndefined();+ });++ it('persists recovered ids before the first receipt write starts', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realRename = fs.promises.rename;+ let queueSeenBeforeReceipt = false;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}recovered.json`)) {+ const ledger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string; pendingIds?: string[] };+ queueSeenBeforeReceipt =+ ledger.state === 'in-progress' && ledger.pendingIds?.includes('recovered') === true;+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });++ try {+ await manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ );+ } finally {+ renameSpy.mockRestore();+ }+ expect(queueSeenBeforeReceipt).toBe(true);+ });++ it('does not overwrite an existing recovery queue when the migration ledger is unreadable', async () => {+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });+ const originalLedger = {+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['existing'],+ };+ await fs.promises.writeFile(migrationLedgerPath(), JSON.stringify(originalLedger));+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realReadFileSync = fs.readFileSync;+ const readSpy = vi.spyOn(fs, 'readFileSync').mockImplementation((target, options) => {+ if (path.resolve(String(target)) === path.resolve(migrationLedgerPath())) {+ throw Object.assign(new Error('EIO: ledger temporarily unreadable'), { code: 'EIO' });+ }+ return realReadFileSync(target, options as never);+ });++ try {+ await expect(+ manager.backfillRecoveredLegacyGhosts(+ ['recovered'],+ await recoveredProjectionOptions('recovered'),+ ),+ ).rejects.toThrow(+ /ledger exists but is unreadable/,+ );+ } finally {+ readSpy.mockRestore();+ }+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toEqual(+ originalLedger,+ );+ });++ it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {+ await manager.install(+ await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),+ );+ await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));+ const inspected = await manager.inspectInstalledReapproval('clasher');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const result = await manager.reapproveInstalled('clasher', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('command-conflict');+ });++ it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {+ await writeLegacyInstall('brokered', {+ ...goodManifest('brokered'),+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key: 'token',+ source: 'oauth',+ oauth: { tokenBroker: 'github' },+ },+ ],+ },+ });+ const inspected = await manager.inspectInstalledReapproval('brokered');+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');+ });++ it('P1-7:重新确认的启停默认值取镜像读数,不重置用户停用偏好', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.previouslyEnabled).toBe(false);+ });++ it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const realRename = fs.promises.rename;+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ // staging→final 与 backup→final 都失败(Windows 文件锁/AV 的典型形态)。+ if (path.resolve(String(to)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EPERM: dir locked'), { code: 'EPERM' });+ }+ return realRename(from as never, to as never);+ });+ try {+ const bumped = await makeCindy('b.cindy', { ...goodManifest(), version: '1.0.1' });+ const result = await updateGhost(bumped);+ expect('rejection' in result).toBe(true);+ if (!('rejection' in result)) return;+ expect(result.rejection.code).toBe('io');+ expect(result.rejection.code === 'io' && result.rejection.rollbackFailed).toBe(true);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ spy.mockRestore();+ }+ });+});++describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {+ const pendingMarkerPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ /** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */+ const freshManager = () =>+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });++ it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {+ // install 在 rename(staging→final) 之后、写 receipt 之前崩溃:finalDir 完整、无+ // receipt、无 ledger。若不处理,迁移会把它(崩溃窗口内可能被改过 manifest)当 legacy+ // 批准掉。事务标记让恢复识别它是"未完成安装"并删除。+ await writeLegacyInstall('hello', goodManifest());+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256: 'a'.repeat(64) }),+ );++ const recovered = freshManager(); // 构造期恢复:删掉未完成安装+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ const outcome = await recovered.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual([]); // 目录已被删,迁移无对象+ });++ it('keeps a committed builtin restore successful and retries tombstone clearing from its journal', async () => {+ trustedBundledIds.add('hello');+ const clearBuiltinTombstone = vi+ .fn<(id: string) => void>()+ .mockImplementationOnce(() => {+ throw new Error('state root temporarily unavailable');+ })+ .mockImplementation(() => undefined);+ const restoringManager = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ clearBuiltinTombstone,+ });++ const installed = await restoringManager.install(+ await makeCindy('builtin-restore.cindy', goodManifest()),+ );++ expect('ghost' in installed).toBe(true);+ expect(restoringManager.list()[0]).toMatchObject({ approval: { state: 'approved' } });+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(JSON.parse(await fs.promises.readFile(pendingMarkerPath(), 'utf8'))).toMatchObject({+ kind: 'install',+ clearBuiltinTombstone: true,+ });++ const recoveredAfterClearFailure = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ clearBuiltinTombstone,+ });++ expect(clearBuiltinTombstone).toHaveBeenCalledTimes(2);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(recoveredAfterClearFailure.list()[0]).toMatchObject({+ approval: { state: 'approved' },+ });+ });++ it('install 恢复必须用 packageSha256 证明旧 receipt 属于这次安装', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ await fs.promises.rm(finalDir, { recursive: true, force: true });+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(finalDir, 'ghost.json'),+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),+ );+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'install',+ packageSha256: 'f'.repeat(64),+ }),+ );++ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });+ expect(fs.existsSync(finalDir)).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('非法 pending marker 会阻断 orphan backup 启发式,不删除待人工恢复的 backup', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-abcdef12';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: '..\\outside',+ }),+ );++ const recovered = freshManager();+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalid pending marker filename blocks orphan-backup heuristics', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ const invalidMarker = path.join(path.dirname(pendingMarkerPath()), '.pending-BAD!.json');+ await fs.promises.writeFile(invalidMarker, '{}');++ const recovered = freshManager();+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(invalidMarker)).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('pending marker JSON 为 null 时按 invalid 保留现场,不让构造期恢复崩溃', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ await fs.promises.writeFile(pendingMarkerPath(), 'null');++ const recovered = freshManager();+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('状态根 journal 扫描 EACCES 时跳过全部恢复启发式,任何现场都不动', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateRoot = path.dirname(pendingMarkerPath());+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.mkdir(stagingDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realReaddirSync = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {+ if (path.resolve(String(target)) === path.resolve(stateRoot)) {+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });+ }+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);+ }) as typeof fs.readdirSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ // 未提交 update 已先移除 final;backup 不可读时保留整笔 journal,+ // 因而此刻 final 仍缺失,等待下次可读时再由 recovery 收敛。+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(stagingDir)).toBe(true);+ });++ it('journal root unreadable blocks the whole owner even when installed ids cannot be enumerated yet', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateRoot = path.dirname(pendingMarkerPath());+ const realReaddirSync = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {+ const resolved = path.resolve(String(target));+ if (resolved === path.resolve(stateRoot) || resolved === path.resolve(rootDir)) {+ throw Object.assign(new Error('EACCES: managed root locked'), { code: 'EACCES' });+ }+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);+ }) as typeof fs.readdirSync);++ let recovered: GhostManager;+ try {+ recovered = freshManager();+ } finally {+ spy.mockRestore();+ }++ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('pending marker 读取 EACCES 时保留 marker/final/backup,不降级到 orphan cleanup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realReadFileSync = fs.readFileSync;+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(pendingMarkerPath())) {+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });+ }+ return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.readFileSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ });++ it('已提交 install 的 receipt 瞬时不可读时保留 final/receipt/journal 等待重试', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ }).packageSha256;+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256 }),+ );+ const realOpenSync = fs.openSync;+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }+ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);+ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('已提交 update 的 receipt lstat EACCES 时保留 final/backup/receipt/journal', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ }).packageSha256;+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ }),+ );+ const realOpenSync = fs.openSync;+ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }+ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);+ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('update backup lstat EACCES 时保留整笔 journal,不清 marker 继续猜恢复', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(backupDir)) {+ throw Object.assign(new Error('EACCES: backup locked'), { code: 'EACCES' });+ }+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.lstatSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('动态 owner 根切换时,首次读取会先恢复新 owner 的 pending mutation', async () => {+ const rootA = rootDir;+ const rootB = path.join(workDir, 'ghosts-b');+ const stateA = path.join(workDir, 'state-a');+ const stateB = path.join(workDir, 'state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ const backupName = '.cindy-updating-hello-abcdef12';+ const finalDir = path.join(rootB, 'hello');+ await fs.promises.mkdir(path.join(rootB, backupName), { recursive: true });+ await fs.promises.writeFile(path.join(rootB, backupName, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(rootB, backupName, 'main.js'), 'old');+ await fs.promises.mkdir(stateB, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateB, '.pending-hello.json'),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: backupName,+ }),+ );+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getLocale: () => hostLocale,+ });+ activeRoot = rootB;+ activeState = stateB;+ expect(owned.list().map((ghost) => ghost.manifest.id)).toEqual(['hello']);+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(rootB, backupName))).toBe(false);+ });++ it('排队中的 mutation 在 owner 代际变化后拒绝执行', async () => {+ const rootA = rootDir;+ const rootB = path.join(workDir, 'ghosts-b');+ const stateA = path.join(workDir, 'state-a');+ const stateB = path.join(workDir, 'state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ let ownerGeneration = 0;+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getOwnerContextKey: () => `owner:${ownerGeneration}`,+ getLocale: () => hostLocale,+ });++ let markStarted!: () => void;+ let releaseFirst!: () => void;+ const started = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ const first = owned.runExclusiveMutation(async () => {+ markStarted();+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ });+ await started;++ const second = owned.runExclusiveMutation(async () => {+ await fs.promises.mkdir(activeRoot, { recursive: true });+ await fs.promises.writeFile(path.join(activeRoot, 'queued-write'), 'must not run');+ });+ const rejected = expect(second).rejects.toThrow(/owner context changed/);+ activeRoot = rootB;+ activeState = stateB;+ ownerGeneration += 1;+ releaseFirst();++ await first;+ await rejected;+ expect(fs.existsSync(path.join(rootA, 'queued-write'))).toBe(false);+ expect(fs.existsSync(path.join(rootB, 'queued-write'))).toBe(false);+ });++ it('执行中的独占 mutation 钉住 owner 内容根与状态根,不把后半段写进新 owner', async () => {+ const rootA = path.join(workDir, 'owned-a');+ const rootB = path.join(workDir, 'owned-b');+ const stateA = path.join(workDir, 'owned-state-a');+ const stateB = path.join(workDir, 'owned-state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ let ownerGeneration = 0;+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getOwnerContextKey: () => `owner:${ownerGeneration}`,+ getLocale: () => hostLocale,+ });+ await owned.install(await makeCindy('owned.cindy', goodManifest()));+ await fs.promises.mkdir(path.join(rootB, 'hello'), { recursive: true });+ await fs.promises.writeFile(path.join(rootB, 'hello', 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(rootB, 'hello', 'main.js'), 'owner-b');++ await owned.runExclusiveMutation(async (mutation) => {+ activeRoot = rootB;+ activeState = stateB;+ ownerGeneration += 1;+ expect(await mutation.uninstall('hello', { notify: false })).toEqual({ ok: true });+ });++ expect(fs.existsSync(path.join(rootA, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(stateA, 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(rootB, 'hello', 'main.js'))).toBe(true);+ expect(owned.list().find((ghost) => ghost.manifest.id === 'hello')?.approval.state).toBe(+ 'legacy-unapproved',+ );+ });++ it('未提交的更新(新字节+旧 receipt+update 标记)回滚到 backup,不固化成按旧批准跑新代码', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-abcdef12';++ // 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,+ // receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir);+ await fs.promises.writeFile(+ path.join(finalDir, 'ghost.json'),+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),+ );+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: backupName,+ }),+ );++ freshManager(); // 构造期恢复:未提交 → 回滚到 backup+ const restored = JSON.parse(await fs.promises.readFile(path.join(finalDir, 'ghost.json'), 'utf8'));+ expect(restored.version).toBe('1.0.0'); // 旧字节搬回+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ // receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);+ });++ it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ revision: string;+ };+ const backupName = '.cindy-updating-hello-abcdef34';+ await fs.promises.mkdir(path.join(rootDir, backupName));+ await fs.promises.writeFile(path.join(rootDir, backupName, 'stale.txt'), 'old');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: committedReceipt.packageSha256,+ receiptRevision: committedReceipt.revision,+ backupDirName: backupName,+ phase: 'published',+ }),+ );++ freshManager();+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false); // 陈旧 backup 回收+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true); // 新版保留+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(manager.list()[0].approval.state).toBe('approved');+ });++ it('same-hash backed-up update restores the only backup instead of deleting it', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');+ const receipt = JSON.parse(receiptBefore) as { packageSha256: string };+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-acde0011';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: receipt.packageSha256,+ oldPackageSha256: receipt.packageSha256,+ receiptRevision: '11111111-1111-4111-8111-111111111111',+ backupDirName: backupName,+ phase: 'backed-up',+ }),+ );++ freshManager();+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);+ });++ it('same-hash backed-up update rolls back a final whose receipt revision is still old', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ };+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-acde0022';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir);+ await fs.promises.writeFile(path.join(finalDir, 'new.txt'), 'uncommitted');+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: receipt.packageSha256,+ oldPackageSha256: receipt.packageSha256,+ receiptRevision: '22222222-2222-4222-8222-222222222222',+ backupDirName: backupName,+ phase: 'backed-up',+ }),+ );++ freshManager();+ expect(fs.existsSync(path.join(finalDir, 'new.txt'))).toBe(false);+ expect(fs.existsSync(path.join(finalDir, 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('legacy install marker with an old same-hash receipt and no final stays isolated', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ };+ await fs.promises.rm(path.join(rootDir, 'hello'), { recursive: true, force: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'install',+ packageSha256: receipt.packageSha256,+ }),+ );++ freshManager();+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(manager.list()).toEqual([]);+ });++ it('卸载先撤批准再删目录:删目录失败时不留"孤立 approved receipt + 目录在"(防借尸还魂)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect(manager.list()[0].approval.state).toBe('approved');+ // 让内容目录的 rm 失败(模拟句柄占用),但放行 receipt/快照的 rm。+ const realRm = fs.promises.rm;+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation((async (p: fs.PathLike, ...rest: unknown[]) => {+ if (String(p) === path.join(rootDir, 'hello')) {+ rmSpy.mockRestore();+ const err = new Error('EBUSY: resource busy') as NodeJS.ErrnoException;+ err.code = 'EBUSY';+ throw err;+ }+ return (realRm as (...a: unknown[]) => Promise<void>)(p, ...rest);+ }) as typeof fs.promises.rm);++ const res = await manager.uninstall('hello');+ await expectRejection(res, 'io');+ // 关键:撤批准在删目录之前 —— receipt 已没了,目录还在但 fail closed(list 报+ // legacy-unapproved),不会被这份 receipt 授权。孤立标记留给启动恢复收尾。+ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('卸载崩在撤批准之后、删目录之前:恢复据 uninstall 标记删净残留目录', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 模拟崩溃现场:receipt 已撤(revoke 先行),目录还在,uninstall 标记在。+ await fs.promises.rm(receiptPath(), { force: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),+ );+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);++ freshManager(); // 构造期恢复+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('卸载崩在撤批准之前:恢复据 uninstall 标记把 receipt 与目录都删净', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 崩在写标记之后、撤批准之前:receipt 与目录都还在。+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),+ );+ expect(fs.existsSync(receiptPath())).toBe(true);++ freshManager();+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ await fs.promises.writeFile(path.join(rootDir, 'foo'), 'not a dir');+ const result = await manager.setEnabled('foo', false);+ await expectRejection(result, 'not-installed');+ });++ it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const dir = path.join(rootDir, 'hello');+ const outside = path.join(workDir, 'outside-target');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.rm(dir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 无 symlink 权限(Windows 未开发者模式):生产守卫仍由 classify 钉死。+ }+ const result = await manager.setEnabled('hello', false);+ await expectRejection(result, 'not-installed');+ // 关键:没有往 junction 目标(安装根之外)写 .disabled。+ expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);+ });+});++describe('GhostManager · update pre-rename recovery', () => {+ it('marker 落盘但尚未 rename 时保留旧 final 与 receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');+ await fs.promises.mkdir(stagingDir, { recursive: true });+ const stateReceiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const statePendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');+ const receipt = JSON.parse(await fs.promises.readFile(stateReceiptPath, 'utf8')) as {+ packageSha256?: string;+ };+ await fs.promises.writeFile(+ statePendingPath,+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: '.cindy-updating-hello-deadbeef',+ phase: 'prepared',+ oldPackageSha256: receipt.packageSha256,+ }),+ );++ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(stateReceiptPath)).toBe(true);+ expect(fs.existsSync(statePendingPath)).toBe(false);+ expect(fs.existsSync(stagingDir)).toBe(false);+ });+});++describe('GhostManager · install', () => {+ it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {+ const manifest = {+ ...goodManifest(),+ name: 'Base name',+ description: 'Base description',+ locales: {+ en: 'locales/en.json',+ 'zh-CN': 'locales/zh-CN.json',+ },+ };- const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({- name,- description,- tools: { do_thing: { description: toolDescription } },- });++ const locale = (name: string, description: string, toolDescription: string) =>++ JSON.stringify({++ name,++ description,++ tools: { do_thing: { description: toolDescription } },++ });+ const cindy = await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': locale('English name', 'English description', 'English tool'),+ 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),+ });+ const result = await manager.install(cindy);+ expect(result).toMatchObject({+ ghost: {+ manifest: {+ name: '中文名称',+ description: '中文说明',+ resolvedLocale: 'zh-CN',+ tools: [{ name: 'do_thing', description: '中文工具' }],+ },+ },+ });++ hostLocale = 'ja';+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'English name',+ description: 'English description',+ resolvedLocale: 'ja',+ tools: [{ name: 'do_thing', description: 'English tool' }],+ });+ hostLocale = 'fr-FR';+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'English name',+ resolvedLocale: 'en',+ });+ });++ it('installed locale symlinks cannot replace the Host-approved locale snapshot', async () => {+ hostLocale = 'en';+ const manifest = {+ ...goodManifest(),+ name: 'Base name',+ locales: { en: 'locales/en.json' },+ };- const locale = (name: string) => JSON.stringify({- name,- tools: { do_thing: { description: 'Localized tool' } },- });++ const locale = (name: string) =>++ JSON.stringify({++ name,++ tools: { do_thing: { description: 'Localized tool' } },++ });+ const cindy = await makeCindy('localized-symlink.cindy', manifest, {+ 'locales/en.json': locale('Packaged name'),+ });+ await manager.install(cindy);+ const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');+ const outsidePath = path.join(workDir, 'outside-locale.json');+ await fs.promises.writeFile(outsidePath, locale('Outside name'));+ await fs.promises.rm(localePath);+ try {+ await fs.promises.symlink(outsidePath, localePath, 'file');+ } catch {+ return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。+ }++ expect(manager.list()[0].manifest).toMatchObject({+ name: 'Packaged name',+ resolvedLocale: 'en',+ tools: [{ name: 'do_thing', description: 'Localized tool' }],+ });++ const localesDir = path.dirname(localePath);+ const outsideLocalesDir = path.join(workDir, 'outside-locales');+ await fs.promises.rm(localesDir, { recursive: true, force: true });+ await fs.promises.mkdir(outsideLocalesDir);- await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));++ await fs.promises.writeFile(++ path.join(outsideLocalesDir, 'en.json'),++ locale('Outside parent name'),++ );+ await fs.promises.symlink(+ outsideLocalesDir,+ localesDir,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'Packaged name',+ resolvedLocale: 'en',+ });+ });++ it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {+ const manifest = {+ ...goodManifest(),+ locales: { en: 'locales/en.json' },+ };+ const missing = await makeCindy('locale-missing.cindy', manifest);+ await expectRejection(await manager.install(missing), 'file-invalid');++ const invalid = await makeCindy('locale-invalid.cindy', manifest, {+ 'locales/en.json': '{ nope',+ });+ await expectRejection(await manager.install(invalid), 'file-invalid');++ const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),+ });+ await expectRejection(await manager.install(unknownTool), 'file-invalid');++ // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。+ hostLocale = 'en';+ const partial = await makeCindy('locale-partial.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'English partial' }),+ });+ expect(await manager.install(partial)).toMatchObject({+ ghost: {+ manifest: {+ name: 'English partial',+ resolvedLocale: 'en',+ tools: [{ name: 'do_thing', description: '做点事' }],+ },+ },+ });++ const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {+ 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),+ });+ await expectRejection(await manager.install(aliasedManifest), 'file-invalid');+ });++ it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {+ const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ const { ghost } = result as { ghost: InstalledGhost };+ expect(ghost.manifest.id).toBe('hello');+ expect(ghost.dir).toBe(path.join(rootDir, 'hello'));+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);+ });++ it('returns the quarantined projection when install journal cleanup fails', async () => {+ const store = (+ manager as unknown as {+ receiptStore: { clearPendingMutation(id: string): Promise<void> };+ }+ ).receiptStore;+ const clearSpy = vi+ .spyOn(store, 'clearPendingMutation')+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));+ let result: Awaited<ReturnType<GhostManager['install']>>;+ try {+ result = await manager.install(await makeCindy('valid.cindy', goodManifest()));+ } finally {+ clearSpy.mockRestore();+ }+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed install projection');+ expect(result.ghost).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({ approval: { state: 'approved' } });+ });++ it('本地包仅自报 cindy-github 不会获得官方 trust;Host override 才能写官方 receipt', async () => {+ const local = await makeCindy('github-local.cindy', goodManifest('cindy-github'));+ const localResult = await manager.install(local);+ expect(localResult).toMatchObject({ ghost: { trust: { level: 'unverified' } } });+ await fs.promises.rm(path.join(rootDir, 'cindy-github'), { recursive: true, force: true });++ const officialResult = await manager.install(local, { trustOverride: 'cindy-official' });+ expect(officialResult).toMatchObject({ ghost: { trust: { level: 'cindy-official' } } });+ const receipt = JSON.parse(+ await fs.promises.readFile(path.join(rootDir, 'cindy-github', '.cindy-trust.json'), 'utf8'),+ ) as { level?: unknown };+ expect(receipt.level).toBe('cindy-official');+ expect(receipt).toMatchObject(CINDY_OFFICIAL_GHOST_TRUST);+ expect(manager.list()[0].trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ });++ it('可变 trust 镜像损坏不会覆盖有效的官方 Host receipt', async () => {+ const local = await makeCindy('github-incomplete-receipt.cindy', goodManifest('cindy-github'));+ await manager.install(local, { trustOverride: 'cindy-official' });+ const metadataPath = path.join(rootDir, 'cindy-github', '.cindy-trust.json');+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;+ delete metadata.publisherName;+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);++ expect(manager.list()[0]?.trust).toEqual(CINDY_OFFICIAL_GHOST_TRUST);+ });++ it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {+ const cindy = await makeCindy('at-resource.cindy', atResourceManifest());+ const installed = await manager.install(cindy);++ const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;++ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<++ string,++ unknown++ >;++ delete metadata.approvedAtResourceProvider;+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.tools).toEqual([- { name: 'do_thing', description: '做点事' },- ]);++ expect(manager.list()[0].manifest.tools).toEqual([{ name: 'do_thing', description: '做点事' }]);++ metadata.approvedAtResourceProvider = { tool: 'other_tool' };+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ });++ it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {+ const cindy = await makeCindy('hello.cindy', goodManifest());+ const result = await manager.install(cindy, { initiallyEnabled: false });+ expect('ghost' in result).toBe(true);+ expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);+ // 重新启用即撕掉标记。+ await manager.setEnabled('hello', true);+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {+ const zip = new JSZip();+ zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));+ zip.file('hello-pack/assets/a.txt', 'a');+ const out = path.join(workDir, 'wrapped.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));++ const result = await manager.install(out);+ expect('ghost' in result).toBe(true);+ // 包裹层被剥掉:内容直接落在 <root>/hello/ 下+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);+ });++ it('源文件不存在 → source-not-found', async () => {- await expectRejection(await manager.install(path.join(workDir, 'nope.cindy')), 'source-not-found');++ await expectRejection(++ await manager.install(path.join(workDir, 'nope.cindy')),++ 'source-not-found',++ );+ });++ it('不是 zip 的文件 → file-invalid', async () => {+ const bad = path.join(workDir, 'bad.cindy');+ await fs.promises.writeFile(bad, 'this is not a zip');+ await expectRejection(await manager.install(bad), 'file-invalid');+ });++ it('缺 ghost.json → file-invalid', async () => {+ const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('ghost.json 不是合法 JSON → file-invalid', async () => {+ const zip = new JSZip();+ zip.file('ghost.json', '{ not json');+ const out = path.join(workDir, 'badjson.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ await expectRejection(await manager.install(out), 'file-invalid');+ });++ it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {+ const cindy = await makeCindy('decl.cindy', {+ schemaVersion: 1,+ id: 'legacy',+ name: '老声明型',+ version: '1.0.0',+ kind: 'declaration',+ panel: { title: '静态面板', body: '一段文字' },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ const manifest = {+ ...goodManifest(),+ slots: ['node'],+ tools: undefined,+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ };+ const cindy = await makeCindy('missing-node.cindy', manifest);+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(+ '包不能自带主机保留文件 %s',+ async (reservedFile) => {+ const cindy = await makeCindy('reserved.cindy', goodManifest(), {+ [reservedFile]: '{}',+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: {+ code: 'file-invalid',+ reason: expect.stringContaining('主机保留文件'),+ },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ },+ );++ it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {+ const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装+ expect(onChanged).not.toHaveBeenCalled();+ });++ // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。+ it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(+ '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',+ async (entryName) => {+ // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字+ // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。+ const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });+ const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {+ [entryName]: evilManifest,+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(onChanged).not.toHaveBeenCalled();+ },+ );++ it('重复装入同 id → already-installed,原安装不受影响', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();- await expectRejection(await manager.install(await makeCindy('b.cindy', goodManifest())), 'already-installed');++ await expectRejection(++ await manager.install(await makeCindy('b.cindy', goodManifest())),++ 'already-installed',++ );+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {+ await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),+ 'command-conflict',+ );+ expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘- const ok = await manager.install(await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')));++ const ok = await manager.install(++ await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),++ );+ expect('ghost' in ok).toBe(true);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ });+});++describe('GhostManager · uninstall', () => {+ it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello');+ expect('ok' in result).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0]).toEqual([]);+ });++ it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello', { notify: false });++ expect('ok' in result).toBe(true);+ expect(manager.list()).toEqual([]);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('persists builtin tombstone intent before removing approval or installed bytes', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).toHaveBeenCalledWith('hello');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });++ it('does not turn Host reconciliation cleanup into a user builtin tombstone', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');++ await expect(+ manager.uninstall('hello', { notify: false, recordBuiltinTombstone: false }),+ ).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).not.toHaveBeenCalled();+ expect(manager.list()).toEqual([]);+ });++ it('keeps builtin uninstall journal and bytes quarantined when tombstone persistence fails', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ const error = new Error('access denied') as NodeJS.ErrnoException;+ error.code = 'EACCES';+ throw error;+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toMatchObject({+ rejection: { code: 'io' },+ });++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ manifest: { id: 'hello' },+ enabled: false,+ approval: { state: 'invalid' },+ });+ expect(+ JSON.parse(+ await fs.promises.readFile(+ path.join(workDir, 'ghosts-install-state', '.pending-hello.json'),+ 'utf8',+ ),+ ),+ ).toMatchObject({ kind: 'uninstall', builtinTombstone: true });+ });++ it('recovers a crashed builtin uninstall by persisting its tombstone before deletion', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateDir, '.pending-hello.json'),+ `${JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'uninstall',+ builtinTombstone: true,+ })}\n`,+ );+ const recoveredTombstone = vi.fn(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ recordBuiltinTombstone: recoveredTombstone,+ });++ expect(recoveredTombstone).toHaveBeenCalledWith('hello');+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(stateDir, '.pending-hello.json'))).toBe(false);+ });++ it('卸未装的 id → not-installed', async () => {+ const result = await manager.uninstall('ghost');+ expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ });++ it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ const sibling = path.join(workDir, 'victim');+ await fs.promises.mkdir(sibling);+ for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {+ const result = await manager.uninstall(id);+ expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');+ }+ expect(fs.existsSync(sibling)).toBe(true);+ });++ it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {+ const cindy = await makeCindy('a.cindy', goodManifest());+ await manager.install(cindy);+ await manager.uninstall('hello');+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });+});++describe('GhostManager · list', () => {+ it('根目录不存在 → 空清单(不报错)', () => {+ expect(manager.list()).toEqual([]);+ });++ it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 手工捏三个坏目录+ await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));+ await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));+ await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');+ await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));+ await fs.promises.writeFile(+ path.join(rootDir, 'wrong-name', 'ghost.json'),+ JSON.stringify(goodManifest('other-id')),+ );+ // 隐藏目录(staging 残留形态)也不进清单+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });++ it('多意识按 id 排序', async () => {+ await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));+ await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ });+});++describe('GhostManager · Host approval receipt', () => {+ /** 真实 copyFile 引用:mock 复制行为的用例要靠它放行非目标文件。 */+ const realCopyFile = fs.promises.copyFile;+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ const writeBundledSource = async (+ manifest: InstalledGhost['manifest'],+ files: Record<string, string> = { 'main.js': '// bundled seed' },+ ): Promise<{ sourceDir: string }> => {+ const sourceDir = path.join(workDir, 'bundled-seeds', manifest.id);+ await fs.promises.rm(sourceDir, { recursive: true, force: true });+ await fs.promises.mkdir(sourceDir, { recursive: true });+ trustedBundledIds.add(manifest.id);+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(manifest));+ for (const [relativePath, content] of Object.entries(files)) {+ const target = path.join(sourceDir, relativePath);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ await fs.promises.writeFile(target, content);+ }+ return { sourceDir };+ };++ /** 带 skill 槽的清单 + 配套包内文件(技能快照相关用例共用)。 */+ const skillManifest = (): Record<string, unknown> => ({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ });+ const skillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('keeps manifest, enabled state, and trust independent from mutable install files', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const before = manager.list()[0];+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(path.dirname(receiptPath())).not.toBe(rootDir);++ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ version: '99.0.0',+ slots: ['node'],+ node: { entry: 'evil.cjs', protocol: 'json-rpc-stdio' },+ }),+ );+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ }),+ );++ const after = manager.list()[0];+ expect(after.manifest).toEqual(before.manifest);+ // 启停是**非对称**的例外:`.disabled` 镜像允许把启停态往下拉(停用必须永远能+ // 成功,状态根不可写时镜像是唯一落点),但 manifest/trust/批准态不受安装目录+ // 影响,镜像也不能把插件往"启用"方向翻。+ expect(after.enabled).toBe(false);+ expect(after.trust).toEqual(before.trust);+ expect(after.approval.state).toBe('approved');++ // 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('fails legacy and corrupt receipts closed until a fully reviewed update replaces them', async () => {+ const legacyDir = path.join(rootDir, 'hello');+ await fs.promises.mkdir(legacyDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(legacyDir, 'ghost.json'),+ JSON.stringify(goodManifest()),+ );+ await fs.promises.writeFile(path.join(legacyDir, 'main.js'), '// legacy');++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ const reviewed = await updateGhost(+ await makeCindy('reviewed.cindy', { ...goodManifest(), version: '2.0.0' }),+ );+ expect(reviewed).toMatchObject({+ ghost: {+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ },+ });++ await fs.promises.writeFile(receiptPath(), '{ broken');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('rejects an update when the approved revision changed after review', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const staleApproval = ghostInstallApprovalToken(manager.list()[0].approval);+ const v2 = await makeCindy('v2.cindy', {+ ...goodManifest(),+ version: '2.0.0',+ });+ const first = await manager.update(v2, {+ expectedInstalledApproval: staleApproval,+ });+ expect(first).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });++ const v3 = await makeCindy('v3.cindy', {+ ...goodManifest(),+ version: '3.0.0',+ });+ await expectRejection(+ await manager.update(v3, {+ expectedInstalledApproval: staleApproval,+ }),+ 'state-changed',+ );+ expect(manager.list()[0].manifest.version).toBe('2.0.0');+ });++ it('quarantines an update while the new directory is published but receipt is not committed', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const originalRename = fs.promises.rename;+ let releasePublish!: () => void;+ let publishStarted!: () => void;+ const publishStartedPromise = new Promise<void>((resolve) => {+ publishStarted = resolve;+ });+ const publishGate = new Promise<void>((resolve) => {+ releasePublish = resolve;+ });+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(from).includes('.cindy-installing-hello-')) {+ const result = await originalRename(from, to);+ publishStarted();+ await publishGate;+ return result;+ }+ return originalRename(from, to);+ });+ try {+ const updatePromise = manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ await publishStartedPromise;+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ releasePublish();+ expect('ghost' in (await updatePromise)).toBe(true);+ } finally {+ releasePublish();+ renameSpy.mockRestore();+ }+ });++ it('keeps a committed update quarantined until its durable journal is cleared', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const store = (+ manager as unknown as {+ receiptStore: { clearPendingMutation(id: string): Promise<void> };+ }+ ).receiptStore;+ const clearSpy = vi+ .spyOn(store, 'clearPendingMutation')+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));+ try {+ const result = await manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed update projection');+ expect(result.ghost).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(manager.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ clearSpy.mockRestore();+ }++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('removes the receipt and approved skill snapshots on uninstall', async () => {+ const manifest = {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ };+ const cindy = await makeCindy('skill.cindy', manifest, {+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ await manager.install(cindy);+ const listed = manager.list()[0];+ expect(listed.approvedSkillRoot).toBeTruthy();+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(true);++ await manager.uninstall('skilled');+ expect(fs.existsSync(receiptPath('skilled'))).toBe(false);+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(false);+ });++ it('keeps an uninstall journal when receipt cleanup fails after content removal', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ await fs.promises.rm(receiptPath());+ await fs.promises.mkdir(receiptPath());+ await fs.promises.writeFile(path.join(receiptPath(), 'blocked'), 'x');++ const result = await manager.uninstall('hello');++ expect(result).toEqual({ ok: true });+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(+ true,+ );+ await fs.promises.rm(receiptPath(), { recursive: true, force: true });+ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('keeps disabling possible when the approved skill snapshot is gone, and rebuilds it on enable', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 外部把快照删掉:停用是安全方向,必须仍然成功,不能把插件卡在既不能用也不能关。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });++ // 重新启用时从当前安装目录重建快照,不需要用户重新走一次确认。+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ const healed = manager.list()[0];+ expect(healed.enabled).toBe(true);+ expect(healed.approvedSkillRoot).toBe(snapshotRoot);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('refuses to rebuild an enable-time snapshot from install bytes that drifted from the approved manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 安装目录里的 SKILL.md 与批准 manifest 声明的 description 不再一致,快照也没了:+ // 停用照样成功(安全方向),但重建快照必须拒——否则启用就等于批准一份用户+ // 没看过的技能指令。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Silently widened skill\n---\n\nTampered instructions\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('prunes skill snapshots left behind by superseded approval revisions', async () => {+ await manager.install(await makeCindy('skill-v1.cindy', skillManifest(), skillFiles()));+ const firstSnapshot = manager.list()[0].approvedSkillRoot!;+ const snapshotParent = path.dirname(firstSnapshot);++ await updateGhost(+ await makeCindy(+ 'skill-v2.cindy',+ { ...skillManifest(), version: '2.0.0' },+ skillFiles(),+ ),+ 'skilled',+ );+ const secondSnapshot = manager.list()[0].approvedSkillRoot!;++ expect(secondSnapshot).not.toBe(firstSnapshot);+ expect(await fs.promises.readdir(snapshotParent)).toEqual([+ path.basename(secondSnapshot),+ ]);+ });++ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');+ // 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。+ const external = path.join(workDir, 'external-data');+ await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });+ await fs.promises.writeFile(path.join(external, 'stale-revision', 'sentinel.txt'), 'keep');+ // 把 `<id>` 父段整个换成指向外部目录的 junction(同权限进程可做到)。+ await fs.promises.rm(idDir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 环境建不了链接则跳过;判定逻辑平台同源。+ }++ // 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把+ // 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的+ // "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。+ await manager.setEnabled('skilled', false);+ expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);+ // 外部目录里也不应多出任何被"发布"进去的快照字节。+ expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);+ });++ it('holds the install-time SKILL.md size ceiling when rebuilding from mutable install bytes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const installedSkillMd = path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md');+ // 快照缺失时取字节的来源是可变安装目录。这里塞的 SKILL.md frontmatter 与批准+ // manifest 完全一致(躲过一致性校验),只是正文超过装入侧上限 —— 重建必须照样拒,+ // 否则启用这条路会批准一份装入/更新永远不会接受的超大技能指令,而且要先整份+ // 读进内存。+ await fs.promises.writeFile(+ installedSkillMd,+ `---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n${'padding '.repeat(+ GHOST_SKILL_MD_MAX_BYTES / 4,+ )}`,+ );+ expect((await fs.promises.lstat(installedSkillMd)).size).toBeGreaterThan(+ GHOST_SKILL_MD_MAX_BYTES,+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when only the SKILL.md body drifted', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,+ // 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when a helper file was added to the skill directory', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),+ '#!/bin/sh\necho injected\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to follow a link planted inside the skill directory when rebuilding', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const outside = path.join(workDir, 'outside-skill');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'bytes from outside the skill dir');+ // Windows junction 不需要管理员权限即可创建,是本平台成本最低的一条"把技能目录+ // 之外的字节拉进批准快照"的路子。判据不能建立在 Dirent 类型位的实现细节上,+ // 所以这条用例把行为钉住:planted link 一律拒,快照不落地。+ try {+ await fs.promises.symlink(+ outside,+ path.join(rootDir, 'skilled', 'skills', 'demo', 'linked'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。+ }+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ // 状态根里不该出现任何来自技能目录之外的字节(含崩溃残留的 .tmp)。+ const stateRoot = manager.approvalStateRoot();+ const leaked: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const child = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(child);+ else if (entry.name === 'leak.txt') leaked.push(child);+ }+ };+ if (fs.existsSync(stateRoot)) walk(stateRoot);+ expect(leaked).toEqual([]);+ });++ it('rejects bytes swapped after the hash check but before the snapshot copy finishes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 先停用、再删快照:停用本身会把快照重建回来(字节没动、校验放行),顺序颠倒+ // 会让后面的启用走"快照已存在"的早退路径,根本不经过复制。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 模拟同权限本机进程抢在复制这一刻换掉源字节:复制动作落到 temp 的是被改写的+ // 内容,而源目录事后看起来仍然"没问题"。所以校验必须落在**已经复制到 temp 的+ // 那份字节**上;若校验读的是源目录,这里就会放行一份没人确认过的技能指令。+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, tampered, 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ try {+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ } finally {+ spy.mockRestore();+ }+ expect(swapped).toBe(1); // 确认这一轮真的走到了复制+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('applies the SKILL.md size ceiling to the bytes that actually landed in the snapshot', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 源目录看起来一切正常(预检放行),复制这一刻落到 temp 的却是超大文件。上限必须+ // 作用在这份字节上,而不是只作用在预检读到的那份 —— 预检不是安全边界。+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, 'x'.repeat(GHOST_SKILL_MD_MAX_BYTES + 1), 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ let result: Awaited<ReturnType<GhostManager['setEnabled']>>;+ try {+ result = await manager.setEnabled('skilled', true);+ } finally {+ spy.mockRestore();+ }+ await expectRejection(result, 'io');+ // 断言到 reason 才能区分校验顺序:上限先跑报"exceeds N bytes",指纹先跑报+ // "no longer matches..."。只比 code 的话两种顺序都是 io,用例就退化成+ // 行为钉住、测不出重排。+ expect((result as { rejection: { reason: string } }).rejection.reason).toMatch(+ /exceeds \d+ bytes/,+ );+ expect(swapped).toBe(1);+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('keeps an install unusable when a stale approval cannot be revoked', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ // 撤销失败(状态根不可写等,与写批准失败同一成因)不得退回"继续拿旧批准跑":+ // removeInstallApproval 的契约是返回后一定不再被授权运行。+ const spy = vi+ .spyOn(fs.promises, 'rm')+ .mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ try {+ await manager.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('does not trust an already-present snapshot whose bytes were rewritten in place', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const snapshotSkillMd = path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md');+ // 快照就位后被就地改写(状态根没有写保护)。主 Agent 是顺着共享链接持续读它的,+ // 所以"快照已存在"不能当成"仍是被批准的那份字节"直接早退信任。+ await fs.promises.writeFile(+ snapshotSkillMd,+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 安装目录里的字节没动过 → 删掉坏快照后能按批准字节重建,自愈。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(await fs.promises.readFile(snapshotSkillMd, 'utf8')).toContain('Approved instructions');+ });++ it('refuses to keep a rewritten snapshot when the installed bytes drifted too', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ // 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。+ await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ tampered,+ );++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 字节指纹校验不能把合法的自愈场景一起堵死:外部清理误删快照、内容没动过。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('bundled unchanged approval repairs a deleted skill snapshot without toggling enabled state', async () => {+ const manifest = skillManifest();+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));+ const listed = manager.list()[0];+ const source = await writeBundledSource(listed.manifest, skillFiles());+ const snapshotRoot = listed.approvedSkillRoot!;+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(+ await manager.approveTrustedBundledInstall(listed.manifest, listed.enabled, source),+ ).toBe(true);+ expect(manager.list()[0].enabled).toBe(listed.enabled);+ const repairedSnapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(+ await fs.promises.readFile(+ path.join(repairedSnapshotRoot, 'skills', 'demo', 'SKILL.md'),+ 'utf8',+ ),+ ).toContain('Approved instructions');+ });++ it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath('skilled'), 'utf8'),+ ) as Record<string, unknown>;+ // 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。+ delete receipt.skillContentSha256;+ await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalidates a schema v1 receipt instead of trusting its legacy content digests', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ // v2 改了内容摘要 framing;旧 receipt 的摘要不能拿来继续授权,必须 fail closed。+ receipt.schemaVersion = 1;+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('revoking approval fails the install closed, and a later bundled approval heals it', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;++ // 随包对账在换入新种子字节后写批准失败时走的收敛动作:撤掉陈旧批准。+ // 撤掉之后插件必须彻底不可运行,而不是继续拿旧批准跑新代码。+ await manager.removeInstallApproval('hello');++ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ // 下一轮启动对账重新补批准即自愈,不需要用户介入。+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },+ });+ });++ it('uses the immutable bundled source directory when minting the approval receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const sourceDir = path.join(workDir, 'bundled-seeds', approvedManifest.id);+ trustedBundledIds.add(approvedManifest.id);+ await fs.promises.mkdir(sourceDir, { recursive: true });+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(approvedManifest));+ await fs.promises.writeFile(path.join(sourceDir, 'main.js'), 'immutable bundled bytes');+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'mutable bytes');++ const unsafeCall = manager.approveTrustedBundledInstall as unknown as (+ manifest: InstalledGhost['manifest'],+ markerEnabled: boolean,+ ) => Promise<boolean>;+ await expect(unsafeCall.call(manager, approvedManifest, true)).rejects.toThrow(+ /verified bundled source directory/,+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: path.join(rootDir, approvedManifest.id),+ }),+ ).rejects.toThrow(/mutable installed directory/);+ const arbitrarySourceDir = path.join(workDir, 'arbitrary-source', approvedManifest.id);+ await fs.promises.mkdir(arbitrarySourceDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(arbitrarySourceDir, 'ghost.json'),+ JSON.stringify(approvedManifest),+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: arbitrarySourceDir,+ }),+ ).rejects.toThrow(/trusted seed roster/);++ expect(+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir }),+ ).toBe(true);+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ const sourcePackageSha256 = receipt.packageSha256;+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'different mutable bytes');+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ expect(stableReceipt.packageSha256).toBe(sourcePackageSha256);+ });++ it('publishes bundled replacements through the pending journal and commits on receipt write', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const { sourceDir } = await writeBundledSource(approvedManifest, {+ 'main.js': 'immutable replacement bytes',+ });+ const stateRoot = manager.approvalStateRoot();+ const pendingPath = path.join(stateRoot, '.pending-hello.json');++ await manager.runExclusiveMutation(async (mutation) => {+ expect(await mutation.removeInstallApproval('hello')).toBe(true);+ await mutation.publishTrustedBundledSeed('hello', sourceDir, { disabled: false });+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(true);+ await mutation.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ });++ expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'main.js'), 'utf8')).toBe(+ 'immutable replacement bytes',+ );+ expect(fs.existsSync(pendingPath)).toBe(false);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('approved');});- it('不是 zip 的文件 → file-invalid', async () => {- const bad = path.join(workDir, 'bad.cindy');- await fs.promises.writeFile(bad, 'this is not a zip');- await expectRejection(await manager.install(bad), 'file-invalid');+ it('keeps a receipt-pinned disable when the .disabled mirror was lost, and rewrites the mirror', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ // 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);++ // 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式+ // 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(false);+ expect(manager.list()[0].enabled).toBe(false);+ // 镜像被补写回去:回滚到旧客户端(只认镜像文件)时仍按停用对待。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);});- it('缺 ghost.json → file-invalid', async () => {- const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });- await expectRejection(await manager.install(cindy), 'file-invalid');+ it('an old-client style .disabled marker still turns a bundled receipt off', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);++ // 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——+ // 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);});- it('ghost.json 不是合法 JSON → file-invalid', async () => {- const zip = new JSZip();- zip.file('ghost.json', '{ not json');- const out = path.join(workDir, 'badjson.cindy');- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));- await expectRejection(await manager.install(out), 'file-invalid');+ it('a bundled update keeps the receipt-pinned disable even when the marker was lost', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 随包更新那一轮走的是"建全新 receipt"分支,与稳态分支共用同一条合并规则:+ // 只堵稳态分支的话,镜像在更新 tick 之前丢失仍会静默重新启用,同一个洞换条路。+ const bumped = { ...approvedManifest, version: '1.0.1' };+ expect(+ await manager.approveTrustedBundledInstall(+ bumped,+ true,+ await writeBundledSource(bumped),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ manifest: { version: '1.0.1' },+ });+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);});- it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {- const cindy = await makeCindy('decl.cindy', {- schemaVersion: 1,- id: 'legacy',- name: '老声明型',- version: '1.0.0',- kind: 'declaration',- panel: { title: '静态面板', body: '一段文字' },+ it('refuses to mint a bundled approval for an id outside the seed roster', async () => {+ // 该入口不经用户确认就铸出批准;builtin-only 边界必须运行期强制,不能只靠+ // "唯一调用者是随包对账"这条纪律。+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: () => false,});- await expectRejection(await manager.install(cindy), 'file-invalid');+ const validated = validateGhostManifest(goodManifest());+ if (!validated.ok) throw new Error(validated.reason);+ await expect(+ guarded.approveTrustedBundledInstall(+ validated.manifest,+ true,+ await writeBundledSource(validated.manifest),+ ),+ ).rejects.toThrow(/种子清单/);});- it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ it('invalidates a receipt whose locale snapshot keys no longer match the manifest', async () => {+ hostLocale = 'en';const manifest = {...goodManifest(),- slots: ['node'],- tools: undefined,- node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ locales: { en: 'locales/en.json' },};- const cindy = await makeCindy('missing-node.cindy', manifest);- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ await manager.install(+ await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'Approved English name' }),+ }),+ );+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ receipt.localeResources = {};+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },});- await expectRejection(await manager.install(cindy), 'file-invalid');});+});- it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(- '包不能自带主机保留文件 %s',- async (reservedFile) => {- const cindy = await makeCindy('reserved.cindy', goodManifest(), {- [reservedFile]: '{}',- });- expect(await manager.inspect(cindy)).toMatchObject({- rejection: {- code: 'file-invalid',- reason: expect.stringContaining('主机保留文件'),- },- });- await expectRejection(await manager.install(cindy), 'file-invalid');- },- );-- it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {- const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装- expect(onChanged).not.toHaveBeenCalled();+describe('GhostManager · 技能批准基线取自包投影(publish 后篡改必须拒装)', () => {+ it('staging→final 发布后、首次校验前换掉 SKILL.md → 拒装,篡改字节不成为批准事实', async () => {+ const cindy = await makeCindy('skill.cindy', {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ }, {+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ // 故障注入:staging→final 的 rename 真实执行后,立刻在 finalDir 里改写 SKILL.md+ // 正文 —— 模拟"发布与首次 hash 之间"的本机进程篡改窗口。+ const realRename = fs.promises.rename;+ const finalDir = path.join(rootDir, 'skilled');+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ await realRename(from, to);+ if (String(to) === finalDir) {+ spy.mockRestore();+ await fs.promises.writeFile(+ path.join(finalDir, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ }+ });+ try {+ const result = await manager.install(cindy);+ // 修复前:指纹从被篡改的 finalDir 首读,篡改字节自洽地成为 receipt 指纹与+ // 快照,install 返回 ok。修复后:指纹来自包投影,快照对账发现字节不符 → 拒装。+ expect('rejection' in result, JSON.stringify(result)).toBe(true);+ } finally {+ spy.mockRestore();+ }+ // 拒装收尾:不留半截安装,也没有任何批准事实落盘。+ expect(manager.list()).toHaveLength(0);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'skilled.json')),+ ).toBe(false);});+});- // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。- it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(- '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',- async (entryName) => {- // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字- // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。- const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });- const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {- [entryName]: evilManifest,- });- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },- });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(onChanged).not.toHaveBeenCalled();- },- );-- it('重复装入同 id → already-installed,原安装不受影响', async () => {+describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {+ it('final 缺位 + 唯一 backup → 下次启动自动搬回,插件不凭空消失', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();- await expectRejection(- await manager.install(await makeCindy('b.cindy', goodManifest())),- 'already-installed',+ // 模拟崩溃现场:final→backup 已发生,staging→final 没来得及。+ await fs.promises.rename(+ path.join(rootDir, 'hello'),+ path.join(rootDir, '.cindy-updating-hello-abcdef01'),);- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(onChanged).not.toHaveBeenCalled();- });+ // 崩溃前 list() 视角:插件消失(点目录被跳过)—— 这正是要修的现场。+ expect(manager.list()).toHaveLength(0);- it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {- await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));- await expectRejection(- await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),- 'command-conflict',- );- expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘- const ok = await manager.install(- await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')),- );- expect('ghost' in ok).toBe(true);- expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ // "重启":新建 manager,构造期恢复扫描搬回。receipt 从未更新过,恢复后+ // receipt 与内容完全一致,等价于那次更新从未发生。+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(restarted.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);});-});-describe('GhostManager · uninstall', () => {- it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ it('final 是普通文件时不删除唯一 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.writeFile(finalDir, 'unexpected file');- const result = await manager.uninstall('hello');- expect('ok' in result).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(manager.list()).toEqual([]);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0]).toEqual([]);+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });++ expect((await fs.promises.lstat(finalDir)).isFile()).toBe(true);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);});- it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ it('final 是 junction/链接时不删除唯一 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();-- const result = await manager.uninstall('hello', { notify: false });+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ const outsideDir = path.join(workDir, 'outside-final-target');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(outsideDir, { recursive: true });+ try {+ await fs.promises.symlink(outsideDir, finalDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // Windows 环境未授予建链接权限时跳过;生产判据仍由 lstat 钉住。+ }- expect('ok' in result).toBe(true);- expect(manager.list()).toEqual([]);- expect(onChanged).not.toHaveBeenCalled();- });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });- it('卸未装的 id → not-installed', async () => {- const result = await manager.uninstall('ghost');- expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ expect((await fs.promises.lstat(finalDir)).isSymbolicLink()).toBe(true);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);});- it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {- await fs.promises.mkdir(rootDir, { recursive: true });- const sibling = path.join(workDir, 'victim');- await fs.promises.mkdir(sibling);- for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {- const result = await manager.uninstall(id);- expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');+ it('final lstat EACCES 时不删除唯一 backup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ await fs.promises.rename(finalDir, backupDir);+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EACCES: final path locked'), { code: 'EACCES' });+ }+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.lstatSync);+ try {+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ } finally {+ spy.mockRestore();}- expect(fs.existsSync(sibling)).toBe(true);- });- it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {- const cindy = await makeCindy('a.cindy', goodManifest());- await manager.install(cindy);- await manager.uninstall('hello');- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);+ expect(fs.existsSync(finalDir)).toBe(false);});-});-describe('GhostManager · list', () => {- it('根目录不存在 → 空清单(不报错)', () => {- expect(manager.list()).toEqual([]);+ it('final 在位的陈旧 backup 与 staging 残留 → 回收;同 id 多个 backup 不猜、原样保留', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-abcdef01'), { recursive: true });+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-hello-deadbeef'), { recursive: true });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, '.cindy-installing-hello-deadbeef'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);++ // 多 backup 且 final 缺位:不猜哪份是对的,原样保留等人工处理。+ await fs.promises.rename(path.join(rootDir, 'hello'), path.join(rootDir, '.cindy-updating-hello-11111111'));+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-22222222'), { recursive: true });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-22222222'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);});- it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- // 手工捏三个坏目录- await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));- await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));- await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');- await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));- await fs.promises.writeFile(- path.join(rootDir, 'wrong-name', 'ghost.json'),- JSON.stringify(goodManifest('other-id')),+ it('id 是另一个 id 的 `-` 前缀(hello / hello-x)各留唯一 backup → 两者都搬回,不因前缀误判互相拖累(P1)', async () => {+ // 回归:siblings 统计曾用 startsWith(`.cindy-updating-${id}-`) 前缀匹配,+ // `.cindy-updating-hello-<hex>` 是 `.cindy-updating-hello-x-<hex>` 的前缀,+ // 于是处理 hello 时把 hello-x 的 backup 也算进来 → siblings 变 2 → 判"多备份+ // 留待人工" → hello 崩溃后持续消失。修复后按解析 id 精确比对,两者各自恢复。+ await manager.install(await makeCindy('a.cindy', goodManifest('hello')));+ await manager.install(await makeCindy('b.cindy', goodManifest('hello-x')));+ // 两个插件都卡在"final→backup 已发生,staging→final 未完成"的崩溃现场,+ // 且各自只有唯一 backup(合法可恢复的场景)。+ await fs.promises.rename(+ path.join(rootDir, 'hello'),+ path.join(rootDir, '.cindy-updating-hello-11111111'),+ );+ await fs.promises.rename(+ path.join(rootDir, 'hello-x'),+ path.join(rootDir, '.cindy-updating-hello-x-22222222'),);- // 隐藏目录(staging 残留形态)也不进清单- await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);- });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });- it('多意识按 id 排序', async () => {- await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));- await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));- expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ // 两者都应搬回 final,backup 清空 —— hello 不能被 hello-x 的存在拖成"消失"。+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello-x', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-x-22222222'))).toBe(false);});});diff --cc apps/desktop/src/main/cindy-brain/index.tsindex 1448d714b9,0fac6ca5b6..2db7e06288--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -606,12 -543,9 +614,10 @@@ async function retryLegacyGhostRecoveryif (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();const authorizedStatus = getLegacyGhostRecoveryStatusForActiveSession();if (!authorizedStatus.canRetry) return authorizedStatus;+ if (authorizedStatus.deferredReason === 'legacy-discovery-incomplete') return authorizedStatus;const existingGhosts = getGhostManager().list();- const existingGhostById = new Map(- existingGhosts.map((ghost) => [ghost.manifest.id, ghost]),- );+ const existingGhostById = new Map(existingGhosts.map((ghost) => [ghost.manifest.id, ghost]));const existingGhostDirs = new Map(existingGhosts.map((ghost) => [ghost.manifest.id, ghost.dir]),);@@@ -1595,10 -1284,8 +1604,9 @@@ export function getGhostCardActionDispagetGhostAgentSlot().issueUserActionToken(ghostId, sessionId),// 呼吸起点:点击成功投递即把该会话标为"意识活动中"(结束由 card-update// state / TTL 收口)。- onActivityStart: (key, sessionId) =>- getGhostSessionActivityTracker().begin(key, sessionId),+ onActivityStart: (key, sessionId) => getGhostSessionActivityTracker().begin(key, sessionId),now: () => Date.now(),+ ownerScope: ghostOwnerScope,log,});}@@@ -1643,12 -1330,15 +1651,16 @@@ export function getGhostSubscriptionGat},now: () => Date.now(),onHookFused: (ghost, ownerStamp) => {- broadcastGhostWindowPush(GHOST_HOOK_FUSED_CHANNEL, {- ghostId: ghost.manifest.id,- name: ghost.manifest.name,- }, isDataOwnerPushStamp(ownerStamp) ? ownerStamp : undefined);+ broadcastGhostWindowPush(+ GHOST_HOOK_FUSED_CHANNEL,+ {+ ghostId: ghost.manifest.id,+ name: ghost.manifest.name,+ },+ isDataOwnerPushStamp(ownerStamp) ? ownerStamp : undefined,+ );},+ ownerScope: ghostOwnerScope,log,});}diff --cc apps/desktop/src/main/cindy-media/__tests__/ingest.test.tsindex 03d1da9af6,89c55d0e88..f992451ccf--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts@@@ -21,12 -25,22 +25,21 @@@ vi.mock('electron', () => (app: { getPath: () => tmpUserData },}));+ vi.mock('../../appSessionState', () => ({+ activeOwnerScopeKey: () => OWNER_SCOPE_KEY,+ dataOwnerStorageKey: () => OWNER_KEY,+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: OWNER_ID, generation: 1 }),+ isAppSessionBoundaryPending: () => false,+ }));+const schema = await import('../../localDb/schema');+ const ledger = await import('../ledger');const ingest = await import('../ingest');+ const refCompensation = await import('../refCompensationJournal');const MIGRATION_0070 = path.resolve(__dirname, '../../../../drizzle/0070_woozy_harpoon.sql');-// eslint-disable-next-line @typescript-eslint/no-require-imports-const migration0071 = require('../../../../drizzle/scripts/0071_bright_ultron.ts') as {- run: (db: Database.Database) => void;+const { default: migration0071 } = (await import('../../../../drizzle/scripts/0071_bright_ultron')) as {+ default: { run: (db: Database.Database) => void };};const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 7, 7]);diff --cc apps/desktop/src/main/cindy-media/__tests__/ledger.test.tsindex 4bad9aa094,dedca96a42..391dca5da3--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts@@@ -19,11 -20,14 +20,13 @@@ vi.mock('electron', () => (const schema = await import('../../localDb/schema');const ledger = await import('../ledger');+ const sessionCleanup = await import('../sessionCleanup');+ const MIGRATION_0000 = path.resolve(__dirname, '../../../../drizzle/0000_init.sql');const MIGRATION_0070 = path.resolve(__dirname, '../../../../drizzle/0070_woozy_harpoon.sql');-// 0071 的加列在配套脚本里(SQL 是占位),与生产同源经 CommonJS require 加载。-// eslint-disable-next-line @typescript-eslint/no-require-imports-const migration0071 = require('../../../../drizzle/scripts/0071_bright_ultron.ts') as {- run: (db: Database.Database) => void;+// 0071 的加列在配套脚本里(SQL 是占位),与生产同源;通过 Vitest 转换 TS helper。+const { default: migration0071 } = (await import('../../../../drizzle/scripts/0071_bright_ultron')) as {+ default: { run: (db: Database.Database) => void };};const HASH_A = 'a'.repeat(64);diff --cc apps/desktop/src/main/device-link/crossProcessLock.tsindex a792021eba,2cc2d6b45a..157c5ecbe4--- a/apps/desktop/src/main/device-link/crossProcessLock.ts+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts@@@ -93,47 -57,28 +93,52 @@@ export async function withCrossProcessLopts: FileLockOptions,task: (status: LockStatus) => Promise<T>,): Promise<T> {- const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);let held = false;let reason: 'busy' | 'unavailable' = 'unavailable';- // 接管次数上限:正常最多一次(删掉陈旧锁 → 下一轮建成功)。反复"删得掉却又立刻 EEXIST"- // 说明有人在高频重建锁,那时该降级而不是继续跟它抢。+ let ownLock: PublishedLock | null = null;let takeovers = 0;+ let publishingAfterTakeover = false;+ const processIdentity = await getProcessIdentity(process.pid);+ // Do not charge the first process-identity probe against the caller's wait+ // budget. On Windows the initial CIM/WMIC lookup can take several seconds.+ const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);+ if (opts.requireProcessIdentity && !processIdentity) {+ return task({ held: false, reason: 'unavailable' });+ }+for (;;) {+ await recoverPendingOwnRecord(lockPath);+ if (await reclaimInProgress(lockPath)) {+ reason = 'busy';+ if (Date.now() >= deadline) break;+ await sleep(LOCK_RETRY_MS);+ continue;+ }try {- const handle = await fsp.open(lockPath, 'wx');- await handle- .writeFile(JSON.stringify({ pid: process.pid, startedAt: Date.now() }), 'utf8')- .catch(() => undefined);- await handle.close().catch(() => undefined);+ const publishedLock = await publishLockRecord(lockPath, processIdentity?.key ?? null);+ if (!publishedLock) throw Object.assign(new Error('lock exists'), { code: 'EEXIST' });+ const { nonce } = publishedLock;+ const [published, reclaiming] = await Promise.all([+ readLockRecord(lockPath, opts.requireProcessIdentity === true),+ reclaimInProgress(lockPath),+ ]);+ if (reclaiming || typeof published === 'string' || published.nonce !== nonce) {+ await cleanupPublishedLock(lockPath, opts.label, publishedLock);+ reason = 'busy';+ if (Date.now() >= deadline) break;+ await sleep(LOCK_RETRY_MS);+ continue;+ }+ ownLock = publishedLock;held = true;break;- } catch (error) {- if ((error as NodeJS.ErrnoException)?.code !== 'EEXIST') {+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code;+ // EEXIST = 锁被别人持着(正常竞争)。+ // EBUSY / EPERM / EACCES 在 Windows 上可能是文件刚被删除但 FS 还没完全释放,+ // 和 EEXIST 一样走重试而不是立刻判 unavailable;有 deadline 兜底不会无限等。+ if (code !== 'EEXIST' && code !== 'EBUSY' && code !== 'EPERM' && code !== 'EACCES') {+ // 锁**建不出来**(EMFILE / 目录不存在…):无从判断有没有别人在临界区。reason = 'unavailable';break;}diff --cc apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.tsindex 0000000000,32d1edb1a0..9a7d7b34d4mode 000000,100644..100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts@@@ -1,0 -1,1462 +1,1471 @@@+ import { mkdir, rm, stat, truncate, writeFile } from 'node:fs/promises';+ import path from 'node:path';++ import { afterEach, describe, expect, it, vi } from 'vitest';++ import type { IOSSimulatorCommandRunner } from '@cindy/ios-simulator-runtime';+++// The media capture defaults its owner-scope check to isAppSessionBoundaryPending(),++// which fails closed on an uncommitted owner. This suite exercises recording++// behavior, not boundary transitions; owner-changed paths are covered by tests++// that pass explicit isOwnerScopeCurrent overrides.++vi.mock('../../appSessionState.js', async (importOriginal) => {++ const actual = await importOriginal<typeof import('../../appSessionState.js')>();++ return { ...actual, isAppSessionBoundaryPending: () => false };++});+++ import { IOSSimulatorMediaCapture } from '../ios-simulator-media';++ afterEach(() => {+ vi.useRealTimers();+ });++ describe('IOSSimulatorMediaCapture', () => {+ it('captures an exact UDID into cindy-media with a session reference', async () => {+ const ingest = vi.fn(async (params) => ({+ hash: 'a'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['ref-a'],+ }));+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });+ const result = await capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ });++ expect(result.url).toMatch(/^cindy-media:\/\/blobs\//);+ expect(run).toHaveBeenCalledWith(+ 'xcrun',+ expect.arrayContaining(['simctl', 'io', 'EXACT-UDID', 'screenshot', '--type=png']),+ expect.any(Object),+ );+ expect(ingest).toHaveBeenCalledWith(+ expect.objectContaining({+ mimeType: 'image/png',+ refs: [+ expect.objectContaining({+ refKind: 'session-attachment',+ refId: 'session-a',+ originSessionId: 'session-a',+ }),+ ],+ }),+ );+ });++ it('forwards screenshot cancellation to xcrun and removes the temporary directory', async () => {+ let screenshotPath = '';+ let runnerSignal: AbortSignal | undefined;+ const run = vi.fn<IOSSimulatorCommandRunner['run']>(async (_command, args, options) => {+ screenshotPath = args.at(-1)!;+ runnerSignal = options?.signal;+ return new Promise((resolve) => {+ options?.signal?.addEventListener(+ 'abort',+ () => resolve({ stdout: '', stderr: '', exitCode: null }),+ { once: true },+ );+ });+ });+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run } });+ const controller = new AbortController();++ const screenshot = capture.captureScreenshotBytes({+ simulatorUdid: 'EXACT-UDID',+ signal: controller.signal,+ });+ await vi.waitFor(() => expect(runnerSignal).toBe(controller.signal));+ const tempRoot = path.dirname(screenshotPath);+ controller.abort(new Error('task closed'));++ await expect(screenshot).rejects.toMatchObject({ code: 'SCREENSHOT_CAPTURE_FAILED' });+ await expect(stat(tempRoot)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('invalidates screenshot ingest when its host mutation is cancelled after capture', async () => {+ let markIngestStarted: () => void = () => undefined;+ let releaseIngest: () => void = () => undefined;+ const ingestStarted = new Promise<void>((resolve) => {+ markIngestStarted = resolve;+ });+ const ingestGate = new Promise<void>((resolve) => {+ releaseIngest = resolve;+ });+ const ingest = vi.fn(async (params) => {+ markIngestStarted();+ await ingestGate;+ params.assertStillValid?.();+ return {+ hash: 'b'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'b'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['late-ref'],+ };+ });+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });+ const controller = new AbortController();++ const screenshot = capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ signal: controller.signal,+ });+ await ingestStarted;+ controller.abort(new Error('task closed'));++ await expect(screenshot).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });+ releaseIngest();+ await expect(capture.dispose()).resolves.toBeUndefined();+ });++ it('does not ingest a screenshot after its data owner changes during capture', async () => {+ let ownerScopeKey = 'owner-a';+ const ingest = vi.fn();+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));+ ownerScopeKey = 'owner-b';+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const capture = new IOSSimulatorMediaCapture({+ commandRunner: { run },+ ingest,+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerScopeCurrent: (expected) => ownerScopeKey === expected,+ });++ await expect(+ capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ expect(ingest).not.toHaveBeenCalled();+ });++ it('quiesces a screenshot before task cleanup and prevents a late session reference', async () => {+ let markCaptureStarted: () => void = () => undefined;+ let markCaptureFinished: () => void = () => undefined;+ let releaseCapture: () => void = () => undefined;+ const captureStarted = new Promise<void>((resolve) => {+ markCaptureStarted = resolve;+ });+ const captureGate = new Promise<void>((resolve) => {+ releaseCapture = resolve;+ });+ const captureFinished = new Promise<void>((resolve) => {+ markCaptureFinished = resolve;+ });+ const ingest = vi.fn();+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ markCaptureStarted();+ await captureGate;+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));+ markCaptureFinished();+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });++ const screenshot = capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ });+ await captureStarted;+ await expect(capture.discardSession('session-a')).resolves.toBeUndefined();+ await expect(screenshot).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });++ releaseCapture();+ await captureFinished;+ await Promise.resolve();+ expect(ingest).not.toHaveBeenCalled();+ });++ it('does not poison media storage while screenshot capture itself is slow', async () => {+ let releaseFirstCapture: () => void = () => undefined;+ let markFirstCaptureStarted: () => void = () => undefined;+ const firstCaptureStarted = new Promise<void>((resolve) => {+ markFirstCaptureStarted = resolve;+ });+ const firstCaptureGate = new Promise<void>((resolve) => {+ releaseFirstCapture = resolve;+ });+ let captureCount = 0;+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ captureCount += 1;+ if (captureCount === 1) {+ markFirstCaptureStarted();+ await firstCaptureGate;+ }+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, captureCount]));+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const ingest = vi.fn(async (params) => ({+ hash: 'f'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'f'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['ref-screenshot'],+ }));+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });++ vi.useFakeTimers();+ const first = capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ });+ await firstCaptureStarted;+ await vi.advanceTimersByTimeAsync(30_000);+ expect(ingest).not.toHaveBeenCalled();++ releaseFirstCapture();+ await expect(first).resolves.toMatchObject({ refIds: ['ref-screenshot'] });+ await expect(+ capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-b',+ instanceId: 'instance-b',+ source: 'user',+ }),+ ).resolves.toMatchObject({ refIds: ['ref-screenshot'] });+ expect(run).toHaveBeenCalledTimes(2);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('bounds only screenshot ingest and poisons later media when storage never settles', async () => {+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ const output = args.at(-1)!;+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));+ return { stdout: '', stderr: '', exitCode: 0 };+ });+ const ingest = vi.fn(() => new Promise<never>(() => undefined));+ const launch = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ commandRunner: { run },+ ingest,+ recordingLauncher: { launch },+ });++ vi.useFakeTimers();+ const screenshot = capture.takeScreenshot({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ source: 'agent',+ });+ const screenshotFailure = expect(screenshot).rejects.toMatchObject({+ code: 'SCREENSHOT_CAPTURE_FAILED',+ });+ await vi.waitFor(() => expect(ingest).toHaveBeenCalledOnce());+ await vi.advanceTimersByTimeAsync(30_000);++ await screenshotFailure;+ await expect(+ capture.startRecording({+ simulatorUdid: 'EXACT-UDID-2',+ sessionId: 'session-b',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ expect(launch).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('records an exact UDID and ingests the finalized MOV through cindy-media', async () => {+ const ingest = vi.fn(async (params) => ({+ hash: 'b'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'b'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['ref-video'],+ }));+ let launchArgs: readonly string[] = [];+ let resolveExit: () => void = () => undefined;+ const recordingLauncher = {+ launch: vi.fn((args: readonly string[]) => {+ launchArgs = args;+ const videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill: vi.fn(async () => {+ await writeFile(videoPath, Buffer.from('mov-bytes'));+ resolveExit();+ }),+ };+ }),+ };+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher, ingest });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'user',+ });+ const result = await capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });++ expect(launchArgs).toEqual([+ 'simctl',+ 'io',+ 'EXACT-UDID',+ 'recordVideo',+ '--codec=h264',+ expect.stringMatching(/recording\.mov$/),+ ]);+ expect(result.mimeType).toBe('video/quicktime');+ expect(ingest).toHaveBeenCalledWith(+ expect.objectContaining({+ mimeType: 'video/quicktime',+ refs: [+ expect.objectContaining({+ refKind: 'session-attachment',+ refId: 'session-a',+ originKind: 'user',+ }),+ ],+ }),+ );+ await expect(stat(path.dirname(launchArgs.at(-1)!))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('rejects an immediately exited recorder and clears its state and temp directory', async () => {+ const videoPaths: string[] = [];+ const launch = vi.fn((args: readonly string[]) => {+ videoPaths.push(args.at(-1)!);+ return {+ started: new Promise<void>(() => undefined),+ exited: Promise.resolve(),+ isAlive: () => false,+ kill: vi.fn(),+ };+ });+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });+ const input = {+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent' as const,+ };++ await expect(capture.startRecording(input)).rejects.toMatchObject({+ code: 'RECORDING_FAILED',+ });+ await expect(capture.startRecording(input)).rejects.toMatchObject({+ code: 'RECORDING_FAILED',+ });++ expect(launch).toHaveBeenCalledTimes(2);+ await Promise.all(+ videoPaths.map((videoPath) =>+ expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' }),+ ),+ );+ });++ it('does not report recording success before the first frame is processed', async () => {+ let resolveStarted: () => void = () => undefined;+ let resolveExit: () => void = () => undefined;+ let processAlive = true;+ const kill = vi.fn(() => {+ processAlive = false;+ resolveExit();+ });+ const launch = vi.fn(() => ({+ started: new Promise<void>((resolve) => {+ resolveStarted = resolve;+ }),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ isAlive: () => processAlive,+ kill,+ }));+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });+ let settled = false;+ const starting = capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ void starting.then(+ () => {+ settled = true;+ },+ () => {+ settled = true;+ },+ );+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());+ await Promise.resolve();+ expect(settled).toBe(false);++ resolveStarted();+ await expect(starting).resolves.toEqual({+ recordingId: expect.any(String),+ startedAt: expect.any(String),+ });+ await expect(capture.discardInstance('instance-a')).resolves.toBeUndefined();+ expect(kill).toHaveBeenCalledWith('SIGKILL');+ });++ it('kills and clears a recorder that never processes its first frame', async () => {+ let resolveExit: () => void = () => undefined;+ let processAlive = true;+ let videoPath = '';+ const kill = vi.fn(() => {+ processAlive = false;+ resolveExit();+ });+ const launch = vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: new Promise<void>(() => undefined),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ isAlive: () => processAlive,+ kill,+ };+ });+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });++ vi.useFakeTimers();+ const starting = capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ const failure = expect(starting).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());+ await vi.advanceTimersByTimeAsync(5_000);++ await failure;+ expect(kill).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('retries a stuck startup cleanup before launching the next recorder', async () => {+ let firstResolveExit: () => void = () => undefined;+ let firstAlive = true;+ let firstKillCount = 0;+ let secondResolveExit: () => void = () => undefined;+ let secondAlive = true;+ const firstKill = vi.fn(() => {+ firstKillCount += 1;+ if (firstKillCount < 2) return;+ firstAlive = false;+ firstResolveExit();+ });+ const secondKill = vi.fn(() => {+ secondAlive = false;+ secondResolveExit();+ });+ const launch = vi.fn(() => {+ if (launch.mock.calls.length === 1) {+ return {+ started: new Promise<void>(() => undefined),+ exited: new Promise<void>((resolve) => {+ firstResolveExit = resolve;+ }),+ isAlive: () => firstAlive,+ kill: firstKill,+ };+ }+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ secondResolveExit = resolve;+ }),+ isAlive: () => secondAlive,+ kill: secondKill,+ };+ });+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });+ const input = {+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent' as const,+ };++ vi.useFakeTimers();+ const firstStart = capture.startRecording(input);+ const firstFailure = expect(firstStart).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());+ await vi.advanceTimersByTimeAsync(5_500);+ await firstFailure;+ expect(firstKill).toHaveBeenCalledTimes(1);++ const secondStart = await capture.startRecording(input);+ expect(secondStart.recordingId).toEqual(expect.any(String));+ expect(firstKill).toHaveBeenCalledTimes(2);+ expect(launch).toHaveBeenCalledTimes(2);+ await expect(capture.discardInstance('instance-a')).resolves.toBeUndefined();+ expect(secondKill).toHaveBeenCalledWith('SIGKILL');+ expect(vi.getTimerCount()).toBe(0);+ });++ it('keeps a starting recorder visible to Host disposal', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn(() => resolveExit());+ const launch = vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: new Promise<void>(() => undefined),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ });+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });+ const starting = capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());++ const disposing = capture.dispose();++ await expect(starting).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(disposing).resolves.toBeUndefined();+ expect(kill).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('does not ingest a recording after its data owner changes during finalization', async () => {+ let ownerScopeKey = 'owner-a';+ let videoPath = '';+ let resolveExit: () => void = () => undefined;+ const ingest = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerScopeCurrent: (expected) => ownerScopeKey === expected,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill: vi.fn(async (signal: NodeJS.Signals) => {+ if (signal !== 'SIGINT') return;+ ownerScopeKey = 'owner-b';+ await writeFile(videoPath, Buffer.from('mov-bytes'));+ resolveExit();+ }),+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });++ await expect(+ capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ expect(ingest).not.toHaveBeenCalled();+ });++ it('does not launch a queued recording after its data owner changes', async () => {+ let ownerScopeKey = 'owner-a';+ let firstVideoPath = '';+ let resolveFirstExit: () => void = () => undefined;+ let markIngestStarted: () => void = () => undefined;+ let releaseIngest: () => void = () => undefined;+ const ingestStarted = new Promise<void>((resolve) => {+ markIngestStarted = resolve;+ });+ const ingestGate = new Promise<void>((resolve) => {+ releaseIngest = resolve;+ });+ const ingest = vi.fn(async (params) => {+ markIngestStarted();+ await ingestGate;+ params.assertStillValid?.();+ return {+ hash: 'c'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'c'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['ref-video'],+ };+ });+ const launch = vi.fn((args: readonly string[]) => {+ firstVideoPath ||= args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveFirstExit = resolve;+ }),+ kill: vi.fn(async (signal: NodeJS.Signals) => {+ if (signal !== 'SIGINT') return;+ await writeFile(firstVideoPath, Buffer.from('mov-bytes'));+ resolveFirstExit();+ }),+ };+ });+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerScopeCurrent: (expected) => ownerScopeKey === expected,+ recordingLauncher: { launch },+ });+ const first = await capture.startRecording({+ simulatorUdid: 'UDID-A',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ const stopping = capture.stopRecording({+ recordingId: first.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ });+ await ingestStarted;+ const queuedStart = capture.startRecording({+ simulatorUdid: 'UDID-B',+ sessionId: 'session-a',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ });++ ownerScopeKey = 'owner-b';+ releaseIngest();++ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(queuedStart).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ expect(launch).toHaveBeenCalledOnce();+ });++ it('rejects oversized recordings before buffering them in Electron Main', async () => {+ const ingest = vi.fn();+ let videoPath = '';+ let resolveExit: () => void = () => undefined;+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill: vi.fn(async () => {+ await writeFile(videoPath, Buffer.alloc(0));+ await truncate(videoPath, 128 * 1024 * 1024 + 1);+ resolveExit();+ }),+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ await expect(+ capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ expect(ingest).not.toHaveBeenCalled();+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('terminates and removes active recording state when an instance is discarded', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') resolveExit();+ });+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const discarded = capture.discardInstance('instance-a');+ await discarded;++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL']);+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(+ capture.stopRecording({+ recordingId: 'missing',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ });++ it('discards every active recording owned by one session without touching another task', async () => {+ const videoPaths: string[] = [];+ const kills: Array<ReturnType<typeof vi.fn>> = [];+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPaths.push(args.at(-1)!);+ let resolveExit: () => void = () => undefined;+ const exited = new Promise<void>((resolve) => {+ resolveExit = resolve;+ });+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') resolveExit();+ });+ kills.push(kill);+ return { started: Promise.resolve(), exited, kill };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'SESSION-A-UDID-1',+ sessionId: 'session-a',+ instanceId: 'instance-a-1',+ generation: 1,+ source: 'agent',+ });+ await capture.startRecording({+ simulatorUdid: 'SESSION-B-UDID',+ sessionId: 'session-b',+ instanceId: 'instance-b',+ generation: 1,+ source: 'user',+ });+ await capture.startRecording({+ simulatorUdid: 'SESSION-A-UDID-2',+ sessionId: 'session-a',+ instanceId: 'instance-a-2',+ generation: 1,+ source: 'user',+ });++ await capture.discardSession('session-a');++ expect(kills[0]).toHaveBeenCalledWith('SIGKILL');+ expect(kills[1]).not.toHaveBeenCalled();+ expect(kills[2]).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(videoPaths[0]!))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(path.dirname(videoPaths[1]!))).resolves.toMatchObject({+ isDirectory: expect.any(Function),+ });+ await expect(stat(path.dirname(videoPaths[2]!))).rejects.toMatchObject({ code: 'ENOENT' });++ await capture.discardSession('session-b');+ expect(kills[1]).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(videoPaths[1]!))).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('does not let another task pending ingest block session cleanup', async () => {+ let videoPath = '';+ let resolveExit: () => void = () => undefined;+ let markIngestStarted: () => void = () => undefined;+ let releaseIngest: () => void = () => undefined;+ const ingestStarted = new Promise<void>((resolve) => {+ markIngestStarted = resolve;+ });+ const ingestGate = new Promise<void>((resolve) => {+ releaseIngest = resolve;+ });+ const ingest = vi.fn(async (params) => {+ markIngestStarted();+ await ingestGate;+ params.assertStillValid?.();+ return {+ hash: 'd'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'d'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['ref-video'],+ };+ });+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill: vi.fn(async (signal: NodeJS.Signals) => {+ if (signal !== 'SIGINT') return;+ await writeFile(videoPath, Buffer.from('mov-bytes'));+ resolveExit();+ }),+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'SESSION-B-UDID',+ sessionId: 'session-b',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ });+ const stopping = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-b',+ instanceId: 'instance-b',+ generation: 1,+ });+ await ingestStarted;++ await expect(capture.discardSession('session-a')).resolves.toBeUndefined();++ releaseIngest();+ await expect(stopping).resolves.toMatchObject({ refIds: ['ref-video'] });+ });++ it('invalidates pending ingest without making session cleanup wait for it', async () => {+ let videoPath = '';+ let resolveExit: () => void = () => undefined;+ let markIngestStarted: () => void = () => undefined;+ let releaseIngest: () => void = () => undefined;+ const ingestStarted = new Promise<void>((resolve) => {+ markIngestStarted = resolve;+ });+ const ingestGate = new Promise<void>((resolve) => {+ releaseIngest = resolve;+ });+ const ingest = vi.fn(async (params) => {+ markIngestStarted();+ await ingestGate;+ params.assertStillValid?.();+ return {+ hash: 'e'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: params.buffer.length,+ url: `cindy-media://blobs/${'e'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['late-ref'],+ };+ });+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill: vi.fn(async (signal: NodeJS.Signals) => {+ if (signal !== 'SIGINT') return;+ await writeFile(videoPath, Buffer.from('mov-bytes'));+ resolveExit();+ }),+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'SESSION-A-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ const stopping = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ });+ await ingestStarted;++ const discarding = capture.discardSession('session-a');+ let cleanupSettled = false;+ void discarding.then(+ () => {+ cleanupSettled = true;+ },+ () => {+ cleanupSettled = true;+ },+ );+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await Promise.resolve();+ expect(cleanupSettled).toBe(false);++ releaseIngest();+ await expect(discarding).resolves.toBeUndefined();+ expect(ingest).toHaveBeenCalledTimes(1);+ });++ it('bounds recording ingest even when storage never settles', async () => {+ let videoPath = '';+ let resolveExit: () => void = () => undefined;+ let processAlive = true;+ const ingest = vi.fn(() => new Promise<never>(() => undefined));+ const launch = vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ isAlive: () => processAlive,+ kill: vi.fn(() => {+ processAlive = false;+ resolveExit();+ }),+ };+ });+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: { launch },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ await writeFile(videoPath, Buffer.from('mov-bytes'));++ vi.useFakeTimers();+ const stopping = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ });+ await vi.waitFor(() => expect(ingest).toHaveBeenCalledTimes(1));+ await vi.advanceTimersByTimeAsync(30_000);++ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ const cleanup = capture.discardSession('session-a');+ const cleanupFailure = expect(cleanup).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.advanceTimersByTimeAsync(30_000);+ await cleanupFailure;+ await expect(+ capture.startRecording({+ simulatorUdid: 'EXACT-UDID-2',+ sessionId: 'session-b',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ expect(launch).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('reports incomplete cleanup and retains tracking when SIGKILL is not confirmed', async () => {+ let videoPath = '';+ const kill = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>(() => undefined),+ kill,+ };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const discarded = capture.discardInstance('instance-a');+ const rejection = expect(discarded).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.advanceTimersByTimeAsync(500);+ await rejection;++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL']);+ await expect(stat(path.dirname(videoPath))).resolves.toBeDefined();++ const retry = capture.discardInstance('instance-a');+ const retryRejection = expect(retry).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.advanceTimersByTimeAsync(500);+ await retryRejection;+ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL', 'SIGKILL']);+ await rm(path.dirname(videoPath), { recursive: true, force: true });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('fails a finalized recording safely when no exit event arrives after SIGKILL', async () => {+ const ingest = vi.fn();+ let videoPath = '';+ const kill = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>(() => undefined),+ kill,+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopped = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });+ const rejection = expect(stopped).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.advanceTimersByTimeAsync(6_500);+ await rejection;++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM', 'SIGKILL']);+ expect(ingest).not.toHaveBeenCalled();+ await expect(stat(path.dirname(videoPath))).resolves.toBeDefined();+ await expect(+ capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_ALREADY_ACTIVE' });+ await rm(path.dirname(videoPath), { recursive: true, force: true });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('does not treat a leader exit as success while its recording group is alive', async () => {+ let resolveLeaderExit: () => void = () => undefined;+ let groupAlive = true;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGINT') resolveLeaderExit();+ if (signal === 'SIGKILL') groupAlive = false;+ });+ const ingest = vi.fn(async () => ({+ hash: 'c'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: 9,+ url: `cindy-media://blobs/${'c'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['ref-video'],+ }));+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveLeaderExit = resolve;+ }),+ isAlive: () => groupAlive,+ kill,+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });+ await writeFile(videoPath, Buffer.from('mov-bytes'));++ vi.useFakeTimers();+ const stopped = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });+ await vi.advanceTimersByTimeAsync(6_025);+ await expect(stopped).rejects.toMatchObject({ code: 'RECORDING_FAILED' });++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM', 'SIGKILL']);+ expect(ingest).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('closes the start gate before an in-flight recording can launch during dispose', async () => {+ const launch = vi.fn();+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });++ const starting = capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });+ const disposing = capture.dispose();++ await expect(starting).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await expect(disposing).resolves.toBeUndefined();+ expect(launch).not.toHaveBeenCalled();+ });++ it('rejects a queued recording start when session cleanup wins before registration', async () => {+ const launch = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: { launch },+ });++ const starting = capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ const discarding = capture.discardSession('session-a');++ await expect(starting).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(discarding).resolves.toBeUndefined();+ expect(launch).not.toHaveBeenCalled();+ });++ it('synchronously kills active recorders on force-exit and rejects later starts', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') resolveExit();+ });+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ capture.abortOperationsForExit();++ expect(kill).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(+ capture.startRecording({+ simulatorUdid: 'EXACT-UDID-2',+ sessionId: 'session-a',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await capture.dispose();+ });++ it('keeps a finalizing recorder visible to the force-exit path', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') resolveExit();+ });+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopped = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });+ await Promise.resolve();+ expect(kill).toHaveBeenCalledWith('SIGINT');++ capture.abortOperationsForExit();++ expect(kill).toHaveBeenCalledWith('SIGKILL');+ await expect(stopped).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('cleans active recorders before reporting a hung ingest during dispose', async () => {+ const paths = new Map<string, string>();+ const kills = new Map<string, ReturnType<typeof vi.fn>>();+ const ingest = vi.fn(() => new Promise<never>(() => undefined));+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ const instanceId = args[2] === 'UDID-A' ? 'instance-a' : 'instance-b';+ paths.set(instanceId, args.at(-1)!);+ let resolveExit: () => void = () => undefined;+ let processAlive = true;+ const kill = vi.fn(() => {+ processAlive = false;+ resolveExit();+ });+ kills.set(instanceId, kill);+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ isAlive: () => processAlive,+ kill,+ };+ }),+ },+ });+ const first = await capture.startRecording({+ simulatorUdid: 'UDID-A',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ await writeFile(paths.get('instance-a')!, Buffer.from('mov-bytes'));+ await capture.startRecording({+ simulatorUdid: 'UDID-B',+ sessionId: 'session-b',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopping = capture.stopRecording({+ recordingId: first.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ });+ await vi.waitFor(() => expect(ingest).toHaveBeenCalledTimes(1));+ const disposing = capture.dispose();+ const disposeFailure = expect(disposing).rejects.toMatchObject({ code: 'RECORDING_FAILED' });++ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await vi.advanceTimersByTimeAsync(30_000);+ await disposeFailure;++ expect(kills.get('instance-a')).toHaveBeenCalledWith('SIGKILL');+ expect(kills.get('instance-b')).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(paths.get('instance-a')!))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ await expect(stat(path.dirname(paths.get('instance-b')!))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('regular dispose immediately kills both finalizing and active recorders', async () => {+ const exits = new Map<string, () => void>();+ const kills = new Map<string, ReturnType<typeof vi.fn>>();+ const paths = new Map<string, string>();+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ const instanceId = args[2] === 'UDID-A' ? 'instance-a' : 'instance-b';+ paths.set(instanceId, args.at(-1)!);+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') exits.get(instanceId)?.();+ });+ kills.set(instanceId, kill);+ return {+ started: Promise.resolve(),+ exited: new Promise<void>((resolve) => exits.set(instanceId, resolve)),+ kill,+ };+ }),+ },+ });+ const first = await capture.startRecording({+ simulatorUdid: 'UDID-A',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ await capture.startRecording({+ simulatorUdid: 'UDID-B',+ sessionId: 'session-a',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopping = capture.stopRecording({+ recordingId: first.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ });+ await Promise.resolve();+ const disposing = capture.dispose();++ expect(kills.get('instance-a')).toHaveBeenCalledWith('SIGKILL');+ expect(kills.get('instance-b')).toHaveBeenCalledWith('SIGKILL');+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(disposing).resolves.toBeUndefined();+ await expect(stat(path.dirname(paths.get('instance-a')!))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ await expect(stat(path.dirname(paths.get('instance-b')!))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(vi.getTimerCount()).toBe(0);+ });+ });diff --cc apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.tsindex 0000000000,0f889a6599..12a5eecb0fmode 000000,100644..100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@@ -1,0 -1,7966 +1,7975 @@@+ import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises';+ import { readFileSync } from 'node:fs';+ import os from 'node:os';+ import path from 'node:path';++ import { app } from 'electron';+ import { describe, expect, it, vi } from 'vitest';++ import {+ createIOSSimulatorNativeDevelopmentAdmissionPolicy,+ evaluateIOSSimulatorNativeCapabilityAdmission,+ IOSSimulatorDeviceGrantStore,+ IOSSimulatorInstanceActor,+ IOSSimulatorInstanceError,+ IOSSimulatorOwnershipStore,+ IOSSimulatorOwnershipRegistryFile,+ IOSSimulatorProjectBuildError,+ IOSSimulatorResourceScheduler,+ WdaError,+ WdaProcessManager,+ type IOSSimulatorEnvironmentReport,+ type IOSSimulatorH264Frame,+ type IOSSimulatorNativeSidecarDriver,+ type IOSSimulatorSimctlLifecycle,+ type IOSSimulatorStreamStats,+ type IOSSimulatorStreamProfile,+ type IOSSimulatorTouchPoint,+ type WdaRunningInstance,+ } from '@cindy/ios-simulator-runtime';++// The host modules default their owner-boundary probe to++// isAppSessionBoundaryPending(), which fails closed on an uncommitted owner.++// These suites exercise simulator/ownership behavior, not boundary transitions;++// owner-pending paths are covered by tests that pass explicit overrides.++vi.mock('../../appSessionState.js', async (importOriginal) => {++ const actual = await importOriginal<typeof import('../../appSessionState.js')>();++ return { ...actual, isAppSessionBoundaryPending: () => false };++});+++ import type { IOSSimulatorPublicRouteStatus } from '../../../shared/iosSimulatorIpc';+ import {+ cancelIOSSimulatorSessionOperations,+ cleanupIOSSimulatorRemovedSession,+ createIOSSimulatorHost,+ createRegistryBackedIOSSimulatorDeviceGrantStore,+ createRegistryBackedIOSSimulatorActor,+ disposeIOSSimulatorHost,+ flushIOSSimulatorOwnershipRegistry,+ getIOSSimulatorPluginStatus,+ getIOSSimulatorMcpDeps,+ reconcilePersistedIOSSimulatorOwnership,+ type IOSSimulatorAppLifecycleAdapter,+ type IOSSimulatorMediaCaptureAdapter,+ type IOSSimulatorProjectBuilderAdapter,+ } from '../ios-simulator';++ const READY_REPORT: IOSSimulatorEnvironmentReport = {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeSelectPath: '/Applications/Xcode.app/Contents/Developer',+ xcodeVersion: 'Xcode 26.4\nBuild version 17E192',+ runtimes: [+ {+ identifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ name: 'iOS 26.4',+ version: '26.4',+ buildVersion: '23E244',+ isAvailable: true,+ availabilityError: null,+ },+ ],+ devices: [+ {+ udid: '1A9D41E0-E031-4AD0-A8B5-847480802E8E',+ name: 'iPhone 17 Pro',+ state: 'Booted',+ isAvailable: true,+ availabilityError: null,+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-26-4',+ runtimeName: 'iOS 26.4',+ runtimeVersion: '26.4',+ deviceTypeIdentifier: null,+ lastBootedAt: null,+ },+ ],+ issue: null,+ error: null,+ setupSteps: [],+ };++ const itMac = process.platform === 'darwin' ? it : it.skip;++ describe('iOS Simulator host', () => {+ function testResourceScheduler() {+ return new IOSSimulatorResourceScheduler({ freeMemoryBytes: () => 100 * 1024 ** 3 });+ }++ function localSession(id: string) {+ return { id, workDir: `/tmp/${id}`, remoteHostId: null };+ }++ it('keeps the default ownership registry lazy for disabled MCP discovery and teardown', async () => {+ const getPath = vi.spyOn(app, 'getPath');+ try {+ const deps = getIOSSimulatorMcpDeps({ isIOSSimulatorEnabled: () => false });++ await expect(deps.describeTools?.({ sessionId: 'disabled-session' })).resolves.toMatchObject({+ ready: false,+ });+ await expect(+ deps.callTool('check_environment', {}, { sessionId: 'disabled-session' }),+ ).resolves.toMatchObject({ errorCode: 'IOS_SIMULATOR_DISABLED' });+ await cancelIOSSimulatorSessionOperations('ordinary-session');+ await flushIOSSimulatorOwnershipRegistry();+ expect(getPath).not.toHaveBeenCalled();+ } finally {+ getPath.mockRestore();+ }+ });++ it('keeps a cold plugin status probe passive and leaves the ownership writer available', async () => {+ const acquireWriter = vi.spyOn(+ IOSSimulatorOwnershipRegistryFile.prototype,+ 'acquireWriterSync',+ );+ const inspectEnvironment = vi.fn(async () => READY_REPORT);+ try {+ await expect(+ getIOSSimulatorPluginStatus('passive-session', {+ getSession: vi.fn(async (id) => localSession(id)),+ inspectEnvironment,+ }),+ ).resolves.toEqual({+ ok: true,+ status: {+ environment: {+ platform: 'darwin',+ supported: true,+ ready: true,+ xcodeVersion: READY_REPORT.xcodeVersion,+ availableDeviceCount: 1,+ },+ instances: [],+ routeStatuses: [],+ },+ });+ expect(inspectEnvironment).toHaveBeenCalledOnce();+ expect(acquireWriter).not.toHaveBeenCalled();+ } finally {+ acquireWriter.mockRestore();+ }+ });++ it.each([+ ['missing', null, 'SESSION_NOT_FOUND'],+ ['archived', { ...localSession('archived'), status: 'archived' as const }, 'SESSION_NOT_FOUND'],+ [+ 'remote',+ { ...localSession('remote'), remoteHostId: 'remote-host' },+ 'UNSUPPORTED_SESSION_KIND',+ ],+ ])(+ 'rejects a %s passive plugin task before inspecting the simulator environment',+ async (_case, session, errorCode) => {+ const inspectEnvironment = vi.fn(async () => READY_REPORT);++ await expect(+ getIOSSimulatorPluginStatus('passive-session', {+ getSession: vi.fn(async () => session),+ inspectEnvironment,+ }),+ ).resolves.toMatchObject({ ok: false, errorCode });+ expect(inspectEnvironment).not.toHaveBeenCalled();+ },+ );++ it('fails a cold plugin status read closed when the account changes during task lookup', async () => {+ let ownerScopeKey = 'cloud:owner-a:1';+ const inspectEnvironment = vi.fn(async () => READY_REPORT);++ await expect(+ getIOSSimulatorPluginStatus('passive-session', {+ getSession: vi.fn(async (id) => {+ ownerScopeKey = 'cloud:owner-b:2';+ return localSession(id);+ }),+ inspectEnvironment,+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerBoundaryPending: () => false,+ isHostClosing: () => false,+ }),+ ).resolves.toEqual({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator status is temporarily unavailable.',+ });+ expect(inspectEnvironment).not.toHaveBeenCalled();+ });++ itMac('fences an ordinary removed task without retaining the default Host lease', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-cleanup-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);+ try {+ await expect(cleanupIOSSimulatorRemovedSession('ordinary-session')).resolves.toBeUndefined();++ expect(getPath).toHaveBeenCalledWith('userData');+ await expect(stat(registryPath)).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(competingRegistry.acquireWriterSync()).toBe(true);+ } finally {+ competingRegistry.releaseWriterSync();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ });++ itMac(+ 'persists device grants in the active Cindy profile and restores them after restart',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-grants-'));+ const ownershipRegistry = new IOSSimulatorOwnershipRegistryFile(+ path.join(root, 'ios-simulator', 'ownership-registry.json'),+ );+ try {+ expect(ownershipRegistry.acquireWriterSync()).toBe(true);+ const firstStore = createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);+ firstStore.set(READY_REPORT.devices[0]!.udid, { agentControl: 'allowed' });++ const restoredStore = createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);+ expect(restoredStore.get(READY_REPORT.devices[0]!.udid)).toMatchObject({+ agentControl: 'allowed',+ policySource: 'user',+ });+ restoredStore.set(READY_REPORT.devices[0]!.udid, { agentControl: 'denied' });+ const deniedAfterRestart =+ createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);+ expect(deniedAfterRestart.get(READY_REPORT.devices[0]!.udid).agentControl).toBe('denied');+ expect(+ JSON.parse(+ await readFile(path.join(root, 'ios-simulator', 'device-grants.json'), 'utf8'),+ ),+ ).toMatchObject({+ version: 1,+ grants: [{ simulatorUdid: READY_REPORT.devices[0]!.udid }],+ });++ await writeFile(+ path.join(root, 'ios-simulator', 'device-grants.json'),+ '{"version":1,"grants":[',+ );+ const failClosedStore = createRegistryBackedIOSSimulatorDeviceGrantStore(ownershipRegistry);+ expect(failClosedStore.get(READY_REPORT.devices[0]!.udid).agentControl).toBe('unknown');+ } finally {+ ownershipRegistry.releaseWriterSync();+ await rm(root, { recursive: true, force: true });+ }+ },+ );++ itMac(+ 'recovers pending creates with an empty registry before releasing its writer lease',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-reconcile-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);+ let finishRecovery: (value: readonly string[]) => void = () => undefined;+ const recoverPendingCreatesAtStartup = vi.fn(+ (_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>+ new Promise<readonly string[]>((resolve) => {+ finishRecovery = resolve;+ }),+ );+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ recoverPendingCreatesAtStartup,+ deleteExact: vi.fn(),+ };+ try {+ const recovering = reconcilePersistedIOSSimulatorOwnership({+ createLifecycle: () => lifecycle,+ });+ await vi.waitFor(() => expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce());+ expect(recoverPendingCreatesAtStartup).toHaveBeenCalledWith([], expect.any(AbortSignal));+ expect(competingRegistry.acquireWriterSync()).toBe(false);++ finishRecovery([]);+ await expect(recovering).resolves.toBeUndefined();+ expect(competingRegistry.acquireWriterSync()).toBe(true);+ } finally {+ competingRegistry.releaseWriterSync();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ },+ );++ itMac(+ 'does not inspect or delete pending markers when the ownership registry is invalid',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-invalid-reconcile-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ await mkdir(path.dirname(registryPath), { recursive: true });+ await writeFile(registryPath, '{"version":1,"instances":[');+ const createLifecycle = vi.fn();+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);+ try {+ await expect(+ reconcilePersistedIOSSimulatorOwnership({ createLifecycle }),+ ).rejects.toMatchObject({ code: 'DEVICE_BUSY' });+ expect(createLifecycle).not.toHaveBeenCalled();+ expect(competingRegistry.acquireWriterSync()).toBe(true);+ } finally {+ competingRegistry.releaseWriterSync();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ },+ );++ it('gates an already-created Host on one startup pending-create recovery', async () => {+ let finishRecovery: (value: readonly string[]) => void = () => undefined;+ const recoverPendingCreatesAtStartup = vi.fn(+ (_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>+ new Promise<readonly string[]>((resolve) => {+ finishRecovery = resolve;+ }),+ );+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ recoverPendingCreatesAtStartup,+ deleteExact: vi.fn(),+ };+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({+ lifecycle,+ runtime: { inspect },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ const firstCall = host.callTool('list_devices', {}, { sessionId: 'session-a' });+ await vi.waitFor(() => expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce());+ expect(recoverPendingCreatesAtStartup).toHaveBeenCalledWith([], expect.any(AbortSignal));+ expect(inspect).not.toHaveBeenCalled();++ finishRecovery([]);+ await expect(firstCall).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool('list_devices', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true });+ expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce();+ });++ it('retries startup pending-create recovery after the ownership gate becomes available', async () => {+ let recoveryAllowed = false;+ const recoverPendingCreatesAtStartup = vi.fn(async () => [] as readonly string[]);+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ recoverPendingCreatesAtStartup,+ deleteExact: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ canReconcilePendingCreates: () => recoveryAllowed,+ });++ await expect(+ host.callTool('list_devices', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true });+ expect(recoverPendingCreatesAtStartup).not.toHaveBeenCalled();++ recoveryAllowed = true;+ await expect(+ host.callTool('list_devices', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true });+ expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce();+ });++ it('does not reconcile Simulator ownership during generic IPC bootstrap', () => {+ const source = readFileSync(new URL('../../maker-ipc/register.ts', import.meta.url), 'utf8');+ expect(source).not.toContain('reconcileIOSSimulatorOwnership');+ });++ it('returns device discovery for a local session', async () => {+ const host = createIOSSimulatorHost({+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await expect(host.callTool('list_devices', {}, { sessionId: 'session-a' })).resolves.toEqual({+ ok: true,+ data: {+ devices: READY_REPORT.devices.map((device) => {+ const { availabilityError: _availabilityError, ...safeDevice } = device;+ void _availabilityError;+ return safeDevice;+ }),+ xcodeVersion: 'Xcode 26.4\nBuild version 17E192',+ },+ });+ const environment = await host.callTool('check_environment', {}, { sessionId: 'session-a' });+ expect(environment).not.toHaveProperty('data.xcodeSelectPath');+ expect(environment).not.toHaveProperty('data.devices.0.availabilityError');+ });++ it('keeps Desktop available while a malformed ownership registry fails Simulator closed', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-registry-'));+ const registry = new IOSSimulatorOwnershipRegistryFile(path.join(root, 'registry.json'), {+ acquireWriterLease: () => {+ let held = true;+ return {+ isHeld: () => held,+ release: () => {+ held = false;+ },+ };+ },+ });+ await writeFile(registry.filePath, '{"version":1,"instances":[');+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ reconcilePendingCreates: vi.fn(),+ deleteExact: vi.fn(),+ };++ try {+ const persisted = createRegistryBackedIOSSimulatorActor(lifecycle, registry);+ await expect(+ persisted.actor.create({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ name: 'Must not be created',+ templateDevice: {+ ...READY_REPORT.devices[0]!,+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ },+ }),+ ).rejects.toMatchObject({ code: 'DEVICE_BUSY' });+ expect(lifecycle.createExact).not.toHaveBeenCalled();+ const host = createIOSSimulatorHost({+ actor: persisted.actor,+ lifecycle,+ canReconcilePendingCreates: persisted.canReconcilePendingCreates,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async () => '/tmp/session-a'),+ });++ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'DEVICE_BUSY',+ message: expect.stringContaining('ownership registry is invalid'),+ });+ expect(lifecycle.reconcilePendingCreates).not.toHaveBeenCalled();+ expect(registry.isWriter).toBe(true);+ await persisted.flush();+ persisted.release();+ await host.dispose();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it('projects task ownership, resource limits, and safe unavailable-device reasons', async () => {+ const unavailableDevice = {+ ...READY_REPORT.devices[0]!,+ udid: 'E223400C-3148-4BE5-9538-A60FE457EF38',+ name: 'iPhone 16',+ state: 'Shutdown',+ isAvailable: false,+ availabilityError: 'runtime profile not found using "System" match policy',+ runtimeIdentifier: 'com.apple.CoreSimulator.SimRuntime.iOS-18-4',+ runtimeName: 'iOS 18-4',+ runtimeVersion: null,+ };+ const report: IOSSimulatorEnvironmentReport = {+ ...READY_REPORT,+ devices: [READY_REPORT.devices[0]!, unavailableDevice],+ };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ actor.attach({+ sessionId: 'session-b',+ worktreeRoot: '/tmp/session-b',+ sourceFingerprint: 'fingerprint-b',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const resourceScheduler = testResourceScheduler();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => report) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ const status = await host.getStatus('session-a');++ expect(status).toMatchObject({+ ok: true,+ resource: {+ runningCount: 1,+ softLimit: 2,+ hardLimit: 4,+ maxInstancesPerTask: 4,+ },+ environment: {+ devices: [+ { udid: READY_REPORT.devices[0]!.udid, ownership: 'other-task' },+ {+ udid: unavailableDevice.udid,+ runtimeName: 'iOS 18.4',+ ownership: 'unowned',+ unavailableReason: { code: 'missing-runtime', runtimeName: 'iOS 18.4' },+ },+ ],+ },+ });+ expect(JSON.stringify(status)).not.toContain('runtime profile not found');+ expect(JSON.stringify(status)).not.toContain('availabilityError');+ expect(JSON.stringify(status)).not.toContain('session-b');+ await expect(+ host.callTool(+ 'attach_device',+ { udid: unavailableDevice.udid },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_NOT_FOUND' });+ await host.dispose();+ });++ it('projects cached plugin status without reconciling or renewing ownership', async () => {+ const runtimeInspect = vi.fn(async () => READY_REPORT);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'private-fingerprint',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const before = actor.getOwned('session-a', attached.instanceId);+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: runtimeInspect },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ const first = await host.getPluginStatus('session-a');+ const second = await host.getPluginStatus('session-a');+ expect(first).toEqual(second);+ expect(first).toMatchObject({+ ok: true,+ status: {+ environment: {+ platform: 'darwin',+ ready: true,+ availableDeviceCount: 1,+ },+ instances: [+ {+ instanceId: attached.instanceId,+ simulatorName: 'iPhone 17 Pro',+ generation: attached.generation,+ },+ ],+ },+ });+ expect(runtimeInspect).toHaveBeenCalledTimes(1);+ const serialized = JSON.stringify(first);+ expect(serialized).not.toContain('session-a');+ expect(serialized).not.toContain('1A9D41E0-E031-4AD0-A8B5-847480802E8E');+ expect(serialized).not.toContain('private-fingerprint');+ expect(serialized).not.toContain('lease');+ expect(serialized).not.toContain('deviceGrants');+ expect(serialized).not.toContain('mutationStates');++ const after = actor.getOwned('session-a', attached.instanceId);+ expect(after.generation).toBe(before.generation);+ expect(after.lease).toEqual(before.lease);+ await host.dispose();+ });++ it('fails plugin status closed while the account boundary is pending', async () => {+ const getSession = vi.fn(async (id: string) => localSession(id));+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession,+ getOwnerScopeKey: () => 'cloud:owner-a:1',+ isOwnerBoundaryPending: () => true,+ });++ try {+ await expect(host.getPluginStatus('session-a')).resolves.toEqual({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator status is temporarily unavailable.',+ });+ expect(getSession).not.toHaveBeenCalled();+ expect(inspect).not.toHaveBeenCalled();+ } finally {+ await host.dispose();+ }+ });++ it('does not return an old-owner plugin snapshot when the account changes mid-inspection', async () => {+ let ownerScopeKey = 'cloud:owner-a:1';+ let markInspectionStarted: () => void = () => undefined;+ let releaseInspection: () => void = () => undefined;+ const inspectionStarted = new Promise<void>((resolve) => {+ markInspectionStarted = resolve;+ });+ const inspectionGate = new Promise<void>((resolve) => {+ releaseInspection = resolve;+ });+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'private-fingerprint',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const host = createIOSSimulatorHost({+ actor,+ runtime: {+ inspect: vi.fn(async () => {+ markInspectionStarted();+ await inspectionGate;+ return READY_REPORT;+ }),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerBoundaryPending: () => false,+ });++ try {+ const statusPromise = host.getPluginStatus('session-a');+ await inspectionStarted;+ ownerScopeKey = 'cloud:owner-b:2';+ releaseInspection();++ const status = await statusPromise;+ expect(status).toEqual({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator status is temporarily unavailable.',+ });+ expect(JSON.stringify(status)).not.toContain(attached.instanceId);+ } finally {+ releaseInspection();+ await host.dispose();+ }+ });++ it('keeps build diagnostics host-available without a running simulator instance', async () => {+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await expect(host.describeTools('session-a')).resolves.toMatchObject({+ tools: {+ build_app: { state: 'requires-instance', backend: 'host' },+ read_build_diagnostics: { state: 'available', backend: 'host' },+ },+ });+ });++ it('removes stale orphaned xcresult bundles during ownership reconciliation', async () => {+ const projectRoot = path.join(+ app.getPath('userData'),+ 'ios-simulator',+ 'projects',+ `orphan-reconcile-${crypto.randomUUID()}`,+ );+ const staleBundle = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);+ const freshBundle = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);+ await mkdir(staleBundle, { recursive: true });+ await mkdir(freshBundle, { recursive: true });+ const staleTime = new Date(Date.now() - 31 * 60_000);+ await utimes(staleBundle, staleTime, staleTime);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ try {+ await host.reconcileOwnership();++ await expect(stat(staleBundle)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(freshBundle)).resolves.toBeDefined();+ } finally {+ await host.dispose();+ await rm(projectRoot, { recursive: true, force: true });+ }+ });++ it('reconciles a persisted binding with fresh generation and lease on startup', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const oldRoute = {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ };+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const status = await host.getStatus('session-a');+ expect(status).toMatchObject({+ ok: true,+ instances: [+ {+ instanceId: attached.instanceId,+ generation: attached.generation + 1,+ viewerState: 'detached',+ healthState: 'healthy',+ },+ ],+ });+ await expect(+ host.callTool('list_instances', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(host.setViewerVisibility('session-a', oldRoute, true)).resolves.toMatchObject({+ ok: false,+ errorCode: 'STALE_GENERATION',+ });+ });++ it('reconciles ownership again for a new account generation and releases stale capacity', async () => {+ let ownerScopeKey = 'cloud:owner-a:1';+ let ownerBoundaryPending = false;+ let sessionExists = true;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'owner-a-session',+ worktreeRoot: '/tmp/owner-a-session',+ sourceFingerprint: 'owner-a-fingerprint',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'agent-booted',+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const inspect = vi.fn(async () => READY_REPORT);+ const getSession = vi.fn(async (id: string) => (sessionExists ? localSession(id) : null));+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: { inspect },+ getSession,+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerBoundaryPending: () => ownerBoundaryPending,+ });++ try {+ await host.reconcileOwnership();+ expect(actor.getOwned(attached.sessionId, attached.instanceId)).toBeDefined();+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(inspect).toHaveBeenCalledTimes(1);++ await host.reconcileOwnership();+ expect(inspect).toHaveBeenCalledTimes(1);++ ownerScopeKey = 'cloud:owner-b:2';+ sessionExists = false;+ ownerBoundaryPending = true;+ await host.reconcileOwnership();+ expect(inspect).toHaveBeenCalledTimes(1);+ expect(resourceScheduler.runningCount()).toBe(1);++ ownerBoundaryPending = false;+ await host.reconcileOwnership();+ expect(inspect).toHaveBeenCalledTimes(2);+ expect(getSession).toHaveBeenCalledTimes(2);+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ attached.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.listAll()).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ } finally {+ await host.dispose();+ }+ });++ it.each(['success', 'failure'] as const)(+ 'waits for an old-owner reconciliation (%s) and then reruns for the current owner',+ async (oldOwnerResult) => {+ let ownerScopeKey = 'cloud:owner-a:1';+ let resolveFirstInspectionStarted: (() => void) | undefined;+ let releaseFirstInspection: (() => void) | undefined;+ const firstInspectionStarted = new Promise<void>((resolve) => {+ resolveFirstInspectionStarted = resolve;+ });+ const firstInspectionGate = new Promise<void>((resolve) => {+ releaseFirstInspection = resolve;+ });+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'owner-a-session',+ worktreeRoot: '/tmp/owner-a-session',+ sourceFingerprint: 'owner-a-fingerprint',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'agent-booted',+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ let sessionReadCount = 0;+ const getSession = vi.fn(async (id: string) => {+ sessionReadCount += 1;+ if (oldOwnerResult === 'success' && sessionReadCount === 1) {+ return localSession(id);+ }+ return null;+ });+ let inspectionCount = 0;+ const inspect = vi.fn(async () => {+ inspectionCount += 1;+ if (inspectionCount === 1) {+ resolveFirstInspectionStarted?.();+ await firstInspectionGate;+ if (oldOwnerResult === 'failure') throw new Error('old owner DB closed');+ }+ return READY_REPORT;+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: { inspect },+ getSession,+ getOwnerScopeKey: () => ownerScopeKey,+ isOwnerBoundaryPending: () => false,+ });++ try {+ const ownerAReconcile = host.reconcileOwnership();+ const ownerAOutcome = ownerAReconcile.then(+ () => ({ ok: true as const, error: null }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ await firstInspectionStarted;+ ownerScopeKey = 'cloud:owner-b:2';+ const ownerBReconcile = host.reconcileOwnership();+ releaseFirstInspection?.();+ await ownerBReconcile;+ const ownerASettled = await ownerAOutcome;++ if (oldOwnerResult === 'failure') {+ expect(ownerASettled).toMatchObject({+ ok: false,+ error: expect.objectContaining({ message: 'old owner DB closed' }),+ });+ } else {+ expect(ownerASettled).toEqual({ ok: true, error: null });+ }++ expect(getSession).toHaveBeenCalledTimes(oldOwnerResult === 'failure' ? 1 : 2);+ expect(inspect).toHaveBeenCalledTimes(2);+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ attached.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.listAll()).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ } finally {+ releaseFirstInspection?.();+ await host.dispose();+ }+ },+ );++ it('restores persisted detach grace and releases scheduler capacity at its deadline', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const seedActor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ createId: () => crypto.randomUUID(),+ }),+ lifecycle,+ clock: { now: () => now },+ scheduler: { schedule: () => () => undefined },+ });+ const attached = seedActor.attach({+ sessionId: 'persisted-grace-session',+ worktreeRoot: '/tmp/persisted-grace-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'agent-booted',+ });+ const detached = await seedActor.detach({+ sessionId: attached.sessionId,+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ });+ now = 101_000;+ const scheduled: Array<{+ delayMs: number;+ task: () => void | Promise<void>;+ cancelled: boolean;+ }> = [];+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ createId: () => crypto.randomUUID(),+ initialInstances: [detached],+ }),+ lifecycle,+ clock: { now: () => now },+ scheduler: {+ schedule: (delayMs, task) => {+ const entry = { delayMs, task, cancelled: false };+ scheduled.push(entry);+ return () => {+ entry.cancelled = true;+ };+ },+ },+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const driverManager = {+ get: vi.fn(() => null),+ cleanupOrphaned: vi.fn(async () => undefined),+ start: vi.fn(async () => {+ throw new Error('not expected');+ }),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('persisted-grace-session')),+ });++ try {+ await host.reconcileOwnership();++ const reconciled = actor.getOwned(detached.sessionId, detached.instanceId);+ expect(reconciled).toMatchObject({+ generation: detached.generation + 1,+ graceExpiresAt: detached.graceExpiresAt,+ });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(scheduled).toHaveLength(1);+ expect(scheduled[0]).toMatchObject({+ delayMs: Date.parse(detached.graceExpiresAt!) - now,+ cancelled: false,+ });++ await scheduled[0]!.task();+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ detached.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.listAll()).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ } finally {+ await host.dispose();+ }+ });++ it('recovers persisted WDA ownership before marking a booted binding healthy', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'persisted-wda-session',+ worktreeRoot: '/tmp/persisted-wda-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const cleanupOrphaned = vi+ .fn(async () => undefined)+ .mockRejectedValueOnce(new WdaError('TERMINATION_FAILED', 'orphan still running'));+ const driverManager = {+ get: vi.fn(() => null),+ cleanupOrphaned,+ start: vi.fn(async () => {+ throw new Error('not expected');+ }),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('persisted-wda-session')),+ });++ await host.reconcileOwnership();+ expect(cleanupOrphaned).toHaveBeenCalledWith(attached.instanceId, attached.simulatorUdid);+ expect(actor.getOwned('persisted-wda-session', attached.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'degraded',+ errorCode: 'WDA_UNAVAILABLE',+ });++ await host.reconcileOwnership();+ expect(cleanupOrphaned).toHaveBeenCalledTimes(2);+ expect(actor.getOwned('persisted-wda-session', attached.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'healthy',+ errorCode: null,+ });+ expect(driverManager.stop).not.toHaveBeenCalled();+ });++ it.each(['Booted', 'Booting'] as const)(+ 'restores scheduler occupancy for a persisted %s device',+ async (deviceState) => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'persisted-capacity-session',+ worktreeRoot: '/tmp/persisted-capacity-session',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: deviceState },+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: deviceState }],+ })),+ },+ getSession: vi.fn(async () => localSession('persisted-capacity-session')),+ });++ await host.reconcileOwnership();++ expect(resourceScheduler.runningCount()).toBe(1);+ await expect(+ resourceScheduler.runStart('new-instance', async () => undefined),+ ).rejects.toMatchObject({ code: 'RESOURCE_LIMIT_REACHED' });+ expect(actor.getOwned('persisted-capacity-session', instance.instanceId)).toMatchObject({+ lifecycleState: deviceState === 'Booted' ? 'ready' : 'booting',+ });+ },+ );++ it('keeps restored capacity reserved when persisted task lookup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ actor.attach({+ sessionId: 'unreadable-persisted-session',+ worktreeRoot: '/tmp/unreadable-persisted-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => {+ throw new Error('database unavailable');+ }),+ });++ await host.reconcileOwnership();++ expect(resourceScheduler.runningCount()).toBe(1);+ await expect(+ resourceScheduler.runStart('new-instance', async () => undefined),+ ).rejects.toMatchObject({ code: 'RESOURCE_LIMIT_REACHED' });+ });++ it('cleans up missing-session ownership using the injected lifecycle only', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'deleted-session',+ worktreeRoot: '/tmp/deleted-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => null),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.listAll()).toEqual([]);+ });++ it('shuts down a Cindy-created device before deleting it even if the user booted it', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'deleted-session',+ worktreeRoot: '/tmp/deleted-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'user-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => null),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.listAll()).toEqual([]);+ });++ it('marks a persisted remote session binding degraded without touching its device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'remote-session',+ worktreeRoot: '/tmp/remote-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({ ...localSession('remote-session'), remoteHostId: 'mac-b' })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('remote-session', instance.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'degraded',+ errorCode: 'UNSUPPORTED_SESSION_KIND',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('fails closed when the MCP call has no session context', async () => {+ const inspect = vi.fn();+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(),+ });++ await expect(host.callTool('check_environment', {})).resolves.toMatchObject({+ ok: false,+ errorCode: 'SESSION_CONTEXT_REQUIRED',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('rejects archived sessions before touching local Apple tooling', async () => {+ const inspect = vi.fn();+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async () => ({+ ...localSession('archived-session'),+ status: 'archived' as const,+ })),+ });++ await expect(host.getStatus('archived-session')).resolves.toMatchObject({+ ok: false,+ errorCode: 'SESSION_NOT_FOUND',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('releases archived external ownership without mutating a user device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-session',+ worktreeRoot: '/tmp/archived-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const discardInstance = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ mediaCapture: { discardInstance } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-session'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.listAll()).toEqual([]);+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('keeps archived ownership when recording cleanup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-recording-failure',+ worktreeRoot: '/tmp/archived-recording-failure',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ mediaCapture: {+ discardInstance: vi.fn(async () => {+ throw new Error('recording process is still alive');+ }),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-recording-failure'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('archived-recording-failure', instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ });++ it('cleans archived Cindy-created ownership using creation provenance', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-cindy',+ worktreeRoot: '/tmp/archived-cindy',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'user-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-cindy'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.listAll()).toEqual([]);+ });++ it('rechecks archived status under the task route lock before destructive recovery', async () => {+ let releaseLock!: () => void;+ const lockGate = new Promise<void>((resolve) => {+ releaseLock = resolve;+ });+ let status: 'active' | 'archived' = 'archived';+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'archived-then-restored',+ worktreeRoot: '/tmp/archived-then-restored',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const observeSessionLock = vi.fn();+ const withSessionLock = async <T>(sessionId: string, task: () => Promise<T>): Promise<T> => {+ observeSessionLock(sessionId, task);+ await lockGate;+ return task();+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ withSessionLock,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-then-restored'),+ status,+ })),+ });++ const reconcile = host.reconcileOwnership();+ await vi.waitFor(() => expect(observeSessionLock).toHaveBeenCalledOnce());+ status = 'active';+ releaseLock();+ await reconcile;++ expect(observeSessionLock).toHaveBeenCalledWith('archived-then-restored', expect.any(Function));+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ expect(actor.getOwned('archived-then-restored', instance.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'healthy',+ });+ });++ it('stops the driver runtime before shutting down and deleting a stale device', async () => {+ const order: string[] = [];+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => {+ order.push('shutdown');+ }),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => {+ order.push('delete');+ }),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'deleted-cindy',+ worktreeRoot: '/tmp/deleted-cindy',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const stopDriver = vi.fn(async () => {+ order.push('driver');+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('deleted-cindy'),+ status: 'deleted' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(order).toEqual(['driver', 'shutdown', 'delete']);+ expect(actor.listAll()).toEqual([]);+ });++ it('preserves stale ownership and the device when driver cleanup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'archived-driver-failure',+ worktreeRoot: '/tmp/archived-driver-failure',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => {+ throw new Error('driver process group did not stop');+ }),+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-driver-failure'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned('archived-driver-failure', instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('aborts driver work before orphan recovery and still scans after stop fails', async () => {+ const order: string[] = [];+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => READY_REPORT.devices[0]),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'removed-during-driver-start',+ worktreeRoot: '/tmp/removed-during-driver-start',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => {+ order.push('stop');+ throw new Error('pending start cancellation failed');+ }),+ cleanupOrphaned: vi.fn(async () => {+ order.push('cleanup');+ }),+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => null),+ });++ await expect(host.cleanupRemovedSession(instance.sessionId)).rejects.toMatchObject({+ code: 'DEVICE_BUSY',+ });+ expect(order).toEqual(['stop', 'cleanup']);+ expect(actor.listAll()).toHaveLength(1);+ });++ it('stops the driver runtime when ownership reconcile observes a shut down device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'device-loss-session',+ worktreeRoot: '/tmp/device-loss-session',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const stopDriver = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' }],+ })),+ },+ getSession: vi.fn(async () => localSession('device-loss-session')),+ });++ await host.reconcileOwnership();++ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(actor.getOwned('device-loss-session', instance.instanceId)).toMatchObject({+ lifecycleState: 'stopped',+ healthState: 'healthy',+ });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('shuts down but does not delete an archived external device booted by the Agent', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'archived-agent-booted',+ worktreeRoot: '/tmp/archived-agent-booted',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-agent-booted'),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ expect(actor.listAll()).toEqual([]);+ });++ it('aborts archived CoreSimulator cleanup before updater force-quit', async () => {+ let shutdownSignal: AbortSignal | undefined;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(+ (_udid: string, signal?: AbortSignal) =>+ new Promise<void>((_resolve, reject) => {+ shutdownSignal = signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ ),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'archived-force-quit',+ worktreeRoot: '/tmp/archived-force-quit',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession(instance.sessionId),+ status: 'archived' as const,+ })),+ });++ const reconciling = host.reconcileOwnership();+ await vi.waitFor(() => expect(shutdownSignal).toBeDefined());+ host.abortOperationsForExit();++ expect(shutdownSignal?.aborted).toBe(true);+ await expect(reconciling).resolves.toBeUndefined();+ expect(actor.getOwned(instance.sessionId, instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ await host.dispose();+ });++ it.each(['abortOperationsForExit', 'dispose'] as const)(+ 'aborts an active runtime inspection during %s',+ async (shutdownMode) => {+ let inspectSignal: AbortSignal | undefined;+ const inspect = vi.fn(+ (signal?: AbortSignal) =>+ new Promise<IOSSimulatorEnvironmentReport>((_resolve, reject) => {+ inspectSignal = signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ );+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ const inspection = host.getPluginStatus('runtime-inspection-exit');+ await vi.waitFor(() => expect(inspectSignal).toBeDefined());+ let disposePromise: Promise<void>;+ if (shutdownMode === 'abortOperationsForExit') {+ host.abortOperationsForExit();+ expect(inspectSignal?.aborted).toBe(true);+ disposePromise = host.dispose();+ } else {+ disposePromise = host.dispose();+ expect(inspectSignal?.aborted).toBe(true);+ }+ await expect(inspection).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ });+ await disposePromise;+ },+ );++ it.each(['Booted', 'Booting'] as const)(+ 'keeps archived ownership and scheduler capacity when %s shutdown fails',+ async (deviceState) => {+ const sessionId = `archived-cleanup-failure-${deviceState.toLowerCase()}`;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => {+ throw new Error('simctl shutdown failed');+ }),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId,+ worktreeRoot: '/tmp/archived-cleanup-failure',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: deviceState },+ });+ const resourceScheduler = testResourceScheduler();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: deviceState }],+ })),+ },+ getSession: vi.fn(async () => ({+ ...localSession(sessionId),+ status: 'archived' as const,+ })),+ });++ await host.reconcileOwnership();++ expect(actor.getOwned(sessionId, instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ },+ );++ it('releases scheduler capacity only after Simulator shutdown succeeds', async () => {+ const shutdownExact = vi+ .fn<() => Promise<void>>()+ .mockRejectedValueOnce(+ new IOSSimulatorInstanceError('SIMULATOR_SHUTDOWN_FAILED', 'simctl shutdown failed', true),+ )+ .mockResolvedValue(undefined);+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact,+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'shutdown-retry-session',+ worktreeRoot: '/tmp/shutdown-retry-session',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const resourceScheduler = testResourceScheduler();+ await resourceScheduler.runStart(instance.instanceId, async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('shutdown-retry-session')),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('shutdown-retry-session', instance.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ await expect(+ host.callTool('stop_instance', route, {+ sessionId: 'shutdown-retry-session',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_SHUTDOWN_FAILED' });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(actor.getOwned('shutdown-retry-session', instance.instanceId)).toMatchObject({+ lifecycleState: 'error',+ errorCode: 'SIMULATOR_SHUTDOWN_FAILED',+ });++ await expect(+ host.callTool('stop_instance', route, {+ sessionId: 'shutdown-retry-session',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(resourceScheduler.runningCount()).toBe(0);+ expect(shutdownExact).toHaveBeenCalledTimes(2);+ await host.dispose();+ });++ it.each([+ {+ label: 'external preexisting',+ creationProvenance: 'external' as const,+ bootProvenance: 'preexisting' as const,+ expectShutdown: false,+ expectDelete: false,+ },+ {+ label: 'external Agent-booted',+ creationProvenance: 'external' as const,+ bootProvenance: 'agent-booted' as const,+ expectShutdown: true,+ expectDelete: false,+ },+ {+ label: 'Cindy-created',+ creationProvenance: 'cindy' as const,+ bootProvenance: 'user-booted' as const,+ expectShutdown: true,+ expectDelete: true,+ },+ ])(+ 'cleans a removed $label binding after startup ownership reconcile has latched',+ async ({ creationProvenance, bootProvenance, expectShutdown, expectDelete }) => {+ const device = { ...READY_REPORT.devices[0]!, state: 'Booted' as const };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => device),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'removed-session',+ worktreeRoot: '/tmp/removed-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance,+ bootProvenance,+ device,+ });+ const resourceScheduler = testResourceScheduler();+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {+ commitRunning();+ });+ const stopDriver = vi.fn(async () => undefined);+ const discardSession = vi.fn(async () => undefined);+ const discardInstance = vi.fn(async () => undefined);+ const framePump = { clear: vi.fn(), snapshot: vi.fn(() => null) };+ const h264FramePump = { clear: vi.fn() };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ framePump: framePump as never,+ h264FramePump: h264FramePump as never,+ mediaCapture: {+ discardSession,+ discardInstance,+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await host.reconcileOwnership();+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();++ expect(actor.list('removed-session')).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ expect(stopDriver).toHaveBeenCalledOnce();+ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(discardInstance).toHaveBeenCalledOnce();+ expect(framePump.clear).toHaveBeenCalledWith(instance.instanceId);+ expect(h264FramePump.clear).toHaveBeenCalledWith(instance.instanceId);+ expect(lifecycle.findExact).toHaveBeenCalledTimes(expectShutdown ? 1 : 0);+ expect(lifecycle.shutdownExact).toHaveBeenCalledTimes(expectShutdown ? 1 : 0);+ expect(lifecycle.deleteExact).toHaveBeenCalledTimes(expectDelete ? 1 : 0);+ },+ );++ it('treats an already missing Cindy-created device as successfully removed', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => null),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'removed-session',+ worktreeRoot: '/tmp/removed-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: READY_REPORT.devices[0]!,+ });+ const resourceScheduler = testResourceScheduler();+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {+ commitRunning();+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ },+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await host.reconcileOwnership();+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();++ expect(actor.list('removed-session')).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ expect(lifecycle.findExact).toHaveBeenCalledOnce();+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('cleans only the removed task ownership and scheduler capacity', async () => {+ const otherDevice = {+ ...READY_REPORT.devices[0]!,+ udid: '2A9D41E0-E031-4AD0-A8B5-847480802E8E',+ name: 'iPhone 17 Pro B',+ };+ const environment = { ...READY_REPORT, devices: [READY_REPORT.devices[0]!, otherDevice] };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const removed = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ device: READY_REPORT.devices[0]!,+ });+ const retained = actor.attach({+ sessionId: 'session-b',+ worktreeRoot: '/tmp/session-b',+ sourceFingerprint: 'fingerprint-b',+ creationProvenance: 'external',+ bootProvenance: 'preexisting',+ device: otherDevice,+ });+ const resourceScheduler = testResourceScheduler();+ for (const instance of [removed, retained]) {+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {+ commitRunning();+ });+ }+ const stopDriver = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => environment) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await host.reconcileOwnership();+ await host.cleanupRemovedSession('session-a');++ expect(actor.list('session-a')).toEqual([]);+ expect(actor.list('session-b')).toHaveLength(1);+ expect(actor.list('session-b')[0]?.instanceId).toBe(retained.instanceId);+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(stopDriver).toHaveBeenCalledOnce();+ expect(stopDriver).toHaveBeenCalledWith(removed.instanceId);+ });++ it('aborts CoreSimulator startup before waiting on task-removal barriers', async () => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' };+ let bootSignal: AbortSignal | undefined;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => shutdownDevice),+ bootExact: vi.fn(+ (_udid, signal) =>+ new Promise<typeof shutdownDevice>((_resolve, reject) => {+ bootSignal = signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ ),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'removed-during-start',+ worktreeRoot: '/tmp/removed-during-start',+ sourceFingerprint: 'fingerprint-a',+ device: shutdownDevice,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler: testResourceScheduler(),+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ },+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: {+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [shutdownDevice] })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ await host.reconcileOwnership();+ let releasePostCancellationProbe: (device: typeof shutdownDevice) => void = () => undefined;+ const postCancellationProbe = new Promise<typeof shutdownDevice>((resolve) => {+ releasePostCancellationProbe = resolve;+ });+ vi.mocked(lifecycle.findExact).mockImplementation(async () => postCancellationProbe);+ const current = actor.getOwned(attached.sessionId, attached.instanceId);+ const starting = host.callTool(+ 'start_instance',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: current.sessionId, origin: 'user' },+ );+ await vi.waitFor(() => expect(bootSignal).toBeDefined());++ const cleanup = host.cleanupRemovedSession(current.sessionId);+ await vi.waitFor(() => expect(bootSignal?.aborted).toBe(true));++ await expect(starting).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ releasePostCancellationProbe(shutdownDevice);+ await expect(cleanup).resolves.toBeUndefined();+ expect(actor.list(current.sessionId)).toEqual([]);+ await host.dispose();+ });++ it('retains degraded ownership and scheduler capacity when removed-task cleanup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'removed-session',+ worktreeRoot: '/tmp/removed-session',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'external',+ bootProvenance: 'agent-booted',+ device: READY_REPORT.devices[0]!,+ });+ const resourceScheduler = testResourceScheduler();+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {+ commitRunning();+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => {+ throw new Error('driver process group did not stop');+ }),+ },+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await host.reconcileOwnership();+ await expect(host.cleanupRemovedSession('removed-session')).rejects.toMatchObject({+ code: 'DEVICE_BUSY',+ });++ expect(actor.getOwned('removed-session', instance.instanceId)).toMatchObject({+ healthState: 'degraded',+ errorCode: 'ARCHIVED_CLEANUP_FAILED',+ });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('aborts and drains pending-marker reconciliation before host disposal completes', async () => {+ let reconcileSignal: AbortSignal | undefined;+ let finishReconciliation: (value: readonly string[]) => void = () => undefined;+ const reconcilePendingCreates = vi.fn(+ (_owned: readonly { udid: string; name: string }[], signal?: AbortSignal) =>+ new Promise<readonly string[]>((resolve) => {+ reconcileSignal = signal;+ finishReconciliation = resolve;+ }),+ );+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ reconcilePendingCreates,+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'abc',+ device: READY_REPORT.devices[0]!,+ });+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({ actor, lifecycle, runtime: { inspect } });++ const reconciling = host.reconcileOwnership();+ await vi.waitFor(() => expect(reconcileSignal).toBeDefined());+ let disposed = false;+ const disposing = host.dispose().then(() => {+ disposed = true;+ });++ expect(reconcileSignal?.aborted).toBe(true);+ await Promise.resolve();+ expect(disposed).toBe(false);+ expect(reconcilePendingCreates).toHaveBeenCalledWith(+ [{ udid: instance.simulatorUdid, name: instance.simulatorName }],+ reconcileSignal,+ );++ finishReconciliation([]);+ await Promise.all([reconciling, disposing]);+ expect(disposed).toBe(true);+ expect(inspect).not.toHaveBeenCalled();+ });++ it('disposes WDA and recording resources on host shutdown without changing ownership', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const cancelLifecycleStarts = vi.spyOn(actor, 'cancelAllLifecycleStarts');+ const instance = actor.attach({+ sessionId: 'dispose-session',+ worktreeRoot: '/tmp/dispose-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const stopDriver = vi.fn(async () => undefined);+ const discardInstance = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ mediaCapture: { discardInstance } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('dispose-session')),+ });++ let mutationSignal: AbortSignal | undefined;+ const activeMutation = actor+ .runMutation(+ {+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ async (_current, signal) => {+ mutationSignal = signal;+ await new Promise<void>((resolve) => {+ signal.addEventListener('abort', () => resolve(), { once: true });+ });+ },+ 'user',+ )+ .catch((error: unknown) => error);+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());++ await host.dispose();+ await host.dispose();++ expect(mutationSignal?.aborted).toBe(true);+ await expect(activeMutation).resolves.toMatchObject({ code: 'MUTATION_CANCELLED' });+ expect(discardInstance).toHaveBeenCalledTimes(1);+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);+ expect(stopDriver).toHaveBeenCalledTimes(1);+ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ expect(cancelLifecycleStarts).toHaveBeenCalledTimes(1);+ expect(actor.listAll()).toHaveLength(1);+ });++ it('fails closed for status and tool calls after host disposal begins', async () => {+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ await host.dispose();++ await expect(host.getStatus('disposed-session')).resolves.toMatchObject({+ ok: false,+ sessionId: 'disposed-session',+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ await expect(+ host.callTool('list_instances', {}, { sessionId: 'disposed-session', origin: 'user' }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('does not keep a WDA start alive when disposal races an in-flight tool call', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });+ const instance = actor.attach({+ sessionId: 'dispose-race-session',+ worktreeRoot: '/tmp/dispose-race-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ let releaseStart!: (value: WdaRunningInstance) => void;+ const startDriver = vi.fn(+ () =>+ new Promise<WdaRunningInstance>((resolve) => {+ releaseStart = resolve;+ }),+ );+ const stopDriver = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ driverManager: {+ get: vi.fn(() => null),+ start: startDriver,+ stop: stopDriver,+ },+ resourceScheduler: testResourceScheduler(),+ getSession: vi.fn(async () => localSession('dispose-race-session')),+ });+ await expect(host.getStatus('dispose-race-session')).resolves.toMatchObject({ ok: true });+ const current = actor.getOwned('dispose-race-session', instance.instanceId);+ const callPromise = host.callTool(+ 'start_instance',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: 'dispose-race-session', origin: 'user' },+ );+ await vi.waitFor(() => expect(startDriver).toHaveBeenCalledTimes(1));++ await host.dispose();+ releaseStart({+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 123,+ controlPort: 8100,+ mjpegPort: 9100,+ sourceRevision: 'revision',+ buildCacheKey: 'cache',+ driver: {} as WdaRunningInstance['driver'],+ driverSessionId: 'session',+ health: {+ ready: true,+ message: null,+ osName: 'iOS',+ osVersion: '26.4',+ sdkVersion: '26.4',+ deviceIp: null,+ },+ startedAt: new Date().toISOString(),+ });++ await expect(callPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ expect(stopDriver).toHaveBeenCalled();+ });++ it('does not retain build results that finish after host disposal', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'dispose-build-session',+ worktreeRoot: '/tmp/dispose-build-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const projectRoot = path.join(+ app.getPath('userData'),+ 'ios-simulator',+ 'projects',+ `dispose-build-${crypto.randomUUID()}`,+ );+ const resultBundlePath = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);+ await mkdir(resultBundlePath, { recursive: true });+ let buildSignal: AbortSignal | undefined;+ const build = vi.fn(+ (input: Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]) =>+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>(+ (_, reject) => {+ buildSignal = input.signal;+ input.signal?.addEventListener('abort', () => {+ reject(+ new IOSSimulatorProjectBuildError(+ 'APP_BUILD_FAILED',+ 'cancelled',+ '',+ resultBundlePath,+ false,+ true,+ ),+ );+ });+ },+ ),+ );+ const disposeMedia = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ projectBuilder: { build },+ mediaCapture: {+ dispose: disposeMedia,+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('dispose-build-session')),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('dispose-build-session', instance.instanceId);+ const callPromise = host.callTool(+ 'build_app',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: 'dispose-build-session', origin: 'user' },+ );+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(1));++ const disposePromise = host.dispose();+ expect(disposeMedia).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(buildSignal?.aborted).toBe(true));+ await disposePromise;++ try {+ await expect(callPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_HOST_ERROR',+ message: 'The iOS Simulator host is shutting down.',+ });+ await expect(stat(resultBundlePath)).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ await rm(projectRoot, { recursive: true, force: true });+ }+ });++ it('aborts and drains active xcresult readers before host disposal completes', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'force-quit-xcresult-session',+ worktreeRoot: '/tmp/force-quit-xcresult-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const resultBundlePath = `/tmp/CindyBuild-${crypto.randomUUID()}.xcresult`;+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(async (input) => ({+ kind: 'xcode-project',+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: `${input.worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: `${input.worktreeRoot}/Demo.app`,+ resultBundlePath,+ buildLogTail: 'build succeeded',+ }));+ let readSignal: AbortSignal | undefined;+ let releaseRead!: () => void;+ let projectBuilder!: IOSSimulatorProjectBuilderAdapter;+ const readXcresult = vi.fn(function (+ this: IOSSimulatorProjectBuilderAdapter,+ _path: string,+ _maxBufferBytes?: number,+ signal?: AbortSignal,+ ) {+ expect(this).toBe(projectBuilder);+ return new Promise<string>((resolve) => {+ readSignal = signal;+ releaseRead = () => {+ resolve('late xcresult content that must not be cached');+ };+ });+ });+ projectBuilder = { build, readXcresult };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ projectBuilder,+ appLifecycle: {+ inspectArtifact: vi.fn(async () => ({+ artifactId: 'artifact-xcresult',+ worktreeRoot: '/tmp/force-quit-xcresult-session',+ authorizedRoot: '/tmp/force-quit-xcresult-session',+ appPath: '/tmp/force-quit-xcresult-session/Demo.app',+ bundleId: 'com.example.demo',+ createdAt: '2026-08-08T00:00:00.000Z',+ })),+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ mediaCapture: {+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('force-quit-xcresult-session')),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('force-quit-xcresult-session', instance.instanceId);+ const built = await host.callTool(+ 'build_app',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: current.sessionId, origin: 'user' },+ );+ expect(built).toMatchObject({ ok: true });+ const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })+ .data.diagnostics.diagnosticsId;+ const readPromise = host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'xcresult' },+ { sessionId: current.sessionId, origin: 'agent' },+ );+ await vi.waitFor(() => expect(readXcresult).toHaveBeenCalledOnce());++ expect(() => host.abortOperationsForExit()).not.toThrow();+ expect(readSignal?.aborted).toBe(true);+ let disposeSettled = false;+ const disposePromise = host.dispose().then(() => {+ disposeSettled = true;+ });+ await Promise.resolve();+ expect(disposeSettled).toBe(false);++ releaseRead();++ await disposePromise;+ await expect(readPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ expect(readXcresult).toHaveBeenCalledWith(resultBundlePath, undefined, readSignal);+ });++ it('synchronously aborts active builds before updater force-quit', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const abortLifecycleStarts = vi.spyOn(actor, 'abortOperationsForExit');+ const instance = actor.attach({+ sessionId: 'force-quit-build-session',+ worktreeRoot: '/tmp/force-quit-build-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ let buildSignal: AbortSignal | undefined;+ const build = vi.fn(+ (input: Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]) =>+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>(+ (_, reject) => {+ buildSignal = input.signal;+ input.signal?.addEventListener('abort', () => {+ reject(+ new IOSSimulatorProjectBuildError(+ 'APP_BUILD_FAILED',+ 'cancelled',+ '',+ null,+ false,+ true,+ ),+ );+ });+ },+ ),+ );+ const abortRecording = vi.fn(() => {+ throw new Error('recording already exited');+ });+ const abortDriver = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ abortOperationsForExit: abortDriver,+ },+ projectBuilder: { build },+ mediaCapture: {+ abortOperationsForExit: abortRecording,+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('force-quit-build-session')),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('force-quit-build-session', instance.instanceId);+ const callPromise = host.callTool(+ 'build_app',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: 'force-quit-build-session', origin: 'user' },+ );+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());++ let mutationSignal: AbortSignal | undefined;+ const activeMutation = actor+ .runMutation(+ {+ sessionId: current.sessionId,+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ async (_instance, signal) => {+ mutationSignal = signal;+ await new Promise<void>((resolve) => {+ signal.addEventListener('abort', () => resolve(), { once: true });+ });+ },+ 'user',+ )+ .catch((error: unknown) => error);+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());++ expect(() => host.abortOperationsForExit()).not.toThrow();++ expect(buildSignal?.aborted).toBe(true);+ expect(mutationSignal?.aborted).toBe(true);+ expect(abortLifecycleStarts).toHaveBeenCalledOnce();+ expect(abortRecording).toHaveBeenCalledOnce();+ expect(abortDriver).toHaveBeenCalledOnce();+ await expect(callPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(activeMutation).resolves.toMatchObject({ code: 'MUTATION_CANCELLED' });+ await host.dispose();+ });++ it('rejects SSH sessions before touching local Apple tooling', async () => {+ const inspect = vi.fn();+ const host = createIOSSimulatorHost({+ runtime: { inspect },+ getSession: vi.fn(async (id) => ({ ...localSession(id), remoteHostId: 'build-mac' })),+ });++ await expect(host.getStatus('remote-session')).resolves.toMatchObject({+ ok: false,+ errorCode: 'UNSUPPORTED_SESSION_KIND',+ });+ expect(inspect).not.toHaveBeenCalled();+ });++ it('enforces the project plugin gate for MCP but not the shared host', async () => {+ const host = createIOSSimulatorHost({+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const deps = getIOSSimulatorMcpDeps({+ host,+ isIOSSimulatorEnabled: () => false,+ });++ await expect(+ deps.callTool('check_environment', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_DISABLED',+ });+ await expect(host.getStatus('session-a')).resolves.toMatchObject({ ok: true });+ });++ it('evaluates the MCP plugin gate against the current project workdir', async () => {+ const host = createIOSSimulatorHost({+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const isIOSSimulatorEnabled = vi.fn(+ (context?: { workingDir?: string }) => context?.workingDir === '/projects/enabled-ios',+ );+ const deps = getIOSSimulatorMcpDeps({ host, isIOSSimulatorEnabled });++ await expect(+ deps.callTool(+ 'check_environment',+ {},+ {+ sessionId: 'session-a',+ workingDir: '/projects/enabled-ios',+ },+ ),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ deps.callTool(+ 'check_environment',+ {},+ {+ sessionId: 'session-a',+ workingDir: '/projects/disabled-ios',+ },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'IOS_SIMULATOR_DISABLED',+ });+ expect(isIOSSimulatorEnabled).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ workingDir: '/projects/enabled-ios' }),+ );+ expect(isIOSSimulatorEnabled).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ workingDir: '/projects/disabled-ios' }),+ );+ });++ it('does not expose WDA endpoints or raw driver errors to callers', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(async () => {+ throw new WdaError(+ 'HTTP_ERROR',+ 'GET http://127.0.0.1:43127/status returned an internal Xcode path',+ 500,+ );+ }),+ stop: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ const result = await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );++ expect(result).toEqual({+ ok: false,+ errorCode: 'WDA_UNAVAILABLE',+ message: 'The simulator automation driver is unavailable.',+ });+ expect(JSON.stringify(result)).not.toContain('127.0.0.1');+ expect(JSON.stringify(result)).not.toContain('43127');+ expect(JSON.stringify(result)).not.toContain('Xcode path');+ });++ it('recycles an idle WDA process without shutting down the simulator', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const started = await actor.start({+ sessionId: 'session-a',+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ });+ const running = {+ instanceId: started.instanceId,+ simulatorUdid: started.simulatorUdid,+ pid: 42,+ driver: { streamFrames: vi.fn(async () => ({ endReason: 'aborted' as const })) },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ idleRecycleMs: 1,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const route = {+ instanceId: started.instanceId,+ generation: started.generation,+ leaseId: started.lease.id,+ };+ await expect(host.setViewerVisibility('session-a', route, false)).resolves.toMatchObject({+ ok: true,+ });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(driverManager.stop).toHaveBeenCalledWith(started.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ });++ it('does not let a late viewer open resurrect a stream after the matching close', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver: {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ let liveRunning: WdaRunningInstance | null = null;+ const probe = vi.fn(async () => liveRunning);+ let resolveMemoryProbe: (value: {+ source: 'node-os';+ freePercentage: null;+ freeBytes: number;+ totalBytes: number;+ }) => void = () => undefined;+ const memoryProbe = vi.fn(+ () =>+ new Promise<{+ source: 'node-os';+ freePercentage: null;+ freeBytes: number;+ totalBytes: number;+ }>((resolve) => {+ resolveMemoryProbe = resolve;+ }),+ );+ const resourceScheduler = new IOSSimulatorResourceScheduler({ memoryProbe });+ const driverManager = {+ get: vi.fn(() => liveRunning),+ probe,+ start: vi.fn(async () => running),+ stop: vi.fn(async () => undefined),+ };+ const framePump = {+ setVisible: vi.fn(({ visible }: { visible: boolean }) => ({+ instanceId: instance.instanceId,+ generation: instance.generation,+ state: visible ? ('connecting' as const) : ('idle' as const),+ reconnectAttempt: 0,+ latestFrame: null,+ })),+ snapshot: vi.fn(() => null),+ clear: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ framePump: framePump as never,+ idleRecycleMs: 20,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ const lateOpen = host.setViewerVisibility(+ 'session-a',+ route,+ true,+ 'jpeg',+ undefined,+ 17,+ 'viewer-a',+ );+ await vi.waitFor(() => expect(memoryProbe).toHaveBeenCalledOnce());+ await expect(+ host.setViewerVisibility('session-a', route, false, 'jpeg', undefined, 17, 'viewer-a'),+ ).resolves.toMatchObject({ ok: true });+ expect(actor.getOwned('session-a', instance.instanceId).healthState).toBe('healthy');+ resolveMemoryProbe({+ source: 'node-os',+ freePercentage: null,+ freeBytes: 100 * 1024 ** 3,+ totalBytes: 128 * 1024 ** 3,+ });++ await expect(lateOpen).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });+ expect(driverManager.start).not.toHaveBeenCalled();+ expect(framePump.setVisible).not.toHaveBeenCalledWith(+ expect.objectContaining({ visible: true }),+ );++ liveRunning = running;+ let resolveStaleProbe: (value: WdaRunningInstance | null) => void = () => undefined;+ probe.mockImplementationOnce(+ () =>+ new Promise<WdaRunningInstance | null>((resolve) => {+ resolveStaleProbe = resolve;+ }),+ );+ const staleOpen = host.setViewerVisibility(+ 'session-a',+ route,+ true,+ 'jpeg',+ undefined,+ 17,+ 'viewer-stale',+ );+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(2));+ await expect(+ host.setViewerVisibility('session-a', route, true, 'jpeg', undefined, 17, 'viewer-current'),+ ).resolves.toMatchObject({ ok: true });+ const hiddenCallsBeforeStaleClose = framePump.setVisible.mock.calls.filter(+ ([request]) => request.visible === false,+ ).length;+ await expect(+ host.setViewerVisibility('session-a', route, false, 'jpeg', undefined, 17, 'viewer-stale'),+ ).resolves.toMatchObject({ ok: true, data: { ignored: true } });+ expect(+ framePump.setVisible.mock.calls.filter(([request]) => request.visible === false),+ ).toHaveLength(hiddenCallsBeforeStaleClose);+ resolveStaleProbe(running);+ await expect(staleOpen).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });++ await expect(+ host.setViewerVisibility('session-a', route, false, 'jpeg', undefined, 17, 'viewer-current'),+ ).resolves.toMatchObject({ ok: true });+ let resolveRevokedProbe: (value: WdaRunningInstance | null) => void = () => undefined;+ probe.mockImplementationOnce(+ () =>+ new Promise<WdaRunningInstance | null>((resolve) => {+ resolveRevokedProbe = resolve;+ }),+ );+ const revokedOpen = host.setViewerVisibility(+ 'session-a',+ route,+ true,+ 'jpeg',+ undefined,+ 17,+ 'viewer-revoked',+ );+ await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(4));+ // The pending open has already cancelled the timer from the explicit+ // close, so only revocation cleanup can produce the next stop call.+ driverManager.stop.mockClear();+ expect(host.revokeRendererViewer('session-a', 17)).toBe(1);+ resolveRevokedProbe(running);+ await expect(revokedOpen).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });+ await vi.waitFor(() => expect(driverManager.stop).toHaveBeenCalledWith(instance.instanceId));++ const invalidOpen = host.setViewerVisibility(+ 'session-a',+ { ...route, instanceId: 'renderer-supplied-unknown-instance' },+ true,+ 'jpeg',+ undefined,+ 18,+ 'viewer-invalid',+ );+ expect(host.revokeRendererViewer('session-a', 18)).toBe(0);+ await expect(invalidOpen).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_FOUND',+ });+ await host.dispose();+ });++ it('returns a fresh viewer route when driver recovery outlives the lease', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ leaseDurationMs: 100,+ });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver: {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(async () => {+ now = 1_101;+ return running;+ }),+ stop: vi.fn(async () => undefined),+ };+ const framePump = {+ setVisible: vi.fn(() => ({+ instanceId: instance.instanceId,+ generation: instance.generation,+ state: 'connecting' as const,+ reconnectAttempt: 0,+ latestFrame: null,+ })),+ snapshot: vi.fn(() => null),+ clear: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler: testResourceScheduler(),+ });+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ const result = await host.setViewerVisibility('session-a', route, true, 'jpeg');++ expect(result).toMatchObject({+ ok: true,+ data: {+ instance: {+ instanceId: instance.instanceId,+ generation: instance.generation,+ lease: {+ id: expect.any(String),+ expiresAt: new Date(1_201).toISOString(),+ },+ },+ stream: { state: 'connecting' },+ },+ });+ expect(+ (+ result as {+ ok: true;+ data: { instance: { lease: { id: string } } };+ }+ ).data.instance.lease.id,+ ).not.toBe(route.leaseId);+ await host.dispose();+ });++ it('stops exact expired viewer media without letting a stale lease stop its replacement', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ leaseDurationMs: 100,+ });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const nativeDriver = {+ kind: 'native-sidecar' as const,+ capabilities: { h264Stream: true },+ };+ const wdaDriver = {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ };+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver: wdaDriver,+ driverRouter: {+ stream: vi.fn(() => ({+ adapter: 'native-sidecar',+ fallback: false,+ reason: null,+ source: nativeDriver,+ })),+ capabilityReport: vi.fn(() => ({+ nativeSidecar: { available: true },+ })),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const snapshot = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ state: 'streaming' as const,+ reconnectAttempt: 0,+ latestFrame: null,+ };+ const framePump = {+ setVisible: vi.fn(() => snapshot),+ snapshot: vi.fn(() => snapshot),+ clear: vi.fn(),+ };+ const h264FramePump = {+ setVisible: vi.fn(() => snapshot),+ snapshot: vi.fn(() => snapshot),+ clear: vi.fn(),+ };+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ h264FramePump: h264FramePump as never,+ idleRecycleMs: Number.POSITIVE_INFINITY,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ const initialRoute = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ await expect(+ host.setViewerVisibility('session-a', initialRoute, true, 'h264', undefined, 17),+ ).resolves.toMatchObject({ ok: true });+ h264FramePump.clear.mockClear();+ now += 101;+ await expect(host.getLatestFrame('session-a', initialRoute, 17)).resolves.toMatchObject({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ });+ expect(h264FramePump.clear).toHaveBeenCalledWith(instance.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(driverManager.stop).not.toHaveBeenCalled();++ const closeLease = actor.heartbeatOwned('session-a', instance.instanceId);+ const closeRoute = {+ instanceId: closeLease.instanceId,+ generation: closeLease.generation,+ leaseId: closeLease.lease.id,+ };+ await host.setViewerVisibility('session-a', closeRoute, true, 'h264');+ h264FramePump.clear.mockClear();+ now += 101;+ await expect(host.setViewerVisibility('session-a', closeRoute, false)).resolves.toMatchObject({+ ok: true,+ });+ expect(h264FramePump.clear).toHaveBeenCalledWith(instance.instanceId);++ const obsoleteLease = actor.heartbeatOwned('session-a', instance.instanceId);+ const obsoleteRoute = {+ instanceId: obsoleteLease.instanceId,+ generation: obsoleteLease.generation,+ leaseId: obsoleteLease.lease.id,+ };+ await host.setViewerVisibility('session-a', obsoleteRoute, true, 'h264');+ h264FramePump.clear.mockClear();+ now += 101;+ actor.heartbeatOwned('session-a', instance.instanceId);+ await expect(+ host.setViewerVisibility('session-a', obsoleteRoute, false),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ });+ expect(h264FramePump.clear).not.toHaveBeenCalled();+ await host.dispose();+ });++ it('pushes H.264 frames only to the exact current viewer and rejects stale generations', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ let frameSink: ((frame: IOSSimulatorH264Frame) => void | Promise<void>) | null = null;+ const emitFrame = async (frame: IOSSimulatorH264Frame): Promise<void> => {+ const sink = frameSink as ((nextFrame: IOSSimulatorH264Frame) => void | Promise<void>) | null;+ if (!sink) throw new Error('native frame sink was not registered');+ await sink(frame);+ };+ const streamNativeFrames = vi.fn<IOSSimulatorNativeSidecarDriver['streamNativeFrames']>(+ async (options) => {+ frameSink = options.onFrame;+ await new Promise<void>((resolve) => {+ if (options.signal?.aborted) resolve();+ else options.signal?.addEventListener('abort', () => resolve(), { once: true });+ });+ return {+ frameCount: 1,+ byteCount: 4,+ startedAt: '2026-08-07T00:00:00.000Z',+ firstFrameAt: '2026-08-07T00:00:00.001Z',+ endedAt: '2026-08-07T00:00:00.002Z',+ endReason: 'aborted',+ } satisfies IOSSimulatorStreamStats;+ },+ );+ const beginTouch = vi.fn(async () => undefined);+ const moveTouch = vi.fn(async () => undefined);+ const endTouch = vi.fn(async () => undefined);+ const nativeDriver = {+ kind: 'native-sidecar',+ capabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: false,+ continuousInput: true,+ multiTouch: true,+ },+ configureNativeStream: vi.fn(async (profile) => profile),+ streamNativeFrames,+ beginTouch,+ moveTouch,+ endTouch,+ } as unknown as IOSSimulatorNativeSidecarDriver;+ const getWindowSize = vi.fn(async () => ({ width: 393, height: 852 }));+ const configureStream = vi.fn(+ async (_driverSessionId: string, profile: IOSSimulatorStreamProfile) => profile,+ );+ const wdaDriver = {+ getWindowSize,+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ configureStream,+ };+ const capabilityReport = () => ({+ nativeSidecar: { available: true },+ routes: {+ continuousInput: {+ selected: 'native-sidecar',+ fallback: false,+ reason: null,+ },+ stream: {+ h264: {+ selected: 'native-sidecar',+ fallback: false,+ reason: null,+ },+ },+ },+ });+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver: wdaDriver,+ driverSessionId: 'wda-session',+ driverRouter: {+ stream: vi.fn(() => ({+ adapter: 'native-sidecar',+ fallback: false,+ reason: null,+ source: nativeDriver,+ })),+ capabilityReport,+ continuousInput: vi.fn(() => nativeDriver),+ },+ } as unknown as WdaRunningInstance;+ const pushH264Frame = vi.fn();+ const liveViewerIds = new Set([77, 88]);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ driverManager: {+ get: vi.fn(() => running),+ start: vi.fn(async () => running),+ stop: vi.fn(async () => undefined),+ },+ pushH264Frame,+ isViewerWebContentsAlive: (webContentsId) => liveViewerIds.has(webContentsId),+ });+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 77, 'viewer-a'),+ ).resolves.toMatchObject({ ok: true });+ await vi.waitFor(() => expect(streamNativeFrames).toHaveBeenCalledOnce());+ const firstFrame: IOSSimulatorH264Frame = {+ encoding: 'h264',+ format: 'annex-b',+ bytes: Uint8Array.from([0, 0, 0, 1]),+ receivedAt: '2026-08-07T00:00:00.001Z',+ width: 393,+ height: 852,+ orientation: 'PORTRAIT',+ scale: 1,+ colorSpace: 'srgb',+ timestampMicros: 1,+ keyFrame: true,+ };+ await emitFrame(firstFrame);+ expect(pushH264Frame).toHaveBeenCalledOnce();+ expect(pushH264Frame).toHaveBeenCalledWith(+ 77,+ expect.objectContaining({+ instanceId: instance.instanceId,+ generation: instance.generation,+ encoding: 'h264',+ }),+ );++ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-b'),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });+ await emitFrame({ ...firstFrame, timestampMicros: 2 });+ expect(pushH264Frame).toHaveBeenCalledTimes(2);+ expect(pushH264Frame).toHaveBeenLastCalledWith(+ 77,+ expect.objectContaining({ instanceId: instance.instanceId }),+ );++ await expect(+ host.setViewerVisibility('session-a', route, false, 'h264', undefined, 77, 'viewer-a'),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-b'),+ ).resolves.toMatchObject({ ok: true });++ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-c'),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.setViewerVisibility('session-a', route, false, 'h264', undefined, 88, 'viewer-b'),+ ).resolves.toMatchObject({ ok: true, data: { ignored: true } });+ await emitFrame({ ...firstFrame, timestampMicros: 3 });+ expect(pushH264Frame).toHaveBeenCalledTimes(3);+ expect(pushH264Frame).toHaveBeenLastCalledWith(+ 88,+ expect.objectContaining({ instanceId: instance.instanceId }),+ );++ const staleViewportDeferred: {+ resolve: ((value: { width: number; height: number }) => void) | null;+ } = { resolve: null };+ getWindowSize.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ staleViewportDeferred.resolve = resolve;+ }),+ );+ const staleRemount = host.setViewerVisibility(+ 'session-a',+ route,+ true,+ 'h264',+ undefined,+ 88,+ 'viewer-d-stale',+ );+ await vi.waitFor(() => expect(staleViewportDeferred.resolve).not.toBeNull());+ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-e-current'),+ ).resolves.toMatchObject({ ok: true });+ staleViewportDeferred.resolve?.({ width: 393, height: 852 });+ await expect(staleRemount).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });+ await expect(+ host.setViewerVisibility('session-a', route, false, 'h264', undefined, 88, 'viewer-d-stale'),+ ).resolves.toMatchObject({ ok: true, data: { ignored: true } });++ const profileCallsBeforeStaleRequest = configureStream.mock.calls.length;+ await expect(+ host.setViewerStreamProfile('session-a', route, 88, 'viewer-c', {+ framesPerSecond: 10,+ jpegQuality: 45,+ scalingPercent: 70,+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });+ expect(configureStream).toHaveBeenCalledTimes(profileCallsBeforeStaleRequest);++ const staleProfileDeferred: {+ resolve: ((profile: IOSSimulatorStreamProfile) => void) | null;+ } = { resolve: null };+ configureStream.mockImplementationOnce(+ (_driverSessionId, profile) =>+ new Promise((resolve) => {+ staleProfileDeferred.resolve = resolve;+ void profile;+ }),+ );+ const staleProfileRequest = host.setViewerStreamProfile(+ 'session-a',+ route,+ 88,+ 'viewer-e-current',+ { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 },+ );+ await vi.waitFor(() => expect(staleProfileDeferred.resolve).not.toBeNull());+ await expect(+ host.setViewerVisibility(+ 'session-a',+ route,+ true,+ 'h264',+ undefined,+ 88,+ 'viewer-profile-current',+ ),+ ).resolves.toMatchObject({ ok: true });+ staleProfileDeferred.resolve?.({+ framesPerSecond: 10,+ jpegQuality: 45,+ scalingPercent: 70,+ });+ await expect(staleProfileRequest).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });+ await expect(+ host.setViewerStreamProfile('session-a', route, 88, 'viewer-profile-current', {+ framesPerSecond: 20,+ jpegQuality: 70,+ scalingPercent: 100,+ }),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },+ },+ });++ await expect(+ host.updateViewerTouch('session-a', route, 88, {+ gestureId: 'gesture-old-viewer',+ phase: 'begin',+ xRatio: 0.4,+ yRatio: 0.4,+ }),+ ).resolves.toMatchObject({ ok: true });+ liveViewerIds.delete(88);+ liveViewerIds.add(99);+ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 99, 'viewer-f'),+ ).resolves.toMatchObject({ ok: true });+ await vi.waitFor(() =>+ expect(endTouch).toHaveBeenCalledWith(+ 'gesture-old-viewer',+ expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }),+ true,+ ),+ );+ endTouch.mockClear();+ await emitFrame({ ...firstFrame, timestampMicros: 4 });+ expect(pushH264Frame).toHaveBeenCalledTimes(4);+ expect(pushH264Frame).toHaveBeenLastCalledWith(+ 99,+ expect.objectContaining({ instanceId: instance.instanceId }),+ );++ await expect(+ host.updateViewerTouch('session-a', route, 99, {+ gestureId: 'gesture-1',+ phase: 'begin',+ xRatio: 0.5,+ yRatio: 0.5,+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(beginTouch).toHaveBeenCalledTimes(2);+ expect(host.revokeRendererViewer('session-b', 99)).toBe(0);+ expect(host.revokeRendererViewer('session-a', 98)).toBe(0);+ await emitFrame({ ...firstFrame, timestampMicros: 5 });+ expect(pushH264Frame).toHaveBeenCalledTimes(5);++ expect(host.revokeRendererViewer('session-a', 99)).toBe(1);+ await vi.waitFor(() =>+ expect(endTouch).toHaveBeenCalledWith(+ 'gesture-1',+ expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }),+ true,+ ),+ );+ await emitFrame({ ...firstFrame, timestampMicros: 6 });+ expect(pushH264Frame).toHaveBeenCalledTimes(5);++ const current = actor.getOwned('session-a', instance.instanceId);+ await actor.stop({+ sessionId: current.sessionId,+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ });+ await emitFrame({ ...firstFrame, timestampMicros: 7 });+ expect(pushH264Frame).toHaveBeenCalledTimes(5);+ await host.dispose();+ });++ it('selects H.264, falls back to JPEG, and re-arms native streaming on the next viewer request', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const started = await actor.start({+ sessionId: 'session-a',+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ });+ const nativeDriver = {+ kind: 'native-sidecar' as const,+ capabilities: { h264Stream: true },+ };+ const recoveredNativeDriver = {+ kind: 'native-sidecar' as const,+ capabilities: { h264Stream: true },+ };+ const wdaDriver = {+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ configureStream: vi.fn(+ async (+ _sessionId: string,+ profile: { framesPerSecond: number; jpegQuality: number; scalingPercent: number },+ ) => profile,+ ),+ setOrientation: vi.fn(async () => undefined),+ tap: vi.fn(async () => undefined),+ swipe: vi.fn(+ async (+ ...args: [+ string,+ { x: number; y: number },+ { x: number; y: number },+ number,+ AbortSignal?,+ ]+ ) => {+ void args;+ },+ ),+ };+ let nativeAvailable = true;+ let selectedNativeDriver = nativeDriver;+ const routeStatuses: IOSSimulatorPublicRouteStatus[] = [];+ const running = {+ instanceId: started.instanceId,+ simulatorUdid: started.simulatorUdid,+ pid: 42,+ driver: wdaDriver,+ driverRouter: {+ continuousInput: vi.fn(() => null),+ stream: vi.fn(() =>+ nativeAvailable+ ? {+ adapter: 'native-sidecar',+ fallback: false,+ reason: null,+ source: selectedNativeDriver,+ }+ : {+ adapter: 'wda',+ fallback: true,+ reason: 'Native sidecar process is not running.',+ source: wdaDriver,+ },+ ),+ capabilityReport: vi.fn(() => ({+ nativeSidecar: { available: nativeAvailable },+ routes: {+ continuousInput: {+ selected: 'wda',+ fallback: true,+ reason: 'Native continuous input is unavailable.',+ },+ stream: {+ h264: nativeAvailable+ ? {+ selected: 'native-sidecar',+ fallback: false,+ reason: null,+ }+ : {+ selected: 'wda',+ fallback: true,+ reason: 'Native sidecar process is not running.',+ },+ },+ },+ })),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ let jpegSnapshot = {+ instanceId: started.instanceId,+ generation: started.generation,+ state: 'connecting' as 'connecting' | 'reconnecting' | 'disconnected',+ reconnectAttempt: 0,+ latestFrame: null,+ };+ let h264Snapshot = {+ ...jpegSnapshot,+ state: 'connecting' as 'connecting' | 'streaming' | 'disconnected',+ };+ const framePump = {+ setVisible: vi.fn((request: { instanceId: string; generation: number }) => {+ jpegSnapshot = {+ ...jpegSnapshot,+ instanceId: request.instanceId,+ generation: request.generation,+ };+ return jpegSnapshot;+ }),+ snapshot: vi.fn(() => jpegSnapshot),+ clear: vi.fn(),+ };+ const h264FramePump = {+ setVisible: vi.fn((request: { instanceId: string; generation: number }) => {+ h264Snapshot = {+ ...h264Snapshot,+ instanceId: request.instanceId,+ generation: request.generation,+ };+ return h264Snapshot;+ }),+ snapshot: vi.fn(() => h264Snapshot),+ clear: vi.fn(),+ };+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ recoverNativeSidecar: vi.fn(async () => {+ selectedNativeDriver = recoveredNativeDriver;+ nativeAvailable = true;+ return running;+ }),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ h264FramePump: h264FramePump as never,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ pushRouteStatus: (status) => routeStatuses.push(status),+ });+ await host.reconcileOwnership();+ const reconciled = actor.getOwned('session-a', started.instanceId);+ const route = {+ instanceId: reconciled.instanceId,+ generation: reconciled.generation,+ leaseId: reconciled.lease.id,+ };++ await expect(+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 77, 'viewer-token'),+ ).resolves.toMatchObject({+ ok: true,+ data: { stream: { state: 'connecting' } },+ });+ expect(h264FramePump.setVisible).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: started.instanceId,+ driver: nativeDriver,+ profile: {+ encoding: 'h264',+ framesPerSecond: 5,+ scalingPercent: 50,+ orientation: 'PORTRAIT',+ },+ visible: true,+ }),+ );+ expect(framePump.setVisible).toHaveBeenCalledWith(expect.objectContaining({ visible: false }));+ expect(routeStatuses.at(-1)).toMatchObject({+ sessionId: 'session-a',+ instanceId: started.instanceId,+ generation: route.generation,+ stream: {+ adapter: 'native-sidecar',+ encoding: 'h264',+ state: 'detecting',+ reasonCode: 'native-probe-pending',+ },+ });++ h264FramePump.snapshot.mockClear();+ framePump.snapshot.mockClear();+ await expect(host.getLatestFrame('session-a', route, 88)).resolves.toMatchObject({+ ok: false,+ errorCode: 'INSTANCE_NOT_OWNED',+ });+ expect(h264FramePump.snapshot).not.toHaveBeenCalled();+ expect(framePump.snapshot).not.toHaveBeenCalled();++ const fallbackHighProfile = {+ framesPerSecond: 20,+ jpegQuality: 70,+ scalingPercent: 100,+ };+ const experimentalNativeProfile = {+ framesPerSecond: 60,+ scalingPercent: 70,+ };+ await expect(+ host.setViewerStreamProfile(+ 'session-a',+ route,+ 77,+ 'viewer-token',+ fallbackHighProfile,+ experimentalNativeProfile,+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ expect(wdaDriver.configureStream).not.toHaveBeenCalled();++ h264Snapshot = { ...h264Snapshot, state: 'streaming' };+ await expect(+ host.setViewerStreamProfile(+ 'session-a',+ route,+ 77,+ 'viewer-token',+ fallbackHighProfile,+ experimentalNativeProfile,+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ profile: fallbackHighProfile,+ nativeProfile: experimentalNativeProfile,+ },+ });+ expect(wdaDriver.configureStream).toHaveBeenLastCalledWith('wda-session', fallbackHighProfile);+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({+ profile: expect.objectContaining({+ encoding: 'h264',+ framesPerSecond: 60,+ scalingPercent: 70,+ }),+ }),+ );+ await expect(+ host.setViewerStreamProfile('session-a', route, 77, 'viewer-token', {+ framesPerSecond: 60,+ jpegQuality: 70,+ scalingPercent: 70,+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });++ wdaDriver.setOrientation.mockRejectedValueOnce(+ new WdaError(+ 'ORIENTATION_UNSUPPORTED',+ 'The foreground app does not support the requested orientation.',+ 500,+ ),+ );+ const orientationResult = await host.callTool(+ 'set_orientation',+ { ...route, orientation: 'LANDSCAPE' },+ { sessionId: 'session-a', origin: 'user' },+ );+ expect(orientationResult).toMatchObject({+ ok: true,+ data: {+ mode: 'viewer',+ orientation: 'LANDSCAPE',+ viewport: { width: 852, height: 393, orientation: 'LANDSCAPE' },+ },+ });+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({+ profile: expect.objectContaining({ orientation: 'LANDSCAPE' }),+ }),+ );+ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 0.25, yRatio: 0.5 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(wdaDriver.tap).toHaveBeenCalledWith(+ 'wda-session',+ {+ x: 196.5,+ y: 639,+ },+ expect.any(AbortSignal),+ );+ await expect(+ host.callTool(+ 'swipe',+ {+ ...route,+ startXRatio: 0.1,+ startYRatio: 0.2,+ endXRatio: 0.9,+ endYRatio: 0.8,+ durationMs: 250,+ },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const rotatedSwipe = wdaDriver.swipe.mock.lastCall!;+ expect(rotatedSwipe[0]).toBe('wda-session');+ expect(rotatedSwipe[1]!.x).toBeCloseTo(78.6);+ expect(rotatedSwipe[1]!.y).toBeCloseTo(766.8);+ expect(rotatedSwipe[2]!.x).toBeCloseTo(314.4);+ expect(rotatedSwipe[2]!.y).toBeCloseTo(85.2);+ expect(rotatedSwipe[3]).toBe(250);+ expect(rotatedSwipe[4]).toBeInstanceOf(AbortSignal);+ await expect(+ host.callTool(+ 'set_orientation',+ { ...route, orientation: 'PORTRAIT' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ mode: 'device',+ viewport: { width: 393, height: 852, orientation: 'PORTRAIT' },+ },+ });+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({+ profile: expect.objectContaining({+ framesPerSecond: 60,+ scalingPercent: 70,+ orientation: 'PORTRAIT',+ }),+ }),+ );++ h264Snapshot = { ...h264Snapshot, state: 'disconnected' };+ nativeAvailable = false;+ const afterOrientation = actor.getOwned('session-a', started.instanceId);+ const latestRoute = {+ instanceId: afterOrientation.instanceId,+ generation: afterOrientation.generation,+ leaseId: afterOrientation.lease.id,+ };+ await expect(host.getLatestFrame('session-a', latestRoute, 77)).resolves.toMatchObject({+ ok: true,+ data: { stream: { state: 'connecting' } },+ });+ expect(h264FramePump.clear).toHaveBeenCalledWith(started.instanceId);+ expect(framePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({ visible: true }),+ );+ expect(routeStatuses.at(-1)).toMatchObject({+ sessionId: 'session-a',+ instanceId: started.instanceId,+ generation: latestRoute.generation,+ stream: {+ adapter: 'wda',+ encoding: 'jpeg',+ state: 'detecting',+ reasonCode: 'native-stream-disconnected',+ },+ });++ jpegSnapshot = { ...jpegSnapshot, state: 'reconnecting' };+ await expect(host.getLatestFrame('session-a', latestRoute, 77)).resolves.toMatchObject({+ ok: true,+ data: { stream: { state: 'reconnecting' } },+ });+ expect(routeStatuses.at(-1)).toMatchObject({+ stream: {+ adapter: 'wda',+ encoding: 'jpeg',+ state: 'reconnecting',+ reasonCode: 'native-stream-disconnected',+ },+ });++ h264Snapshot = { ...h264Snapshot, state: 'connecting' };+ await expect(+ host.setViewerVisibility(+ 'session-a',+ latestRoute,+ true,+ 'h264',+ undefined,+ 77,+ 'viewer-token',+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: { stream: { state: 'connecting' } },+ });+ expect(driverManager.recoverNativeSidecar).toHaveBeenCalledWith(started.instanceId, {+ rearm: false,+ });+ expect(h264FramePump.setVisible).toHaveBeenLastCalledWith(+ expect.objectContaining({+ driver: recoveredNativeDriver,+ visible: true,+ }),+ );++ await expect(+ host.setViewerVisibility(+ 'session-a',+ latestRoute,+ false,+ 'jpeg',+ undefined,+ 77,+ 'viewer-token',+ ),+ ).resolves.toMatchObject({ ok: true });+ nativeAvailable = false;+ await expect(+ host.setViewerVisibility(+ 'session-a',+ latestRoute,+ true,+ 'h264',+ undefined,+ 77,+ 'viewer-reopened',+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {+ rearm: true,+ });+ });++ it('stops the embedded viewer when the exact external simulator is shut down', async () => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => shutdownDevice),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const initialGeneration = attached.generation;+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler: testResourceScheduler(),+ deviceLivenessIntervalMs: 0,+ });+ const route = {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ };++ const result = await host.setViewerVisibility('session-a', route, true);++ expect(result).toMatchObject({+ ok: true,+ data: {+ instance: {+ generation: initialGeneration + 1,+ lifecycleState: 'stopped',+ healthState: 'healthy',+ errorCode: null,+ },+ stream: null,+ viewport: null,+ },+ });+ expect(lifecycle.bootExact).not.toHaveBeenCalled();+ expect(driverManager.start).not.toHaveBeenCalled();+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);+ });++ it('does not resurrect a viewer when driver startup finishes after an external shutdown', async () => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi+ .fn()+ .mockResolvedValueOnce(READY_REPORT.devices[0]!)+ .mockResolvedValue(shutdownDevice),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ let resolveStart!: (running: WdaRunningInstance) => void;+ let liveRunning: WdaRunningInstance | null = null;+ const running = {+ instanceId: attached.instanceId,+ simulatorUdid: attached.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => liveRunning),+ start: vi.fn(+ () =>+ new Promise<WdaRunningInstance>((resolve) => {+ resolveStart = (value) => {+ liveRunning = value;+ resolve(value);+ };+ }),+ ),+ stop: vi.fn(async () => {+ liveRunning = null;+ }),+ };+ const framePump = {+ setVisible: vi.fn(),+ snapshot: vi.fn(() => null),+ clear: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler: testResourceScheduler(),+ deviceLivenessIntervalMs: 0,+ });+ const route = {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ };++ const viewer = host.setViewerVisibility('session-a', route, true);+ await vi.waitFor(() => expect(driverManager.start).toHaveBeenCalledTimes(1));+ await expect(host.getStatus('session-a')).resolves.toMatchObject({+ ok: true,+ instances: [+ {+ instanceId: attached.instanceId,+ lifecycleState: 'stopped',+ healthState: 'healthy',+ errorCode: null,+ },+ ],+ });++ resolveStart(running);++ await expect(viewer).resolves.toMatchObject({+ ok: true,+ data: {+ instance: {+ instanceId: attached.instanceId,+ lifecycleState: 'stopped',+ healthState: 'healthy',+ errorCode: null,+ },+ stream: null,+ viewport: null,+ },+ });+ expect(framePump.setVisible).not.toHaveBeenCalled();+ expect(driverManager.stop).toHaveBeenCalledTimes(2);+ });++ it('does not unblock builds when an external shutdown overlaps instance activation', async () => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const environment = { ...READY_REPORT, devices: [shutdownDevice] };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => shutdownDevice),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: shutdownDevice,+ });+ const running = {+ instanceId: attached.instanceId,+ simulatorUdid: attached.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(async () => running),+ stop: vi.fn(async () => undefined),+ };+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>();+ const resourceScheduler = testResourceScheduler();+ const runStart = resourceScheduler.runStart.bind(resourceScheduler);+ let signalActivationReady!: () => void;+ const activationReady = new Promise<void>((resolve) => {+ signalActivationReady = resolve;+ });+ let releaseActivation!: () => void;+ const activationGate = new Promise<void>((resolve) => {+ releaseActivation = resolve;+ });+ vi.spyOn(resourceScheduler, 'runStart').mockImplementation(async (instanceId, task) => {+ const result = await runStart(instanceId, task);+ signalActivationReady();+ await activationGate;+ return result;+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ projectBuilder: { build },+ runtime: { inspect: vi.fn(async () => environment) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler,+ deviceLivenessIntervalMs: 0,+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('session-a', attached.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ const startPromise = host.callTool('start_instance', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await activationReady;+ await expect(host.getStatus('session-a')).resolves.toMatchObject({+ ok: true,+ instances: [+ {+ instanceId: attached.instanceId,+ lifecycleState: 'stopped',+ },+ ],+ });+ releaseActivation();++ await expect(startPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ const stopped = actor.getOwned('session-a', attached.instanceId);+ await expect(+ host.callTool(+ 'build_app',+ {+ instanceId: stopped.instanceId,+ generation: stopped.generation,+ leaseId: stopped.lease.id,+ },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ expect(build).not.toHaveBeenCalled();+ await host.dispose();+ });++ it.each(['stop_instance', 'detach_device'] as const)(+ 'cancels driver startup when %s overlaps Simulator boot',+ async (toolName) => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const bootedDevice = { ...READY_REPORT.devices[0]!, state: 'Booted' as const };+ let resolveBoot: (device: typeof bootedDevice) => void = () => undefined;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => bootedDevice),+ bootExact: vi.fn(+ () =>+ new Promise<typeof bootedDevice>((resolve) => {+ resolveBoot = resolve;+ }),+ ),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const detachedCleanups: Array<() => void | Promise<void>> = [];+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ scheduler: {+ schedule: (_delay, task) => {+ detachedCleanups.push(task);+ return () => {+ const index = detachedCleanups.indexOf(task);+ if (index >= 0) detachedCleanups.splice(index, 1);+ };+ },+ },+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: shutdownDevice,+ });+ const startDriver = vi.fn();+ const stopDriver = vi.fn(async () => undefined);+ const resourceScheduler = testResourceScheduler();+ const environment = { ...READY_REPORT, devices: [shutdownDevice] };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: startDriver,+ stop: stopDriver,+ },+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => environment) },+ getSession: vi.fn(async (id) => localSession(id)),+ deviceLivenessIntervalMs: 0,+ });+ await host.reconcileOwnership();+ stopDriver.mockClear();+ const current = actor.getOwned('session-a', attached.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ const start = host.callTool('start_instance', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(lifecycle.bootExact).toHaveBeenCalledOnce());+ const teardown = host.callTool(toolName, route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(stopDriver).toHaveBeenCalledWith(attached.instanceId));+ resolveBoot(bootedDevice);++ await expect(start).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(teardown).resolves.toMatchObject({ ok: true });+ expect(startDriver).not.toHaveBeenCalled();++ if (toolName === 'stop_instance') {+ expect(actor.getOwned('session-a', attached.instanceId)).toMatchObject({+ lifecycleState: 'stopped',+ });+ expect(resourceScheduler.runningCount()).toBe(0);+ } else {+ expect(actor.getOwned('session-a', attached.instanceId)).toMatchObject({+ viewerState: 'detached',+ bootProvenance: 'agent-booted',+ });+ expect(detachedCleanups).toHaveLength(1);+ await detachedCleanups[0]?.();+ expect(actor.list('session-a')).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ }+ await host.dispose();+ },+ );++ it('ignores an exact-device probe that finishes after the binding is detached', async () => {+ let resolveProbe!: (device: (typeof READY_REPORT.devices)[number] | null) => void;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(+ () =>+ new Promise<(typeof READY_REPORT.devices)[number] | null>((resolve) => {+ resolveProbe = resolve;+ }),+ ),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ deviceLivenessIntervalMs: 0,+ });++ const status = host.getStatus('session-a');+ await vi.waitFor(() => expect(lifecycle.findExact).toHaveBeenCalledTimes(1));+ const current = actor.getOwned('session-a', attached.instanceId);+ await actor.detach({+ instanceId: current.instanceId,+ sessionId: current.sessionId,+ generation: current.generation,+ leaseId: current.lease.id,+ });+ resolveProbe(READY_REPORT.devices[0]!);++ await expect(status).resolves.toMatchObject({ ok: true, instances: [] });+ });++ it('marks an unavailable exact simulator as orphaned even when it reports Shutdown', async () => {+ const unavailableDevice = {+ ...READY_REPORT.devices[0]!,+ state: 'Shutdown' as const,+ isAvailable: false,+ availabilityError: 'runtime unavailable',+ };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => unavailableDevice),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ deviceLivenessIntervalMs: 0,+ });++ await expect(host.getStatus('session-a')).resolves.toMatchObject({+ ok: true,+ instances: [+ {+ instanceId: attached.instanceId,+ lifecycleState: 'error',+ healthState: 'degraded',+ errorCode: 'ORPHANED_DEVICE',+ },+ ],+ });+ });++ it('marks an externally deleted exact simulator as orphaned', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => null),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const initialGeneration = attached.generation;+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ deviceLivenessIntervalMs: 0,+ });++ const status = await host.getStatus('session-a');++ expect(status).toMatchObject({+ ok: true,+ instances: [+ {+ instanceId: attached.instanceId,+ generation: initialGeneration + 2,+ lifecycleState: 'error',+ healthState: 'degraded',+ errorCode: 'ORPHANED_DEVICE',+ },+ ],+ });+ expect(lifecycle.bootExact).not.toHaveBeenCalled();+ expect(driverManager.start).not.toHaveBeenCalled();+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);+ });++ it('deduplicates concurrent exact-device liveness probes for one generation', async () => {+ let resolveProbe!: (device: (typeof READY_REPORT.devices)[number] | null) => void;+ const probe = new Promise<(typeof READY_REPORT.devices)[number] | null>((resolve) => {+ resolveProbe = resolve;+ });+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(() => probe),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const initialGeneration = attached.generation;+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ deviceLivenessIntervalMs: 1_000,+ });++ const statuses = Promise.all([host.getStatus('session-a'), host.getStatus('session-a')]);+ await vi.waitFor(() => expect(lifecycle.findExact).toHaveBeenCalledTimes(1));+ resolveProbe({ ...READY_REPORT.devices[0]!, state: 'Booted' });++ await expect(statuses).resolves.toEqual([+ expect.objectContaining({+ ok: true,+ instances: [+ expect.objectContaining({+ instanceId: attached.instanceId,+ generation: initialGeneration + 1,+ lifecycleState: 'ready',+ }),+ ],+ }),+ expect.objectContaining({+ ok: true,+ instances: [+ expect.objectContaining({+ instanceId: attached.instanceId,+ generation: initialGeneration + 1,+ lifecycleState: 'ready',+ }),+ ],+ }),+ ]);+ expect(lifecycle.findExact).toHaveBeenCalledTimes(1);+ });++ it('creates and attaches a Cindy-owned simulator from an exact template device', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(async ({ name, runtimeIdentifier, deviceTypeIdentifier }) => ({+ udid: '2A9D41E0-E031-4AD0-A8B5-847480802E8E',+ name,+ runtimeIdentifier,+ deviceTypeIdentifier,+ })),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const templateDevice = {+ ...READY_REPORT.devices[0]!,+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ };+ const host = createIOSSimulatorHost({+ actor,+ runtime: {+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [templateDevice] })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ await expect(+ host.callTool(+ 'create_instance',+ { templateUdid: templateDevice.udid, name: 'Cindy iPhone' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ instance: {+ simulatorName: 'Cindy iPhone',+ creationProvenance: 'cindy',+ lifecycleState: 'stopped',+ },+ },+ });+ expect(lifecycle.createExact).toHaveBeenCalledWith(+ {+ name: 'Cindy iPhone',+ runtimeIdentifier: templateDevice.runtimeIdentifier,+ deviceTypeIdentifier: templateDevice.deviceTypeIdentifier,+ },+ expect.any(AbortSignal),+ );+ });++ it('aborts and drains create_instance before Host disposal completes', async () => {+ const createdUdid = '2A9D41E0-E031-4AD0-A8B5-847480802E8E';+ let createSignal: AbortSignal | undefined;+ let resolveCreate: (created: {+ udid: string;+ name: string;+ runtimeIdentifier: string;+ deviceTypeIdentifier: string;+ }) => void = () => undefined;+ let resolveDelete: () => void = () => undefined;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(+ (_input, signal) =>+ new Promise<Awaited<ReturnType<IOSSimulatorSimctlLifecycle['createExact']>>>(+ (resolve) => {+ createSignal = signal;+ resolveCreate = resolve;+ },+ ),+ ),+ deleteExact: vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveDelete = resolve;+ }),+ ),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const templateDevice = {+ ...READY_REPORT.devices[0]!,+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: {+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [templateDevice] })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ const call = host.callTool(+ 'create_instance',+ { templateUdid: templateDevice.udid, name: 'Cindy iPhone' },+ { sessionId: 'session-a', origin: 'user' },+ );+ await vi.waitFor(() => expect(createSignal).toBeDefined());++ const disposing = host.dispose();+ expect(createSignal?.aborted).toBe(true);+ resolveCreate({+ udid: createdUdid,+ name: 'Cindy iPhone',+ runtimeIdentifier: templateDevice.runtimeIdentifier,+ deviceTypeIdentifier: templateDevice.deviceTypeIdentifier,+ });+ await vi.waitFor(() => expect(lifecycle.deleteExact).toHaveBeenCalledOnce());+ let disposed = false;+ void disposing.then(() => {+ disposed = true;+ });+ await Promise.resolve();+ expect(disposed).toBe(false);+ resolveDelete();++ await expect(call).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(disposing).resolves.toBeUndefined();+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdUdid, expect.any(AbortSignal));+ expect(actor.listAll()).toEqual([]);+ });++ it('forwards task cancellation to an active simulator control command', async () => {+ let controlSignal: AbortSignal | undefined;+ const bootedDevice = READY_REPORT.devices[0]!;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => bootedDevice),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ setAppearance: vi.fn(+ (_udid, _appearance, signal) =>+ new Promise<void>((_resolve, reject) => {+ controlSignal = signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ ),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'abc',+ device: bootedDevice,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('session-a', instance.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ const changing = host.callTool(+ 'set_appearance',+ { ...route, appearance: 'dark' },+ { sessionId: 'session-a', origin: 'user' },+ );+ await vi.waitFor(() => expect(controlSignal).toBeDefined());++ const cancelling = host.cancelSessionOperations('session-a');+ expect(controlSignal?.aborted).toBe(true);++ await expect(changing).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cancelling).resolves.toBeUndefined();+ expect(lifecycle.setAppearance).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'dark',+ controlSignal,+ );+ await host.dispose();+ });++ it('cancels active WDA snapshot reads with the owning task', async () => {+ let snapshotSignal: AbortSignal | undefined;+ const bootedDevice = READY_REPORT.devices[0]!;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => bootedDevice),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'abc',+ device: bootedDevice,+ });+ const driver = {+ getAccessibilityTree: vi.fn(+ (_sessionId: string | undefined, signal?: AbortSignal) =>+ new Promise<never>((_resolve, reject) => {+ snapshotSignal = signal;+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });+ }),+ ),+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ };+ const running = {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ pid: 42,+ driver,+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('session-a', instance.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ const reading = host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(snapshotSignal).toBeDefined());++ const cancelling = host.cancelSessionOperations('session-a');+ expect(snapshotSignal?.aborted).toBe(true);+ await expect(reading).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cancelling).resolves.toBeUndefined();+ expect(driver.getAccessibilityTree).toHaveBeenCalledWith('wda-session', snapshotSignal);+ await host.dispose();+ });++ it('automatically authorizes the same agent session after attach for start', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const driver = {+ configureStream: vi.fn(+ async (_sessionId: string, profile: IOSSimulatorStreamProfile) => profile,+ ),+ };+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver,+ driverSessionId: 'wda-session',+ }) as unknown as WdaRunningInstance,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ const attachedResult = await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-agent', origin: 'agent' },+ );+ expect(attachedResult).toMatchObject({ ok: true });++ const instance = actor.list('session-agent')[0]!;+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-agent', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(lifecycle.bootExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ });++ it('revokes an attached agent lease even when persisting the denial fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const grantStore = new IOSSimulatorDeviceGrantStore({+ initialGrants: [+ {+ simulatorUdid: READY_REPORT.devices[0]!.udid,+ agentControl: 'allowed',+ screenshotCapture: 'unknown',+ policySource: 'user',+ updatedAt: '2026-08-07T00:00:00.000Z',+ },+ ],+ onChange: () => {+ throw new Error('disk unavailable');+ },+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ grantStore,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-agent', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const instance = actor.list('session-agent')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };++ await expect(+ host.setAgentControlGrant('session-agent', instance.instanceId, 'denied'),+ ).resolves.toMatchObject({ ok: false });+ expect(grantStore.get(instance.simulatorUdid).agentControl).toBe('denied');+ await expect(+ host.callTool('stop_instance', route, {+ sessionId: 'session-agent',+ origin: 'agent',+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'DEVICE_CONTROL_NOT_GRANTED' });+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ });++ it('rechecks a Main-owned elevation after resolving the task and before persistence', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const grantStore = new IOSSimulatorDeviceGrantStore();+ let pauseSessionResolution = false;+ let notifyResolutionStarted: (() => void) | undefined;+ let releaseSessionResolution: (() => void) | undefined;+ const resolutionStarted = new Promise<void>((resolve) => {+ notifyResolutionStarted = resolve;+ });+ const resolutionGate = new Promise<void>((resolve) => {+ releaseSessionResolution = resolve;+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ grantStore,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => {+ if (pauseSessionResolution) {+ notifyResolutionStarted?.();+ await resolutionGate;+ }+ return localSession(id);+ }),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-agent', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const instance = actor.list('session-agent')[0]!;+ let approvalCurrent = true;+ const assertElevationCurrent = vi.fn(() => {+ if (!approvalCurrent) throw new Error('Agent control approval expired');+ });++ pauseSessionResolution = true;+ const elevation = host.setAgentControlGrant(+ 'session-agent',+ instance.instanceId,+ 'allowed',+ assertElevationCurrent,+ );+ await resolutionStarted;+ approvalCurrent = false;+ releaseSessionResolution?.();++ await expect(elevation).resolves.toMatchObject({ ok: false });+ expect(assertElevationCurrent).toHaveBeenCalledOnce();+ expect(grantStore.get(instance.simulatorUdid).agentControl).toBe('unknown');+ });++ it('renews the lease after a slow driver start and opens the embedded viewer', async () => {+ let now = 1_000;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const store = new IOSSimulatorOwnershipStore({+ clock: { now: () => now },+ leaseDurationMs: 60_000,+ });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle,+ clock: { now: () => now },+ });+ const requestViewerFocus = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(async (options) => {+ now = 61_001;+ return {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ }),+ stop: vi.fn(async () => undefined),+ },+ requestViewerFocus,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler: testResourceScheduler(),+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'slow-session', origin: 'user' },+ );+ const attached = actor.list('slow-session')[0]!;+ const result = await host.callTool(+ 'start_instance',+ {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ },+ { sessionId: 'slow-session', origin: 'user' },+ );++ expect(result).toMatchObject({+ ok: true,+ data: {+ instance: {+ instanceId: attached.instanceId,+ lifecycleState: 'ready',+ lease: {+ id: expect.any(String),+ expiresAt: new Date(121_001).toISOString(),+ },+ },+ },+ });+ expect(+ (+ result as {+ ok: true;+ data: { instance: { lease: { id: string } } };+ }+ ).data.instance.lease.id,+ ).not.toBe(attached.lease.id);+ expect(requestViewerFocus).toHaveBeenCalledOnce();+ expect(requestViewerFocus).toHaveBeenCalledWith('slow-session', attached.instanceId);+ });++ it('does not open the embedded viewer when driver startup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const requestViewerFocus = vi.fn();+ const resourceScheduler = testResourceScheduler();+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(async (options: { instanceId: string; simulatorUdid: string }) => {+ return {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ }),+ stop: vi.fn(async () => undefined),+ };+ driverManager.start.mockRejectedValueOnce(new WdaError('UNREACHABLE', 'driver failed'));+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ requestViewerFocus,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' as const }],+ })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler,+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'failed-session', origin: 'user' },+ );+ const attached = actor.list('failed-session')[0]!;+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ },+ { sessionId: 'failed-session', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'DRIVER_DISCONNECTED',+ });+ expect(requestViewerFocus).not.toHaveBeenCalled();+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ const retryInstance = actor.list('failed-session')[0]!;+ expect(retryInstance).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'degraded',+ errorCode: 'WDA_UNAVAILABLE',+ });+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: retryInstance.instanceId,+ generation: retryInstance.generation,+ leaseId: retryInstance.lease.id,+ },+ { sessionId: 'failed-session', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(lifecycle.bootExact).toHaveBeenCalledOnce();+ expect(driverManager.start).toHaveBeenCalledTimes(2);+ expect(resourceScheduler.runningCount()).toBe(1);+ });++ it.each(['booting', 'probe-error'] as const)(+ 'keeps scheduler occupancy when readiness fails with a %s exact probe',+ async (probeMode) => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const bootingDevice = { ...READY_REPORT.devices[0]!, state: 'Booting' as const };+ let findExactCalls = 0;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => {+ findExactCalls += 1;+ if (findExactCalls === 1) return shutdownDevice;+ if (probeMode === 'probe-error') throw new Error('simctl probe failed');+ return bootingDevice;+ }),+ bootExact: vi.fn(async () => {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_BOOT_TIMEOUT',+ 'Device boot started but readiness timed out.',+ true,+ );+ }),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const resourceScheduler = testResourceScheduler();+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: {+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [shutdownDevice] })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler,+ deviceLivenessIntervalMs: 0,+ });++ await host.callTool(+ 'attach_device',+ { udid: shutdownDevice.udid },+ { sessionId: 'boot-timeout-session', origin: 'user' },+ );+ const attached = actor.list('boot-timeout-session')[0]!;+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ },+ { sessionId: 'boot-timeout-session', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_BOOT_TIMEOUT' });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(driverManager.start).not.toHaveBeenCalled();+ expect(actor.list('boot-timeout-session')[0]).toMatchObject({+ lifecycleState: 'error',+ errorCode: 'SIMULATOR_BOOT_TIMEOUT',+ });+ await host.dispose();+ },+ );++ it('cancels an active build before detaching and releasing scheduler capacity', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const actorStart = vi.spyOn(actor, 'start');+ const actorAttach = vi.spyOn(actor, 'attachSerialized');+ const resourceScheduler = testResourceScheduler();+ let running: WdaRunningInstance | null = null;+ let buildSignal: AbortSignal | undefined;+ let finishDetachCleanup!: () => void;+ const discardInstance = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishDetachCleanup = resolve;+ }),+ );+ const build = vi.fn(+ (input: Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]) =>+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>(+ (_, reject) => {+ buildSignal = input.signal;+ input.signal?.addEventListener('abort', () => {+ reject(+ new IOSSimulatorProjectBuildError(+ 'APP_BUILD_FAILED',+ 'cancelled',+ '',+ null,+ false,+ true,+ ),+ );+ });+ },+ ),+ );+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler,+ projectBuilder: { build },+ driverManager: {+ get: vi.fn(() => running),+ start: vi.fn(async (options) => {+ running = {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {} as WdaRunningInstance['driver'],+ driverSessionId: 'wda-session',+ } as WdaRunningInstance;+ return running;+ }),+ stop: vi.fn(async () => {+ running = null;+ }),+ },+ mediaCapture: {+ discardInstance,+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });++ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ actorAttach.mockClear();+ expect(resourceScheduler.runningCount()).toBe(1);+ const attached = actor.list('session-a')[0]!;+ const route = {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ };+ const buildPromise = host.callTool('build_app', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());++ const detachPromise = host.callTool('detach_device', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(discardInstance).toHaveBeenCalledOnce());+ expect(buildSignal?.aborted).toBe(true);+ await expect(buildPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(+ host.callTool('build_app', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ await expect(+ host.callTool('start_instance', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ expect(build).toHaveBeenCalledOnce();+ expect(actorStart).not.toHaveBeenCalled();+ expect(actorAttach).not.toHaveBeenCalled();+ finishDetachCleanup();+ await expect(detachPromise).resolves.toMatchObject({ ok: true });+ expect(resourceScheduler.runningCount()).toBe(0);+ await host.dispose();+ });++ it('waits for a racing start and shuts down the device before cleanup returns', async () => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const bootedDevice = { ...READY_REPORT.devices[0]!, state: 'Booted' as const };+ let resolveBoot: (device: typeof bootedDevice) => void = () => undefined;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => bootedDevice),+ bootExact: vi.fn(+ () =>+ new Promise<typeof bootedDevice>((resolve) => {+ resolveBoot = resolve;+ }),+ ),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: shutdownDevice,+ });+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const resourceScheduler = testResourceScheduler();+ const environment = { ...READY_REPORT, devices: [shutdownDevice] };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ resourceScheduler,+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => environment) },+ getSession: vi.fn(async (id) => localSession(id)),+ });+ await host.reconcileOwnership();+ driverManager.stop.mockClear();+ const current = actor.getOwned('session-a', attached.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ const start = host.callTool('start_instance', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(lifecycle.bootExact).toHaveBeenCalledOnce());+ const cleanup = host.cleanupRemovedSession('session-a');+ resolveBoot(bootedDevice);++ await expect(start).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cleanup).resolves.toBeUndefined();+ expect(driverManager.start).not.toHaveBeenCalled();+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ attached.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.list('session-a')).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ });++ it('waits for a racing viewer open before clearing its runtime projection', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ let resolveWindowSize: (size: { width: number; height: number }) => void = () => undefined;+ const running = {+ instanceId: attached.instanceId,+ simulatorUdid: attached.simulatorUdid,+ pid: 42,+ driver: {+ getWindowSize: vi.fn(+ () =>+ new Promise<{ width: number; height: number }>((resolve) => {+ resolveWindowSize = resolve;+ }),+ ),+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const framePump = {+ setVisible: vi.fn(),+ snapshot: vi.fn(() => null),+ clear: vi.fn(),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ framePump: framePump as never,+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resourceScheduler: testResourceScheduler(),+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('session-a', attached.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ const viewer = host.setViewerVisibility('session-a', route, true, 'jpeg');+ await vi.waitFor(() => expect(running.driver.getWindowSize).toHaveBeenCalledOnce());+ const cleanup = host.cleanupRemovedSession('session-a');+ await Promise.resolve();+ expect(driverManager.stop).not.toHaveBeenCalled();+ resolveWindowSize({ width: 393, height: 852 });++ await expect(viewer).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cleanup).resolves.toBeUndefined();+ expect(framePump.setVisible).not.toHaveBeenCalled();+ expect(framePump.clear).toHaveBeenCalledWith(attached.instanceId);+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);+ expect(actor.list('session-a')).toEqual([]);+ });++ it('waits for a racing attach and removes its partially started runtime', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ let resolveDriverStart: (running: WdaRunningInstance) => void = () => undefined;+ let liveRunning: WdaRunningInstance | null = null;+ const driverManager = {+ get: vi.fn(() => liveRunning),+ start: vi.fn(+ () =>+ new Promise<WdaRunningInstance>((resolve) => {+ resolveDriverStart = (running) => {+ liveRunning = running;+ resolve(running);+ };+ }),+ ),+ stop: vi.fn(async () => {+ liveRunning = null;+ }),+ };+ const resourceScheduler = testResourceScheduler();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ resourceScheduler,+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });+ await host.reconcileOwnership();++ const attach = host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ await vi.waitFor(() => expect(driverManager.start).toHaveBeenCalledOnce());+ const attached = actor.list('session-a')[0]!;+ const cleanup = host.cleanupRemovedSession('session-a');+ resolveDriverStart({+ instanceId: attached.instanceId,+ simulatorUdid: attached.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance);++ await expect(attach).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cleanup).resolves.toBeUndefined();+ expect(actor.list('session-a')).toEqual([]);+ expect(resourceScheduler.runningCount()).toBe(0);+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ });++ it('waits for a racing create and deletes the late Cindy-owned device', async () => {+ const template = {+ ...READY_REPORT.devices[0]!,+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ };+ const createdDevice = {+ ...template,+ udid: '2A9D41E0-E031-4AD0-A8B5-847480802E8E',+ name: 'Late Cindy iPhone',+ state: 'Shutdown' as const,+ };+ let resolveCreate: (device: {+ udid: string;+ name: string;+ runtimeIdentifier: string;+ deviceTypeIdentifier: string;+ }) => void = () => undefined;+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => createdDevice),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(+ (_input: Parameters<IOSSimulatorSimctlLifecycle['createExact']>[0]) =>+ new Promise<Awaited<ReturnType<IOSSimulatorSimctlLifecycle['createExact']>>>(+ (resolve) => {+ resolveCreate = resolve;+ },+ ),+ ),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const environment = { ...READY_REPORT, devices: [template] };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ runtime: { inspect: vi.fn(async () => environment) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });+ await host.reconcileOwnership();++ const create = host.callTool(+ 'create_instance',+ { templateUdid: template.udid, name: createdDevice.name },+ { sessionId: 'session-a', origin: 'user' },+ );+ await vi.waitFor(() => expect(lifecycle.createExact).toHaveBeenCalledOnce());+ const cleanup = host.cleanupRemovedSession('session-a');+ resolveCreate({+ udid: createdDevice.udid,+ name: createdDevice.name,+ runtimeIdentifier: createdDevice.runtimeIdentifier,+ deviceTypeIdentifier: createdDevice.deviceTypeIdentifier!,+ });++ await expect(create).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cleanup).resolves.toBeUndefined();+ expect(actor.list('session-a')).toEqual([]);+ expect(lifecycle.findExact).not.toHaveBeenCalled();+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdDevice.udid, expect.any(AbortSignal));+ });++ it('does not register a build after its task is archived at the reconcile boundary', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ let armed = false;+ let armedReadCount = 0;+ let signalFinalRead!: () => void;+ const finalReadStarted = new Promise<void>((resolve) => {+ signalFinalRead = resolve;+ });+ let resolveFinalRead!: () => void;+ const getSession = vi.fn(async (id: string) => {+ const snapshot = { ...localSession(id), status: 'active' as const };+ if (armed && ++armedReadCount === 2) {+ signalFinalRead();+ await new Promise<void>((resolve) => {+ resolveFinalRead = resolve;+ });+ }+ return snapshot;+ });+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>();+ const discardSession = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession,+ projectBuilder: { build },+ mediaCapture: {+ discardSession,+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });++ await host.reconcileOwnership();+ const instance = actor.list('session-a')[0]!;+ armed = true;++ const buildPromise = host.callTool(+ 'build_app',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-a', origin: 'user' },+ );+ await finalReadStarted;+ await host.cancelSessionOperations('session-a');+ expect(discardSession).toHaveBeenCalledOnce();+ expect(discardSession).toHaveBeenCalledWith('session-a');+ resolveFinalRead();++ await expect(buildPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ expect(build).not.toHaveBeenCalled();+ await host.dispose();+ });++ it('does not register a recording after its task cancellation has completed', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ let armed = false;+ let armedReadCount = 0;+ let signalFinalRead!: () => void;+ const finalReadStarted = new Promise<void>((resolve) => {+ signalFinalRead = resolve;+ });+ let resolveFinalRead!: () => void;+ const getSession = vi.fn(async (id: string) => {+ const snapshot = { ...localSession(id), status: 'active' as const };+ if (armed && ++armedReadCount === 2) {+ signalFinalRead();+ await new Promise<void>((resolve) => {+ resolveFinalRead = resolve;+ });+ }+ return snapshot;+ });+ const startRecording = vi.fn(async () => ({+ recordingId: 'late-recording',+ startedAt: new Date().toISOString(),+ }));+ const discardSession = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession,+ mediaCapture: {+ startRecording,+ discardSession,+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });++ await host.reconcileOwnership();+ const instance = actor.list('session-a')[0]!;+ armed = true;+ const recordingPromise = host.callTool(+ 'start_recording',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-a', origin: 'user' },+ );+ await finalReadStarted;+ await host.cancelSessionOperations('session-a');+ resolveFinalRead();++ await expect(recordingPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ expect(startRecording).not.toHaveBeenCalled();+ expect(discardSession).toHaveBeenCalledOnce();+ await host.dispose();+ });++ it('does not capture a screenshot after its task cancellation has completed', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ let armed = false;+ let armedReadCount = 0;+ let signalFinalRead!: () => void;+ const finalReadStarted = new Promise<void>((resolve) => {+ signalFinalRead = resolve;+ });+ let resolveFinalRead!: () => void;+ const getSession = vi.fn(async (id: string) => {+ const snapshot = { ...localSession(id), status: 'active' as const };+ if (armed && ++armedReadCount === 2) {+ signalFinalRead();+ await new Promise<void>((resolve) => {+ resolveFinalRead = resolve;+ });+ }+ return snapshot;+ });+ const takeScreenshot = vi.fn(async () => ({+ hash: 'a'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: 8,+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['ref-a'],+ }));+ const discardSession = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession,+ mediaCapture: {+ takeScreenshot,+ discardSession,+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });++ await host.reconcileOwnership();+ const instance = actor.list('session-a')[0]!;+ armed = true;+ const screenshotPromise = host.callTool(+ 'take_screenshot',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-a', origin: 'user' },+ );+ await finalReadStarted;+ await host.cancelSessionOperations('session-a');+ resolveFinalRead();++ await expect(screenshotPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ expect(takeScreenshot).not.toHaveBeenCalled();+ expect(discardSession).toHaveBeenCalledOnce();+ await host.dispose();+ });++ it('aborts and drains an active simulator mutation before task cancellation returns', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ mediaCapture: {+ discardSession: vi.fn(async () => undefined),+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });+ let mutationSignal: AbortSignal | undefined;+ const active = actor+ .runMutation(+ {+ sessionId: instance.sessionId,+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ async (_current, signal) => {+ mutationSignal = signal;+ await new Promise<void>((resolve) => {+ signal.addEventListener('abort', () => resolve(), { once: true });+ });+ },+ 'user',+ )+ .catch((error: unknown) => error);+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());++ await expect(host.cancelSessionOperations('session-a')).resolves.toBeUndefined();+ expect(mutationSignal?.aborted).toBe(true);+ await expect(active).resolves.toMatchObject({ code: 'MUTATION_CANCELLED' });+ await host.dispose();+ });++ it('does not block task removal when recording cleanup fails', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const discardSession = vi.fn(async () => {+ throw new Error('recording process did not exit');+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ mediaCapture: {+ discardSession,+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });++ await expect(host.cancelSessionOperations('session-a')).resolves.toBeUndefined();+ expect(discardSession).toHaveBeenCalledWith('session-a');+ await host.dispose();+ });++ it('rejects queued screenshot and recording registration after instance teardown begins', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ let markActiveStarted: () => void = () => undefined;+ let releaseActive: () => void = () => undefined;+ const activeStarted = new Promise<void>((resolve) => {+ markActiveStarted = resolve;+ });+ const activeGate = new Promise<void>((resolve) => {+ releaseActive = resolve;+ });+ let markDiscardStarted: () => void = () => undefined;+ let releaseDiscard: () => void = () => undefined;+ const discardStarted = new Promise<void>((resolve) => {+ markDiscardStarted = resolve;+ });+ const discardGate = new Promise<void>((resolve) => {+ releaseDiscard = resolve;+ });+ let discardCalls = 0;+ const discardInstance = vi.fn(async () => {+ discardCalls += 1;+ if (discardCalls !== 1) return;+ markDiscardStarted();+ await discardGate;+ });+ const takeScreenshot = vi.fn(async () => ({+ hash: 'a'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: 8,+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['ref-a'],+ }));+ const startRecording = vi.fn(async () => ({+ recordingId: 'late-recording',+ startedAt: new Date().toISOString(),+ }));+ const openUrlExact = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ },+ mediaCapture: {+ takeScreenshot,+ startRecording,+ discardInstance,+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ appLifecycle: {+ inspectArtifact: vi.fn(),+ installExact: vi.fn(),+ launchExact: vi.fn(),+ terminateExact: vi.fn(),+ openUrlExact,+ },+ });++ await host.reconcileOwnership();+ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ await expect(+ host.setAgentControlGrant('session-a', instance.instanceId, 'allowed'),+ ).resolves.toMatchObject({ ok: true });+ const active = actor.runMutation(+ { sessionId: 'session-a', ...route },+ async () => {+ markActiveStarted();+ await activeGate;+ },+ 'agent',+ );+ await activeStarted;++ const screenshot = host.callTool('take_screenshot', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ const recording = host.callTool('start_recording', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ await vi.waitFor(() =>+ expect(actor.mutationState(instance.instanceId)).toMatchObject({ queuedAgentMutations: 2 }),+ );++ const stopping = host.callTool('stop_instance', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await discardStarted;+ await expect(+ host.callTool(+ 'open_url',+ { ...route, url: 'demo://teardown-race' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });+ expect(openUrlExact).not.toHaveBeenCalled();+ releaseActive();++ await expect(screenshot).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(recording).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ expect(takeScreenshot).not.toHaveBeenCalled();+ expect(startRecording).not.toHaveBeenCalled();++ releaseDiscard();+ await expect(stopping).resolves.toMatchObject({ ok: true });+ await expect(active).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });+ await host.dispose();+ });++ it.each(['stop_instance', 'detach_device'] as const)(+ 'completes %s even when pending media cleanup times out',+ async (toolName) => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const instance = actor.attach({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ bootProvenance: 'preexisting',+ });+ const discardInstance = vi+ .fn()+ .mockRejectedValueOnce(new Error('raw media ingest did not become idle'))+ .mockResolvedValue(undefined);+ const stopDriver = vi.fn(async () => undefined);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: stopDriver,+ },+ mediaCapture: {+ discardInstance,+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ });+ await host.reconcileOwnership();+ const current = actor.getOwned('session-a', instance.instanceId);+ const route = {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ };++ await expect(+ host.callTool(toolName, route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ mediaCleanupWarning: { code: 'MEDIA_CLEANUP_INCOMPLETE' },+ },+ });+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);+ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);+ if (toolName === 'stop_instance') {+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(actor.list('session-a')[0]).toMatchObject({ lifecycleState: 'stopped' });+ } else {+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(actor.list('session-a')).toEqual([]);+ }+ await host.dispose();+ },+ );++ it('shares exact attachment and lifecycle state while rejecting another session', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ setAppearance: vi.fn(async () => undefined),+ setIncreaseContrast: vi.fn(async () => undefined),+ setContentSize: vi.fn(async () => undefined),+ setLocation: vi.fn(async () => undefined),+ startLocationRoute: vi.fn(async () => undefined),+ clearLocation: vi.fn(async () => undefined),+ setPrivacy: vi.fn(async () => undefined),+ pushNotification: vi.fn(async () => undefined),+ setStatusBar: vi.fn(async () => undefined),+ clearStatusBar: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const driver = {+ kind: 'wda' as const,+ probe: vi.fn(async (...args: [signal?: AbortSignal]) => {+ void args;+ return { ready: true, message: null };+ }),+ getAccessibilityTree: vi.fn(async (...args: [sessionId?: string, signal?: AbortSignal]) => {+ void args;+ return {+ capturedAt: '2026-07-22T12:00:00.000Z',+ tree: {+ type: 'XCUIElementTypeButton',+ label: 'Continue',+ enabled: true,+ visible: true,+ rect: { x: 20, y: 40, width: 100, height: 40 },+ },+ };+ }),+ getWindowSize: vi.fn(async (...args: [sessionId?: string, signal?: AbortSignal]) => {+ void args;+ return { width: 393, height: 852 };+ }),+ getOrientation: vi.fn(async (...args: [sessionId?: string, signal?: AbortSignal]) => {+ void args;+ return 'PORTRAIT' as const;+ }),+ configureStream: vi.fn(+ async (+ ...args: [+ string,+ { framesPerSecond: number; jpegQuality: number; scalingPercent: number },+ ]+ ) => args[1],+ ),+ tap: vi.fn(async () => undefined),+ swipe: vi.fn(+ async (...args: [string, { x: number; y: number }, { x: number; y: number }, number]) => {+ void args;+ },+ ),+ typeText: vi.fn(async () => undefined),+ home: vi.fn(async () => undefined),+ setOrientation: vi.fn(async () => undefined),+ lock: vi.fn(async () => undefined),+ unlock: vi.fn(async () => undefined),+ };+ const nativeInput = {+ capabilities: {+ continuousInput: true,+ multiTouch: true,+ },+ touchPath: vi.fn(async (...args: [IOSSimulatorTouchPoint[], AbortSignal?]) => {+ void args;+ }),+ touch2Path: vi.fn(+ async (...args: [IOSSimulatorTouchPoint[], IOSSimulatorTouchPoint[], AbortSignal?]) => {+ void args;+ },+ ),+ beginTouch: vi.fn(async () => undefined),+ moveTouch: vi.fn(async () => undefined),+ endTouch: vi.fn(async () => undefined),+ };+ let nativeInputEnabled = false;+ let running: WdaRunningInstance | null = null;+ const nativeAdmission = evaluateIOSSimulatorNativeCapabilityAdmission({+ policy: createIOSSimulatorNativeDevelopmentAdmissionPolicy({+ enableH264Stream: true,+ }),+ detectedCapabilities: {+ accessibility: false,+ sessions: false,+ jpegStream: false,+ h264Stream: true,+ bgraStream: true,+ discreteInput: false,+ continuousInput: false,+ multiTouch: false,+ },+ processState: 'parked',+ now: () => new Date('2026-07-25T00:00:00.000Z'),+ });+ const driverManager = {+ get: vi.fn(() => running),+ start: vi.fn(async (options) => {+ running = {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver,+ driverRouter: {+ continuousInput: vi.fn(() => (nativeInputEnabled ? nativeInput : null)),+ },+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ return running;+ }),+ stop: vi.fn(async () => {+ running = null;+ }),+ diagnostics: vi.fn(() => ({+ running: true,+ logTail: '',+ capabilityReport: null,+ nativeSidecar: {+ running: false,+ state: 'parked' as const,+ crashCount: 3,+ probe: null,+ lastFailure: 'IOSurface lookup failed at /Users/example/private/SimulatorKit.framework',+ lastTermination: {+ reasonCode: 'process-exit' as const,+ message: 'Native sidecar exited beside /Users/example/private/SimulatorKit.framework',+ exitCode: 23,+ signal: null,+ occurredAt: '2026-07-25T00:00:01.000Z',+ stderrTail:+ 'token=private-value VideoToolbox failed at /Users/example/private/CoreSimulator.framework',+ },+ admission: nativeAdmission,+ },+ })),+ };+ const discardInstance = vi.fn(async () => undefined);+ const mediaCapture = {+ discardInstance,+ captureScreenshotBytes: vi.fn(async () =>+ Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',+ 'base64',+ ),+ ),+ takeScreenshot: vi.fn(async () => ({+ hash: 'a'.repeat(64),+ ext: '.png',+ mimeType: 'image/png',+ bytes: 8,+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,+ deduplicated: false,+ refIds: ['ref-screenshot'],+ })),+ startRecording: vi.fn(),+ stopRecording: vi.fn(),+ } as unknown as IOSSimulatorMediaCaptureAdapter;+ const resourceScheduler = testResourceScheduler();+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ mediaCapture,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ const attached = await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ expect(attached).toMatchObject({+ ok: true,+ data: { instance: { sessionId: 'session-a', lifecycleState: 'ready' } },+ });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(attached).not.toHaveProperty('data.instance.worktreeRoot');+ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-b' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_ATTACHED_ELSEWHERE' });+ await expect(+ host.callTool('list_instances', {}, { sessionId: 'session-a' }),+ ).resolves.toMatchObject({ ok: true, data: { instances: [{ sessionId: 'session-a' }] } });++ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ await expect(+ host.setViewerVisibility('session-a', route, true, 'jpeg', undefined, 17, 'viewer-token'),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.setViewerStreamProfile('session-a', route, 17, 'viewer-token', {+ framesPerSecond: 10,+ jpegQuality: 45,+ scalingPercent: 70,+ }),+ ).resolves.toMatchObject({+ ok: true,+ data: { profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 } },+ });+ await expect(+ host.callTool('stop_instance', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'DEVICE_CONTROL_NOT_GRANTED' });+ await expect(+ host.setAgentControlGrant('session-a', instance.instanceId, 'allowed'),+ ).resolves.toMatchObject({ ok: true, data: { grant: { agentControl: 'allowed' } } });+ const screenResult = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ expect(screenResult).toMatchObject({+ ok: true,+ data: { screenMap: { generation: instance.generation, elements: [{ label: 'Continue' }] } },+ });+ expect(driver.getAccessibilityTree).toHaveBeenLastCalledWith(+ 'wda-session',+ expect.any(AbortSignal),+ );+ expect(driver.getWindowSize).toHaveBeenLastCalledWith('wda-session', expect.any(AbortSignal));+ expect(driver.getOrientation).toHaveBeenLastCalledWith('wda-session', expect.any(AbortSignal));+ const doctor = await host.callTool('doctor', {}, { sessionId: 'session-a', origin: 'agent' });+ expect(doctor).toMatchObject({+ ok: true,+ data: {+ availability: {+ ready: true,+ instanceCount: 1,+ runningInstanceCount: 1,+ tools: {+ drag: { state: 'available', backend: 'wda' },+ touch_path: { state: 'unavailable', reasonCode: 'NATIVE_HID_NOT_ADMITTED' },+ },+ },+ resource: { runningCount: 1 },+ },+ });+ expect(JSON.stringify(doctor)).not.toContain('/Users/example');+ expect(JSON.stringify(doctor)).not.toContain('SimulatorKit.framework');+ const capturedState = await host.callTool('capture_state', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ expect(capturedState).toMatchObject({+ ok: true,+ data: {+ driverDiagnostics: {+ nativeSidecar: {+ state: 'parked',+ lastFailure: 'Native sidecar is unavailable.',+ lastTermination: {+ reasonCode: 'process-exit',+ exitCode: 23,+ signal: null,+ occurredAt: '2026-07-25T00:00:01.000Z',+ stderrTail: 'token=<redacted> VideoToolbox failed at <redacted-path>',+ },+ admission: {+ generatedAt: '2026-07-25T00:00:00.000Z',+ processState: 'parked',+ launch: { active: false, reasonCode: 'PROCESS_PARKED' },+ capabilities: {+ h264Stream: { active: false, reasonCode: 'PROCESS_PARKED' },+ },+ },+ },+ },+ },+ });+ expect(driver.probe).toHaveBeenLastCalledWith(expect.any(AbortSignal));+ expect(driver.getOrientation).toHaveBeenLastCalledWith('wda-session', expect.any(AbortSignal));+ expect(driver.getAccessibilityTree).toHaveBeenLastCalledWith(+ 'wda-session',+ expect.any(AbortSignal),+ );+ expect(JSON.stringify(capturedState)).not.toContain('/Users/example');+ expect(JSON.stringify(capturedState)).not.toContain('SimulatorKit.framework');+ expect(JSON.stringify(capturedState)).not.toContain('private-value');+ expect(JSON.stringify(capturedState)).not.toContain('CoreSimulator.framework');+ const baseline = (screenResult as { ok: true; data: { screenMap: unknown } }).data.screenMap;+ await expect(+ host.callTool(+ 'compare_screen_maps',+ { ...route, baseline },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: { diff: { unchangedCount: 1, added: [], removed: [], changed: [] } },+ });+ await expect(+ host.callTool('take_screenshot', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({+ ok: true,+ data: { mediaUrl: expect.stringMatching(/^cindy-media:\/\/blobs\//) },+ });+ expect(mediaCapture.takeScreenshot).toHaveBeenCalledWith({+ simulatorUdid: instance.simulatorUdid,+ sessionId: 'session-a',+ instanceId: instance.instanceId,+ source: 'agent',+ signal: expect.any(AbortSignal),+ });+ const visualBaseline = await host.callTool('capture_visual_baseline', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ expect(visualBaseline).toMatchObject({+ ok: true,+ data: { baselineId: expect.any(String), bytes: expect.any(Number) },+ });+ const baselineId = (visualBaseline as { ok: true; data: { baselineId: string } }).data+ .baselineId;+ await expect(+ host.callTool(+ 'visual_diff',+ { ...route, baselineId, threshold: 16 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: { diff: { comparedPixels: 1, differentPixels: 0, differenceRatio: 0 } },+ });+ expect(mediaCapture.captureScreenshotBytes).toHaveBeenNthCalledWith(1, {+ simulatorUdid: instance.simulatorUdid,+ signal: expect.any(AbortSignal),+ });+ expect(mediaCapture.captureScreenshotBytes).toHaveBeenNthCalledWith(2, {+ simulatorUdid: instance.simulatorUdid,+ signal: expect.any(AbortSignal),+ });+ await expect(+ host.callTool(+ 'audit_accessibility',+ { ...route, maxViolations: 10 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ audit: {+ generation: instance.generation,+ checkedElements: 1,+ violationCount: 0,+ violations: [],+ },+ },+ });+ await expect(+ host.callTool(+ 'set_appearance',+ { ...route, appearance: 'dark' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_appearance' } });+ await expect(+ host.callTool(+ 'set_increase_contrast',+ { ...route, enabled: true },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_increase_contrast' } });+ await expect(+ host.callTool(+ 'set_content_size',+ { ...route, contentSize: 'accessibility-extra-large' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_content_size' } });+ await expect(+ host.callTool(+ 'set_location',+ { ...route, latitude: 31.23, longitude: 121.47 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_location' } });+ await expect(+ host.callTool(+ 'start_location_route',+ {+ ...route,+ waypoints: [+ { latitude: 31.23, longitude: 121.47 },+ { latitude: 31.24, longitude: 121.48 },+ ],+ speedMetersPerSecond: 8,+ intervalSeconds: 1,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'start_location_route' } });+ await expect(+ host.callTool('clear_location', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'clear_location' } });+ await expect(+ host.callTool(+ 'set_privacy',+ { ...route, action: 'grant', service: 'photos', bundleId: 'com.example.app' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_privacy' } });+ await expect(+ host.callTool(+ 'push_notification',+ { ...route, bundleId: 'com.example.app', payload: { aps: { alert: 'Hi' } } },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'push_notification' } });+ await expect(+ host.callTool(+ 'set_status_bar',+ { ...route, time: '9:41', wifiBars: 3 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'set_status_bar' } });+ await expect(+ host.callTool('clear_status_bar', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true, data: { interaction: 'clear_status_bar' } });+ expect(lifecycle.setAppearance).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'dark',+ expect.any(AbortSignal),+ );+ expect(lifecycle.setIncreaseContrast).toHaveBeenCalledWith(+ instance.simulatorUdid,+ true,+ expect.any(AbortSignal),+ );+ expect(lifecycle.setContentSize).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'accessibility-extra-large',+ expect.any(AbortSignal),+ );+ expect(lifecycle.setLocation).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 31.23,+ 121.47,+ expect.any(AbortSignal),+ );+ expect(lifecycle.startLocationRoute).toHaveBeenCalledWith(+ instance.simulatorUdid,+ {+ waypoints: [+ { latitude: 31.23, longitude: 121.47 },+ { latitude: 31.24, longitude: 121.48 },+ ],+ speedMetersPerSecond: 8,+ intervalSeconds: 1,+ distanceMeters: undefined,+ },+ expect.any(AbortSignal),+ );+ expect(lifecycle.clearLocation).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ expect(lifecycle.setPrivacy).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'grant',+ 'photos',+ 'com.example.app',+ expect.any(AbortSignal),+ );+ expect(lifecycle.pushNotification).toHaveBeenCalledWith(+ instance.simulatorUdid,+ 'com.example.app',+ { aps: { alert: 'Hi' } },+ expect.any(AbortSignal),+ );+ expect(lifecycle.setStatusBar).toHaveBeenCalledWith(+ instance.simulatorUdid,+ {+ time: '9:41',+ wifiBars: 3,+ },+ expect.any(AbortSignal),+ );+ expect(lifecycle.clearStatusBar).toHaveBeenCalledWith(+ instance.simulatorUdid,+ expect.any(AbortSignal),+ );+ const refreshedScreenResult = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!refreshedScreenResult.ok) throw new Error('expected a refreshed screen map');+ let screenMap = (+ refreshedScreenResult.data as {+ screenMap: { snapshotId: string; elements: Array<{ elementId: string }> };+ }+ ).screenMap;+ driver.getAccessibilityTree.mockResolvedValueOnce({+ capturedAt: '2026-07-22T12:00:01.000Z',+ tree: {+ type: 'XCUIElementTypeButton',+ label: 'Done',+ enabled: true,+ visible: true,+ rect: { x: 20, y: 40, width: 100, height: 40 },+ },+ });+ await expect(+ host.callTool(+ 'tap',+ {+ ...route,+ snapshotId: screenMap.snapshotId,+ elementId: screenMap.elements[0]!.elementId,+ observeAfter: 'immediate',+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ interaction: 'tap',+ screenMapInvalidated: false,+ observation: {+ mode: 'immediate',+ screenMap: { elements: [{ label: 'Done' }] },+ },+ },+ });++ driver.getAccessibilityTree.mockResolvedValueOnce({+ capturedAt: '2026-07-22T12:00:02.000Z',+ tree: {+ type: 'XCUIElementTypeStaticText',+ label: 'Loading',+ enabled: true,+ visible: true,+ rect: { x: 20, y: 40, width: 100, height: 40 },+ },+ });+ driver.getAccessibilityTree.mockResolvedValueOnce({+ capturedAt: '2026-07-22T12:00:03.000Z',+ tree: {+ type: 'XCUIElementTypeButton',+ label: 'Done',+ enabled: true,+ visible: true,+ rect: { x: 20, y: 40, width: 100, height: 40 },+ },+ });+ await expect(+ host.callTool(+ 'wait_for_ui',+ {+ ...route,+ condition: { kind: 'element_exists', selector: { labelContains: 'Done' } },+ timeoutMs: 1_000,+ pollIntervalMs: 100,+ stableForMs: 100,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ timedOut: false,+ screenMap: { elements: [{ label: 'Done' }] },+ },+ });+ await expect(+ host.callTool(+ 'wait_for_ui',+ {+ ...route,+ condition: { kind: 'element_exists', selector: { labelContains: 'Never appears' } },+ timeoutMs: 100,+ pollIntervalMs: 100,+ stableForMs: 100,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'UI_WAIT_TIMEOUT' });+ expect(actor.mutationState(instance.instanceId)).toMatchObject({+ activeSource: null,+ takeoverPending: false,+ });++ const postObservationScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!postObservationScreen.ok) throw new Error('expected post-observation screen map');+ screenMap = (+ postObservationScreen.data as {+ screenMap: { snapshotId: string; elements: Array<{ elementId: string }> };+ }+ ).screenMap;+ const tapArgs = {+ ...route,+ snapshotId: screenMap.snapshotId,+ elementId: screenMap.elements[0]!.elementId,+ };+ await expect(+ host.callTool('tap', tapArgs, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.tap).toHaveBeenCalledWith(+ 'wda-session',+ { x: 70, y: 60 },+ expect.any(AbortSignal),+ );+ await expect(+ host.callTool('tap', tapArgs, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'STALE_UI_SNAPSHOT' });++ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 0.5, yRatio: 0.25 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.tap).toHaveBeenLastCalledWith(+ 'wda-session',+ { x: 196.5, y: 213 },+ expect.any(AbortSignal),+ );+ await expect(+ host.callTool(+ 'swipe',+ {+ ...route,+ startXRatio: 0.1,+ startYRatio: 0.2,+ endXRatio: 0.9,+ endYRatio: 0.8,+ durationMs: 250,+ },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const swipeCall = driver.swipe.mock.lastCall!;+ expect(swipeCall[0]).toBe('wda-session');+ expect(swipeCall[1].x).toBeCloseTo(39.3);+ expect(swipeCall[1].y).toBeCloseTo(170.4);+ expect(swipeCall[2].x).toBeCloseTo(353.7);+ expect(swipeCall[2].y).toBeCloseTo(681.6);+ expect(swipeCall[3]).toBe(250);+ nativeInputEnabled = true;+ await expect(+ host.updateViewerTouch('session-a', route, 18, {+ gestureId: 'viewer-1',+ phase: 'begin',+ xRatio: 0.1,+ yRatio: 0.2,+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });+ expect(nativeInput.beginTouch).not.toHaveBeenCalled();+ await expect(+ host.updateViewerTouch('session-a', route, 17, {+ gestureId: 'viewer-1',+ phase: 'begin',+ xRatio: 0.1,+ yRatio: 0.2,+ }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.updateViewerTouch('session-a', route, 17, {+ gestureId: 'viewer-1',+ phase: 'move',+ xRatio: 0.5,+ yRatio: 0.5,+ }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.updateViewerTouch('session-a', route, 17, {+ gestureId: 'viewer-1',+ phase: 'end',+ xRatio: 0.9,+ yRatio: 0.8,+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.beginTouch).toHaveBeenCalledWith(+ 'viewer-1',+ expect.objectContaining({ x: expect.closeTo(0.1), y: expect.closeTo(0.2) }),+ expect.any(AbortSignal),+ );+ expect(nativeInput.moveTouch).toHaveBeenCalledWith(+ 'viewer-1',+ expect.objectContaining({ x: expect.closeTo(0.5), y: expect.closeTo(0.5) }),+ expect.any(AbortSignal),+ );+ expect(nativeInput.endTouch).toHaveBeenCalledWith(+ 'viewer-1',+ expect.objectContaining({ x: expect.closeTo(0.9), y: expect.closeTo(0.8) }),+ false,+ expect.any(AbortSignal),+ );+ nativeInput.touchPath.mockClear();+ const wdaTapCount = driver.tap.mock.calls.length;+ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 0.5, yRatio: 0.25 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.touchPath).toHaveBeenCalledOnce();+ expect(driver.tap).toHaveBeenCalledTimes(wdaTapCount);+ nativeInput.touchPath.mockClear();+ const nativeSwipeScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!nativeSwipeScreen.ok) throw new Error('expected native swipe screen map');+ const nativeSwipeSnapshot = (+ nativeSwipeScreen.data as {+ screenMap: { snapshotId: string };+ }+ ).screenMap.snapshotId;+ await expect(+ host.callTool(+ 'swipe',+ {+ ...route,+ snapshotId: nativeSwipeSnapshot,+ startX: 39.3,+ startY: 170.4,+ endX: 353.7,+ endY: 681.6,+ durationMs: 250,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.touchPath).toHaveBeenCalledOnce();+ const nativeSwipePath = nativeInput.touchPath.mock.lastCall![0];+ expect(nativeSwipePath[0]).toMatchObject({+ phase: 'down',+ y: 0.2,+ dtMs: 0,+ });+ expect(nativeSwipePath[0]!.x).toBeCloseTo(0.1);+ expect(nativeSwipePath.at(-1)).toMatchObject({+ phase: 'up',+ y: 0.8,+ });+ expect(nativeSwipePath.at(-1)!.x).toBeCloseTo(0.9);++ const nativeMultiScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!nativeMultiScreen.ok) throw new Error('expected native multi-touch screen map');+ const nativeMultiSnapshot = (+ nativeMultiScreen.data as {+ screenMap: { snapshotId: string };+ }+ ).screenMap.snapshotId;+ await expect(+ host.callTool(+ 'touch2_path',+ {+ ...route,+ snapshotId: nativeMultiSnapshot,+ first: [+ { phase: 'down', x: 157.2, y: 426 },+ { phase: 'move', x: 117.9, y: 426, dtMs: 20 },+ { phase: 'up', x: 78.6, y: 426, dtMs: 20 },+ ],+ second: [+ { phase: 'down', x: 235.8, y: 426 },+ { phase: 'move', x: 275.1, y: 426, dtMs: 20 },+ { phase: 'up', x: 314.4, y: 426, dtMs: 20 },+ ],+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(nativeInput.touch2Path).toHaveBeenCalledOnce();+ expect(nativeInput.touch2Path.mock.lastCall![0][0]!.x).toBeCloseTo(0.4);+ expect(nativeInput.touch2Path.mock.lastCall![0][0]!.y).toBeCloseTo(0.5);+ expect(nativeInput.touch2Path.mock.lastCall![1][0]!.x).toBeCloseTo(0.6);+ expect(nativeInput.touch2Path.mock.lastCall![1][0]!.y).toBeCloseTo(0.5);++ const takeoverScreen = await host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ });+ if (!takeoverScreen.ok) throw new Error('expected takeover screen map');+ const takeoverSnapshot = (+ takeoverScreen.data as {+ screenMap: { snapshotId: string };+ }+ ).screenMap.snapshotId;+ let takeoverSignal: AbortSignal | undefined;+ nativeInput.touchPath.mockImplementationOnce(+ async (_points: IOSSimulatorTouchPoint[], signal?: AbortSignal) => {+ takeoverSignal = signal;+ await new Promise<void>((resolve) => {+ signal?.addEventListener('abort', () => resolve(), { once: true });+ });+ },+ );+ const activeNativeGesture = host.callTool(+ 'touch_path',+ {+ ...route,+ snapshotId: takeoverSnapshot,+ points: [+ { phase: 'down', x: 39.3, y: 170.4 },+ { phase: 'move', x: 196.5, y: 426, dtMs: 1_000 },+ { phase: 'up', x: 353.7, y: 681.6, dtMs: 1_000 },+ ],+ },+ { sessionId: 'session-a', origin: 'agent' },+ );+ await vi.waitFor(() => expect(takeoverSignal).toBeDefined());+ await expect(host.setAgentMutationPaused('session-a', route, true)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { takeoverPending: true } },+ });+ expect(takeoverSignal?.aborted).toBe(true);+ await expect(activeNativeGesture).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(host.setAgentMutationPaused('session-a', route, false)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { agentPaused: false } },+ });++ const accessibilityCallsAfterNativeInteractions = driver.getAccessibilityTree.mock.calls.length;+ await expect(+ host.callTool(+ 'type_text',+ { ...route, text: 'Hello' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.typeText).toHaveBeenLastCalledWith(+ 'wda-session',+ 'Hello',+ expect.any(AbortSignal),+ );+ await expect(+ host.callTool('press_home', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.home).toHaveBeenCalledOnce();+ await expect(+ host.callTool(+ 'set_orientation',+ { ...route, orientation: 'LANDSCAPE' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true, data: { orientation: 'LANDSCAPE' } });+ expect(driver.setOrientation).toHaveBeenCalledWith(+ 'LANDSCAPE',+ 'wda-session',+ expect.any(AbortSignal),+ );+ driver.setOrientation.mockRejectedValueOnce(+ new WdaError(+ 'ORIENTATION_UNSUPPORTED',+ 'The foreground app does not support the requested orientation.',+ 500,+ ),+ );+ await expect(+ host.callTool(+ 'set_orientation',+ { ...route, orientation: 'PORTRAIT' },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'ORIENTATION_UNSUPPORTED',+ message: 'The foreground app does not support the requested orientation.',+ });+ await expect(+ host.callTool('lock_screen', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool('unlock_screen', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driver.lock).toHaveBeenCalledWith('wda-session', expect.any(AbortSignal));+ expect(driver.unlock).toHaveBeenCalledWith('wda-session', expect.any(AbortSignal));+ expect(driver.getAccessibilityTree).toHaveBeenCalledTimes(+ accessibilityCallsAfterNativeInteractions,+ );+ await expect(+ host.callTool(+ 'tap',+ { ...route, xRatio: 1.1, yRatio: 0.5 },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ expect(driver.getAccessibilityTree).toHaveBeenCalledTimes(+ accessibilityCallsAfterNativeInteractions,+ );++ await expect(host.setAgentMutationPaused('session-a', route, true)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { agentPaused: true } },+ });+ await expect(+ host.callTool('get_screen_map', route, {+ sessionId: 'session-a',+ origin: 'agent',+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'AGENT_MUTATION_PAUSED' });+ await expect(+ host.callTool('press_home', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(host.setAgentMutationPaused('session-a', route, false)).resolves.toMatchObject({+ ok: true,+ data: { mutation: { agentPaused: false } },+ });++ running = null;+ await expect(+ host.setViewerStreamProfile('session-a', route, 17, 'viewer-token', {+ framesPerSecond: 20,+ jpegQuality: 70,+ scalingPercent: 100,+ }),+ ).resolves.toMatchObject({+ ok: true,+ data: { profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 } },+ });+ await expect(host.setViewerVisibility('session-a', route, true)).resolves.toMatchObject({+ ok: true,+ data: { viewport: { width: 393, height: 852 } },+ });+ expect(driverManager.start).toHaveBeenCalledTimes(2);++ await expect(+ host.callTool('stop_instance', route, { sessionId: 'session-a', origin: 'agent' }),+ ).resolves.toMatchObject({ ok: true });+ expect(driverManager.start).toHaveBeenCalledWith(+ expect.objectContaining({+ instanceId: instance.instanceId,+ simulatorUdid: READY_REPORT.devices[0]!.udid,+ }),+ );+ expect(driverManager.stop).toHaveBeenCalledWith(instance.instanceId);+ expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);++ const stopped = actor.list('session-a')[0]!;+ await expect(+ host.callTool(+ 'detach_device',+ {+ instanceId: stopped.instanceId,+ generation: stopped.generation,+ leaseId: stopped.lease.id,+ },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(discardInstance).toHaveBeenCalledTimes(2);+ expect(resourceScheduler.runningCount()).toBe(0);+ });++ it('routes build, install, launch, terminate, and URL actions through injected adapters', async () => {+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const buildProject = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(+ async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: `${worktreeRoot}/ios`,+ containerPath: `${worktreeRoot}/ios/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: `${worktreeRoot}/build/Demo.app`,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail:+ 'compile /tmp/session-a/secret.swift\\nGH_TOKEN=ghp_1234567890abcdefghijkl\\nwarning: keep this warning',+ }),+ );+ const validateLaunch = vi.fn(async () => ({+ healthy: true,+ expectedPort: 8081,+ expectedSource: 'branch@commit',+ currentSourceOnExpectedPort: true,+ anyMetro: true,+ targetSimulatorUdid: READY_REPORT.devices[0]!.udid,+ targetBooted: true,+ }));+ const projectBuilder: IOSSimulatorProjectBuilderAdapter = {+ build: buildProject,+ readXcresult: vi.fn(async () =>+ JSON.stringify({+ issues: [+ {+ message:+ 'failed at /Users/secret/project.swift Authorization: Bearer simulator-diagnostic-secret-123456',+ },+ ],+ }),+ ),+ validateLaunch,+ };+ const artifact = {+ artifactId: 'artifact-a',+ worktreeRoot: '/tmp/session-a',+ authorizedRoot: '/tmp/session-a',+ appPath: '/tmp/session-a/build/Demo.app',+ bundleId: 'com.example.demo',+ createdAt: '2026-07-23T00:00:00.000Z',+ };+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async () => artifact,+ );+ const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(+ async () => undefined,+ );+ const appLifecycle: IOSSimulatorAppLifecycleAdapter = {+ inspectArtifact,+ installExact,+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ };+ const requestViewerFocus = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder,+ appLifecycle,+ resourceScheduler: testResourceScheduler(),+ requestViewerFocus,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const built = await host.callTool(+ 'build_app',+ { ...route, containerPath: 'ios/Demo.xcodeproj' },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );+ expect(built).toMatchObject({+ ok: true,+ data: {+ artifact: { artifactId: artifact.artifactId, bundleId: artifact.bundleId },+ diagnostics: {+ diagnosticsId: expect.any(String),+ buildLogTail: expect.stringContaining('<redacted-path>'),+ xcresultAvailable: true,+ },+ },+ });+ expect(JSON.stringify(built)).not.toContain('ghp_1234567890abcdefghijkl');+ const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })+ .data.diagnostics.diagnosticsId;+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log', offset: 0, limit: 20 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ diagnosticsId,+ source: 'build-log',+ offset: 0,+ limit: 20,+ available: true,+ text: expect.any(String),+ nextOffset: 20,+ eof: false,+ },+ });+ const xcresult = await host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'xcresult', offset: 0, limit: 64 * 1024 },+ { sessionId: 'session-a', origin: 'agent' },+ );+ expect(xcresult).toMatchObject({ ok: true, data: { available: true, eof: true } });+ expect(JSON.stringify(xcresult)).not.toContain('/Users/secret');+ expect(JSON.stringify(xcresult)).not.toContain('simulator-diagnostic-secret-123456');+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log' },+ { sessionId: 'session-b', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ expect(projectBuilder.readXcresult).toHaveBeenCalledTimes(1);++ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: artifact.artifactId },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ ),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'launch_app',+ { ...route, artifactId: artifact.artifactId, args: ['--uitesting'] },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });++ const mobileArtifact = { ...artifact, artifactId: 'mobile-artifact' };+ buildProject.mockResolvedValueOnce({+ kind: 'cindy-mobile',+ worktreeRoot: '/tmp/session-a',+ projectRoot: '/tmp/session-a/apps/mobile',+ containerPath: null,+ scheme: 'Cindy',+ appPath: '/tmp/session-a/apps/mobile/ios/build/Cindy.app',+ resultBundlePath: null,+ buildLogTail: '',+ });+ inspectArtifact.mockResolvedValueOnce(mobileArtifact);+ await expect(+ host.callTool('build_app', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'launch_app',+ { ...route, artifactId: mobileArtifact.artifactId, args: [] },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(validateLaunch).toHaveBeenCalledWith(+ '/tmp/session-a',+ READY_REPORT.devices[0]!.udid,+ expect.any(AbortSignal),+ );+ await host.callTool(+ 'terminate_app',+ { ...route, artifactId: artifact.artifactId },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );+ await host.callTool(+ 'open_url',+ { ...route, url: 'demo://home' },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );++ expect(projectBuilder.build).toHaveBeenCalledWith(+ expect.objectContaining({+ worktreeRoot: '/tmp/session-a',+ containerPath: 'ios/Demo.xcodeproj',+ }),+ );+ expect(appLifecycle.installExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact,+ expect.any(AbortSignal),+ );+ expect(appLifecycle.launchExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact,+ ['--uitesting'],+ expect.any(AbortSignal),+ );+ expect(appLifecycle.terminateExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact.bundleId,+ expect.any(AbortSignal),+ );+ expect(appLifecycle.openUrlExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ 'demo://home',+ expect.any(AbortSignal),+ );+ expect(requestViewerFocus).toHaveBeenCalledWith('session-a', instance.instanceId);++ let installSignal: AbortSignal | undefined;+ installExact.mockImplementationOnce(+ async (_simulatorUdid, _artifact, signal) =>+ new Promise<void>((resolve) => {+ installSignal = signal;+ signal?.addEventListener('abort', () => resolve(), { once: true });+ }),+ );+ const installing = host.callTool(+ 'install_app',+ { ...route, artifactId: artifact.artifactId },+ { sessionId: 'session-a', origin: 'user' },+ );+ await vi.waitFor(() => expect(installSignal).toBeDefined());+ const stopping = host.callTool('stop_instance', route, {+ sessionId: 'session-a',+ origin: 'user',+ });+ await vi.waitFor(() => expect(installSignal?.aborted).toBe(true));+ await expect(installing).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(stopping).resolves.toMatchObject({ ok: true });+ });++ it('returns readable diagnostics when build_app fails', async () => {+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const resultBundlePath =+ '/tmp/cindy-user-data/ios-simulator/projects/build/CindyBuild-failed.xcresult';+ const projectBuilder: IOSSimulatorProjectBuilderAdapter = {+ build: vi.fn(async () => {+ throw new IOSSimulatorProjectBuildError(+ 'APP_BUILD_FAILED',+ 'The Xcode project could not be built.',+ 'compile /Users/secret/project.swift\nerror: BUILD_FAILURE_MARKER',+ resultBundlePath,+ true,+ true,+ );+ }),+ readXcresult: vi.fn(async () => 'xcresult BUILD_FAILURE_MARKER'),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder,+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const failed = await host.callTool('build_app', route, {+ sessionId: 'session-a',+ origin: 'user',+ });++ expect(failed).toMatchObject({+ ok: false,+ errorCode: 'APP_BUILD_FAILED',+ message: 'The Xcode project could not be built.',+ data: {+ diagnostics: {+ diagnosticsId: expect.any(String),+ buildLogTail: expect.stringMatching(/<redacted-path>.*BUILD_FAILURE_MARKER/s),+ xcresultAvailable: true,+ outputTruncated: true,+ },+ },+ });+ const diagnosticsId = (+ failed as unknown as { ok: false; data: { diagnostics: { diagnosticsId: string } } }+ ).data.diagnostics.diagnosticsId;+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log' },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ diagnosticsId,+ available: true,+ text: expect.stringContaining('BUILD_FAILURE_MARKER'),+ },+ });+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log' },+ { sessionId: 'session-b', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ });++ itMac(+ 'retries persisted removed-task cleanup after another registry writer releases its lease',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-persisted-cleanup-'));+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ const setupRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath, {+ acquireWriterLease: () => {+ let held = true;+ return {+ isHeld: () => held,+ release: () => {+ held = false;+ },+ };+ },+ });+ expect(setupRegistry.acquireWriterSync()).toBe(true);+ const persistedInstance = new IOSSimulatorOwnershipStore({+ createId: () => 'persisted-removed-instance',+ }).attach({+ sessionId: 'persisted-removed-session',+ worktreeRoot: '/tmp/persisted-removed-session',+ sourceFingerprint: 'persisted-fingerprint',+ device: READY_REPORT.devices[0]!,+ });+ setupRegistry.saveSync([persistedInstance]);+ setupRegistry.releaseWriterSync();++ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ let writerLeaseHeld = false;+ let acquireAttempts = 0;+ const acquireWriter = vi+ .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'acquireWriterSync')+ .mockImplementation(() => {+ if (writerLeaseHeld) return true;+ acquireAttempts += 1;+ if (acquireAttempts === 1) return false;+ writerLeaseHeld = true;+ return true;+ });+ const isWriter = vi+ .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'isWriter', 'get')+ .mockImplementation(() => writerLeaseHeld);+ const releaseWriter = vi+ .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'releaseWriterSync')+ .mockImplementation(() => {+ writerLeaseHeld = false;+ });+ const cleanupOrphaned = vi+ .spyOn(WdaProcessManager.prototype, 'cleanupOrphaned')+ .mockResolvedValue();+ try {+ await expect(+ cleanupIOSSimulatorRemovedSession('persisted-removed-session'),+ ).rejects.toMatchObject({+ code: 'DEVICE_BUSY',+ retryable: true,+ });+ expect(acquireAttempts).toBe(1);++ await expect(+ cleanupIOSSimulatorRemovedSession('persisted-removed-session'),+ ).resolves.toBeUndefined();++ expect(acquireAttempts).toBe(2);+ const persisted = JSON.parse(await readFile(registryPath, 'utf8')) as {+ instances: unknown[];+ };+ expect(persisted.instances).toEqual([]);+ } finally {+ await disposeIOSSimulatorHost();+ expect(writerLeaseHeld).toBe(false);+ releaseWriter.mockRestore();+ isWriter.mockRestore();+ acquireWriter.mockRestore();+ cleanupOrphaned.mockRestore();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ },+ );+ });diff --cc apps/desktop/src/renderer/__tests__/composerHostCapability.test.tsindex 0000000000,9c5b319a2e..2758893846mode 000000,100644..100644--- a/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts@@@ -1,0 -1,132 +1,133 @@@+ // @vitest-environment jsdom++ import { Editor } from '@tiptap/core';+ import Document from '@tiptap/extension-document';+ import Paragraph from '@tiptap/extension-paragraph';+ import Text from '@tiptap/extension-text';+ import { afterEach, describe, expect, it } from 'vitest';++ import { expandGhostCommand } from '@/cindy-brain/ghostCommand';+ import {+ expandHostCapabilityInvocation,+ splitHostCapabilityDirective,+ } from '@/cindy-brain/hostCapabilityInvocation';+ import { serializeEditorContent } from '@/components/new-chat/composerContentSerialization';+ import { MentionChipNode } from '@/components/new-chat/MentionChipNode';+ import { i18n } from '@/i18n';+ import type { InstalledGhost } from '../../shared/ghost';++ const editors: Editor[] = [];+ const initialLanguage = i18n.language;++ function capabilityGhost(): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: 'ios-simulator',+ name: 'iOS Simulator',+ version: '0.2.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['ios-simulator'],+ },+ dir: '/tmp/ios-simulator',+ enabled: true,++ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+ };+ }++ function editorWithCapability(path = 'ios-simulator', label = 'iOS Simulator', body = ''): Editor {+ const editor = new Editor({+ extensions: [Document, Paragraph, Text, MentionChipNode],+ content: {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ {+ type: 'mentionChip',+ attrs: {+ kind: 'plugin-capability',+ label,+ path,+ pluginId: 'ios-simulator',+ sourceLabel: 'iOS Simulator',+ },+ },+ ...(body ? [{ type: 'text', text: ` ${body}` }] : []),+ ],+ },+ ],+ },+ });+ editors.push(editor);+ return editor;+ }++ afterEach(async () => {+ for (const editor of editors.splice(0)) editor.destroy();+ await i18n.changeLanguage(initialLanguage);+ });++ describe('Host capability composer chip', () => {+ it('serializes as routing metadata rather than an automatic visible prefix', async () => {+ await i18n.changeLanguage('zh-CN');+ const serialized = serializeEditorContent(editorWithCapability());++ expect(serialized.text).toBe('');+ expect(serialized.hostCapability).toEqual({+ capability: 'ios-simulator',+ ghostId: 'ios-simulator',+ name: 'iOS Simulator',+ });+ expect(serialized.mentions).toEqual([]);+ expect(serialized.agentReferences).toEqual([]);+ expect(expandGhostCommand(serialized.text, [capabilityGhost()])).toBe(serialized.text);+ expect(serialized.text).not.toContain('ghost_call');+ });++ it('keeps user text once and appends a parseable Host route without ghost_call routing', () => {+ const serialized = serializeEditorContent(+ editorWithCapability('ios-simulator', 'iOS Simulator', '帮我打开iOS模拟器,调试当前项目'),+ );+ expect(serialized.text).toBe('帮我打开iOS模拟器,调试当前项目');++ const expanded = expandHostCapabilityInvocation(+ serialized.text,+ serialized.hostCapability!,+ '帮我打开 iOS 模拟器。',+ );+ const split = splitHostCapabilityDirective(expanded);+ expect(split?.body).toBe('帮我打开iOS模拟器,调试当前项目');+ expect(split?.directive).toMatchObject({+ kind: 'host-capability',+ capability: 'ios-simulator',+ route: 'cindy_ios_simulator',+ ghostId: 'ios-simulator',+ });+ expect(expanded.match(/帮我打开/g)).toHaveLength(1);+ expect(expanded).toContain('不要通过 ghost_call 调用');+ expect(expanded).not.toContain('必须通过 cindy 总机的 ghost_call');+ });++ it('uses one default prompt when the chip is sent by itself', () => {+ const serialized = serializeEditorContent(editorWithCapability());+ const expanded = expandHostCapabilityInvocation(+ serialized.text,+ serialized.hostCapability!,+ '帮我打开 iOS 模拟器。',+ );+ expect(splitHostCapabilityDirective(expanded)?.body).toBe('帮我打开 iOS 模拟器。');+ });++ it('preserves an unknown future capability as structured metadata', () => {+ expect(+ serializeEditorContent(editorWithCapability('future-capability', 'Future')).hostCapability,+ ).toEqual({+ capability: 'future-capability',+ ghostId: 'ios-simulator',+ name: 'iOS Simulator',+ });+ });+ });diff --cc apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.tsindex 54b224d0eb,d6abbd3476..87ff46e293--- a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts@@@ -36,6 -39,22 +40,23 @@@ function ghost(command: string, id = co};}+ function hostCapabilityGhost(id = 'ios-simulator'): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id,+ name: 'iOS Simulator',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['ios-simulator'],+ },+ dir: `/tmp/${id}`,+ enabled: true,++ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+ };+ }+function editorWith(content: string): Editor {const editor = new Editor({extensions: [Document, Paragraph, Text, MentionChipNode],diff --cc apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.tsindex a6488ec67c,fe3bf71f3c..94edc63adb--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts@@@ -108,9 -108,8 +109,10 @@@ describe('ghostPluginViewModel', () =>version: '1',enabled: true,canUse: true,+ approvalState: 'approved',+ builtin: false,tabPanel: false,+ hostCapability: null,},{id: 'lizi-mivo',@@@ -119,9 -118,8 +121,10 @@@version: '1',enabled: true,canUse: true,+ approvalState: 'approved',+ builtin: false,tabPanel: false,+ hostCapability: null,},{id: 'slack',@@@ -130,9 -128,8 +133,10 @@@version: '1',enabled: true,canUse: true,+ approvalState: 'approved',+ builtin: false,tabPanel: false,+ hostCapability: null,},] satisfies GhostPluginListItem[];diff --cc apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 6e6c367dc7,12eaa053f0..4afb81c87e--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@@ -167,13 -163,13 +169,16 @@@ export function GhostPluginDetailView(const [descriptionExpanded, setDescriptionExpanded] = useState(false);const [descriptionOverflows, setDescriptionOverflows] = useState(false);const descriptionRef = useRef<HTMLParagraphElement>(null);- const enabled = enabledOverride ?? detail.enabled;+ // 未批准的安装不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它+ // 看起来只是"被关掉了"),再喂 main 改版的 primaryAction/primaryEnabled。+ const needsReapproval = detail.approvalState !== 'approved';+ const enabled = (enabledOverride ?? detail.enabled) && !needsReapproval;const primaryAction = ghostPrimaryAction(detail);const primaryEnabled =- enabled && (primaryAction === 'panel' || (primaryAction === 'command' && detail.canUse));+ enabled &&+ (primaryAction === 'panel' ||+ primaryAction === 'capability' ||+ (primaryAction === 'command' && detail.canUse));const cindyCapabilities = detail.cindyCapabilities;const hasConfiguration = detail.hasSettingsUi || cindyCapabilities.length > 0 || detail.hasErrand;const summary = ghostPluginSummary(detail.description, detail.id);diff --cc apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex 7b5f73a92d,a2d76cbf1f..c02a3425d9--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@@ -90,9 -54,8 +90,10 @@@ const commandPlugin: GhostPluginListIteversion: '1.0.0',enabled: true,canUse: true,+ approvalState: 'approved',+ builtin: false,tabPanel: false,+ hostCapability: null,};const panelPlugin: GhostPluginListItem = {diff --cc apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex 7168edbdec,30b6b0e589..21042534d2--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@@ -114,9 -114,8 +114,10 @@@ const detail: GhostPluginDetail =version: '1.2.3',enabled: true,canUse: true,+ approvalState: 'approved',+ builtin: false,tabPanel: false,+ hostCapability: null,author: 'XD',contents: ['code'],permissions: [],diff --cc apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex 16424a45bb,0b4733afea..7f0e0e3a08--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@@ -35,15 -34,10 +35,17 @@@ export interface GhostPluginListItemversion: string;enabled: boolean;canUse: boolean;+ /**+ * Host 是否持有一次明确的安装/更新确认。非 `approved` 的安装不可运行,列表与+ * 详情都必须如实说明并给出重新确认入口,而不是让它看起来只是"被关掉了"。+ */+ approvalState: GhostInstallApproval['state'];+ /** 随包内置插件(main 按种子清单投影)。批准态异常时文案与恢复入口都不同。 */+ builtin: boolean;/** 声明了插件页内独占面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */tabPanel: boolean;+ /** 声明了由 Host 承载、但可从插件 UI 主动进入的能力。 */+ hostCapability: 'ios-simulator' | null;trust?: GhostTrustInfo;iconDataUrl?: string;}@@@ -269,9 -263,8 +271,10 @@@ export function toGhostPluginListItemversion: manifest.version,enabled: ghost.enabled,canUse: Boolean(manifest.command),+ approvalState: ghost.approval.state,+ builtin: ghost.builtin === true,tabPanel: manifest.panel?.position === 'tab',+ hostCapability: manifest.slots.includes('ios-simulator') ? 'ios-simulator' : null,trust: ghost.trust ?? {level: 'unverified',publisherSigned: false,diff --cc apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 6175579855,87f00c3251..1a108cb532--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@@ -3571,8 -3566,8 +3576,9 @@@},"errors": {"fileInvalid": "Not a valid .cindy plugin file",+ "hostUnsupported": "This plugin needs Cindy capabilities that this version does not provide. Update Cindy, then install it again.","alreadyInstalled": "This plugin is already installed",+ "approvalRequired": "This plugin's permissions must be reviewed again before continuing.","commandConflict": "Its command conflicts with an installed plugin. Uninstall the other one or rename the command.","idReserved": "This id uses the reserved official prefix cindy-; it is only available to plugins bundled with the app","sourceMissing": "The selected file could not be found",diff --cc apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c0230209b8,3d5066857c..b9319e36f3--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@@ -3570,8 -3565,8 +3575,9 @@@},"errors": {"fileInvalid": "有効な .cindy プラグインファイルではありません",+ "hostUnsupported": "このプラグインには、現在のバージョンでは提供されていない Cindy の機能が必要です。Cindy を更新してから、もう一度インストールしてください。","alreadyInstalled": "このプラグインは既にインストールされています",+ "approvalRequired": "続けるには、このプラグインの権限を再確認する必要があります","commandConflict": "コマンドがインストール済みのプラグインと重複しています。先に相手をアンインストールするか、コマンド名を変更してください。","idReserved": "この id は公式予約プレフィックス cindy- を使用しています。アプリに同梱されたプラグインのみ使用できます","sourceMissing": "選択したファイルが見つかりません",diff --cc apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 1029b527b5,484520c423..1c891e9fde--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@@ -3570,8 -3565,8 +3575,9 @@@},"errors": {"fileInvalid": "유효한 .cindy 플러그인 파일이 아닙니다",+ "hostUnsupported": "이 플러그인에는 현재 버전에서 제공하지 않는 Cindy 기능이 필요합니다. Cindy를 업데이트한 후 다시 설치하세요.","alreadyInstalled": "이 플러그인은 이미 설치되어 있습니다",+ "approvalRequired": "계속하려면 이 플러그인의 권한을 다시 확인해야 합니다","commandConflict": "명령어가 설치된 플러그인과 충돌합니다. 먼저 상대를 제거하거나 명령어 이름을 변경하세요.","idReserved": "이 id는 공식 예약 접두사 cindy-를 사용합니다. 앱에 내장된 플러그인만 사용할 수 있습니다","sourceMissing": "선택한 파일을 찾을 수 없습니다",diff --cc apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 59011c55d4,2fbb2a6442..c27b91f16d--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@@ -3430,9 -3424,8 +3433,9 @@@"toast": {"installed": "已安装「{{name}}」","uninstalled": "已卸载「{{name}}」",- "installedAsleep": "已安装「{{name}}」(未生效,可在此开启)",+ "installedAsleep": "已安装「{{name}}」(已停用,可随时在此启用)","updated": "「{{name}}」已更新到 v{{version}}",+ "reapproved": "已恢复「{{name}}」","exported": "已导出「{{name}}」的 .cindy 文件","exportFailed": "导出「{{name}}」失败,请重试","projectDisabled": "已在此项目停用「{{name}}」",@@@ -3570,8 -3565,8 +3575,9 @@@},"errors": {"fileInvalid": "不是合法的 .cindy 插件文件",+ "hostUnsupported": "这个插件需要当前版本尚未提供的 Cindy 能力。请先升级 Cindy,再重新安装。","alreadyInstalled": "这个插件已经安装",+ "approvalRequired": "需要重新确认这个插件的权限后才能继续","commandConflict": "它的指令和已装插件撞名了,先卸载占用方或让作者改名","idReserved": "该 id 使用了官方保留前缀 cindy-,仅随应用内置的插件可用","sourceMissing": "找不到所选文件",diff --cc apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 591368749d,c1f567e96f..1383d48744--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@@ -2255,6 -2255,6 +2255,9 @@@"title": "Codex Subagent 護欄","enableHint": "允許 Codex 在執行任務時建立一次性 Subagent。關閉後對舊版(V1)和 Sol / Terra(V2)都生效。","enableAria": "允許 Codex 使用 Subagent",++ "cindyPolicyLabel": "使用 Cindy 自訂 Subagent 策略",++ "cindyPolicyHint": "開啟後,Cindy 會注入策略,引導 Codex 在探索型任務中主動使用 Subagent。對於本身已擅長規劃和委派的模型,額外引導可能適得其反;關閉後不再注入,改用 Codex 的原生預設行為。",++ "cindyPolicyAria": "使用 Cindy 自訂 Subagent 策略","concurrencyLabel": "Subagent 併發上限","concurrencyHint": "同時執行的 Subagent 數量上限。每個 Subagent 都會消耗模型配額,調低更省;Ultra 檔位下併發達到 8 時 Codex 會發出用量警告。","concurrencyFollowDefault": "跟隨 Codex 預設(舊版 V1 為 6,Sol / Terra 為 3)",@@@ -3570,8 -3562,8 +3575,9 @@@},"errors": {"fileInvalid": "不是合法的 .cindy 插件檔案",+ "hostUnsupported": "這個插件需要目前版本尚未提供的 Cindy 能力。請先更新 Cindy,再重新安裝。","alreadyInstalled": "這個插件已經安裝",+ "approvalRequired": "繼續前需要重新確認這個插件的權限","commandConflict": "它的指令和已裝插件撞名了,先解除安裝佔用方或讓作者改名","idReserved": "該 id 使用了官方保留字首 cindy-,僅隨應用內建的插件可用","sourceMissing": "找不到所選檔案",@@@ -3675,14 -3667,10 +3681,15 @@@"slotBadge": "未讀角標","slotFs": "寫檔案","slotSkill": "Agent 技能",- "slotWorkspace": "工作區任務"+ "slotWorkspace": "工作區任務",+ "slotIOSSimulator": "內建 iOS 模擬器"},"commandPaletteTag": "插件指令",+ "reapproveConfirm": {+ "title": "重新確認「{{name}}」的權限?",+ "body": "按下方清單重新授權這個已安裝的插件,不需要重新提供安裝包檔案。",+ "confirm": "確認並恢復"+ },"updateConfirm": {"title": "更新插件「{{name}}」?","body": "版本 {{from}} → {{to}}。將替換現有版本;生效狀態與面板位置保持不變。",diff --cc docs/dev-rules/plugin-approval-main-merge-2026-08-10.mdindex 0000000000,0000000000..863a616b7anew file mode 100644--- /dev/null+++ b/docs/dev-rules/plugin-approval-main-merge-2026-08-10.md@@@ -1,0 -1,0 +1,110 @@@++# Plugin Approval PR Main Merge Strategy (2026-08-10)++++Second main merge for PR #1916 after merging `origin/main` at `9bcf7bd1a`.++The first merge (2026-08-09, `e78f44ae5`) is recorded in++`plugin-approval-main-merge-2026-08-09.md`. This note records the decisions for++this round only; it does not replace the authoritative security rules.++++## Invariants (unchanged, carry forward)++++- Host-owned approval receipts remain the only runtime authorization fact. Mutable++ install-directory trust mirrors are migration or display inputs only.++- A durable owner boundary is published before local session publication. Missing,++ malformed, pending, mismatched, or durability-uncertain state fails closed.++- Every owner-bound Ghost, Agent, broker, slot, skill-link, and IPC consumer must++ use the same durable owner and in-process owner generation.++- General Cindy account capabilities are also fail-closed unless the durable++ projection marker is `stable` for the active data owner.++- Ghost mutation owner capture and lease acquisition re-check durable owner++ stability at the mutation boundary.++- Passive shared-userData instances are read-only for the global projection.++- Content and manifest reads keep no-follow, containment, handle identity, and++ post-read stability checks.++- Existing approved plugins remain compatible without reinstall or reapproval.++ New security checks may reject only malformed or untrusted state.++++## Conflict decisions (2026-08-10 round)++++Six files conflicted. Resolutions below preserve the PR's invariants and absorb++main's changes without weakening fail-closed behavior.++++- **GhostManager.ts:** main's newer receipt/approval/trust code and the PR's++ legacy-backfill hardening both landed. Resolution keeps the union: the PR's++ optional-icon degradation (`readLegacyIconDataUrlForApproval` catch → omit++ iconDataUrl), the removed `readInstalledHostMetadata` (mutable mirror no longer++ projected), and main's newer projection/approval helpers. Where main added a++ newer signature or helper, keep main's and route the PR's caller through it;++ never drop a containment/no-follow/identity check to satisfy a signature.++- **index.ts:** main's newer owner/mutation wiring and the PR's++ `captureGhostMutationOwner`/`beginGhostMutation` durable-stability re-check both++ land. Keep the PR's boundary re-check; incorporate main's newer session helpers++ where the call shape changed.++- **crossProcessLock.ts:** main's newer lock/reclaim code and the PR's++ nonce-bound `.released` release-marker + malformed-gate fail-closed reclaim both++ land. Keep the PR's marker bound to gate basename + valid nonce, and main's++ newer helper shapes; any release-marker/cleanup path must remove both gate and++ marker and stay fail-closed on identity-unresolvable / EPERM / EACCES.++- **shared/ghost.ts:** main introduced a narrower per-item fingerprint++ (`ghostPermissionItemFingerprint` = key + detail + detailKey + detailArgs)++ for the baseline key and `unreviewedGhostPermissionItems`. The PR's++ `ghostPermissionProjectionKey`/`Fingerprint` is a superset (also fingerprints++ `kind`, the GitHub-normalized `labelKey`, and `labelArgs`), and the projection++ docs explicitly treat `labelArgs` (hosts / tool names shown in preview) as++ authorization-relevant. Dropping those fields would silently miss a++ permission-surface change on an unchanged key. Resolution keeps the PR's++ superset for baseline and unreviewed (consistent with `diffGhostPermissionItems`,++ which already uses the same superset) and removes main's now-unused++ `ghostPermissionItemFingerprint`. The GitHub credential detailKey normalization++ is retained in both directions.++- **GhostManager.test.ts:** union of both sides' regression tests; adjust only++ where main renamed a fixture/expectation. Do not weaken a behavioral assertion++ to resolve a conflict.++- **plugin-security-and-authoring.md:** keep the PR's existing text and absorb++ main's newer security-rule paragraphs; no invariant is relaxed, no rule removed.++++## Do not accept during conflict resolution++++- Direct authorization from install-directory mirrors, renderer-provided tokens,++ mutable manifests, or a stale in-memory session.++- A path-based read/write that drops no-follow, containment, identity, or stability++ validation because main added a convenience helper.++- A lock-only solution that omits the owner lease, or an owner lease that omits the++ per-Ghost mutation lock where both are required.++- A test-only weakening, skipped test, or branch-specific assertion that hides a++ conflict instead of expressing the merged behavior.++++## Additional resolution notes++++- **Submodule alignment:** the merge advanced the `cindy-protocol` gitlink to++ `dbbf169` (identical to `origin/main`). The submodule working tree was still++ on the pre-merge `56d9d9f`; it was aligned to `dbbf169` (no protocol source++ change, no gitlink edit).++- **Icon byte cap:** the PR's local `MAX_GHOST_ICON_BYTES` duplicate was removed++ in favor of the shared `GHOST_ICON_MAX_BYTES` from `shared/ghost.ts` (same++ 512 KiB value; renderer/Forge already use the shared constant).++- **Test fixtures:** main's new renderer tests (`composerHostCapability.test.ts`,++ `ghostComposerPlacement.test.ts`) construct `InstalledGhost` objects without++ the PR-required `approval` field; the fixtures were given a minimal++ `{ state: 'approved', revision }` approval so they typecheck against the++ receipt model.++- **iOS Simulator test adaptation:** main's new `ios-simulator.test.ts` /++ `ios-simulator-media.test.ts` default their owner-boundary probe to++ `isAppSessionBoundaryPending()`, which the PR hardens to fail closed on an++ uncommitted/durable-unstable owner — so the suites failed on every status++ probe / media capture in the (owner-less) test environment. The suites++ exercise simulator/ownership behavior, not boundary transitions, so both++ files now mock `../../appSessionState.js` to override only++ `isAppSessionBoundaryPending: () => false`. Owner-pending paths are still++ covered by the tests that pass explicit `isOwnerBoundaryPending` /++ `isOwnerScopeCurrent` overrides; no production behavior was changed.++- **Dependency linking:** local Node 22.14 < `[email protected]` engines requirement++ blocks a strict install; `pnpm install --frozen-lockfile --prefer-offline++ --config.engine-strict=false` links the workspace without touching the++ lockfile. The lockfile in the merge matches `origin/main` byte-for-byte.++++## Post-merge gate++++After all conflicts are resolved: inspect the complete diff, verify no unmerged++entries, run targeted plugin/auth/Forge tests, run the desktop typecheck, run the++full `pnpm test:unit` gate, then perform an independent review before committing++or pushing the merge result.diff --cc docs/dev-rules/plugin-security-and-authoring.mdindex b154a1f5c2,f5fd5a949c..4aceb01a1c--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@@ -24,18 -24,17 +24,18 @@@## 事实来源- | 内容 | 权威来源 |- |---|---|- | 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |- | 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |- | 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |- | 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |- | 安装批准事实(receipt / 技能快照 / revision) | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,批准态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |- | 能力 slot(网络/通知/角标/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`) |- | 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |- | 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |- | 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |- | 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |+ | 内容 | 权威来源 |+ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+ | 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |+ | 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) |+ | 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |+ | 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |++| 安装批准事实(receipt / 技能快照 / revision) | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,批准态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |+ | 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`)、`iosSimulatorSlot.ts`(当前台前任务的公开状态与 Host viewer 入口) |+ | 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |+ | 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` |+ | 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |+ | 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |文档与实现冲突时以代码为准,但必须在同一改动内同步修正本文与手册。