From d7e15e0586a72466993ba3bfa6522be5da9bbc92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:17:06 +0100 Subject: [PATCH 1/8] fix(ios): prepare the reinstall replacement before uninstalling the app A replacement that cannot be prepared no longer removes the installed app or its data. A failure during install after the uninstall can still leave the app removed. Co-Authored-By: Claude Sonnet 5.5 --- .../command-surface/src/management/install.ts | 2 +- .../src/deployment/runtime.test.ts | 105 +++++++++++++----- .../platform-apple/src/deployment/runtime.ts | 5 +- .../provider-scenarios/ios-lifecycle.test.ts | 17 +++ website/docs/docs/commands.md | 1 + 5 files changed, 98 insertions(+), 32 deletions(-) diff --git a/packages/command-surface/src/management/install.ts b/packages/command-surface/src/management/install.ts index ad2cb4f6f3..6716632df4 100644 --- a/packages/command-surface/src/management/install.ts +++ b/packages/command-surface/src/management/install.ts @@ -38,7 +38,7 @@ const installCommandMetadata = defineFieldCommandMetadata( const reinstallCommandMetadata = defineFieldCommandMetadata( 'reinstall', - 'Replace an installed app with a binary from a local path. This preserves the app identity while installing a new build on the selected device. Local Android and iOS install steps time out after 120s; the command allows 480s including device startup and uninstall.', + 'Replace an installed app with a binary from a local path. This preserves the app identity while installing a new build on the selected device. Local Android and iOS install steps time out after 120s; the command allows 480s including device startup and uninstall. On iOS, a build that cannot be read leaves the installed app in place; a failure during install after the uninstall can still leave the app removed.', { app: requiredField(stringField()), appPath: requiredField(stringField('Path to app binary.')), diff --git a/packages/platform-apple/src/deployment/runtime.test.ts b/packages/platform-apple/src/deployment/runtime.test.ts index 82502afb1f..45c8c448f8 100644 --- a/packages/platform-apple/src/deployment/runtime.test.ts +++ b/packages/platform-apple/src/deployment/runtime.test.ts @@ -440,7 +440,10 @@ test('simulator push failure surfaces the simctl stderr excerpt', async () => { test('physical iOS uninstall failure surfaces the devicectl Developer Mode hint', async () => { const resolveAppBundleId = vi.fn(async () => 'com.example.app'); const executor = { - prepareArtifact: vi.fn(), + prepareArtifact: vi.fn(async () => ({ + installablePath: '/tmp/replacement.app', + cleanup: async () => {}, + })), resolveAppBundleId, withInvalidatedAppResolutionCache: withoutInvalidatingAppResolutionCache, } as AppleAppDeploymentExecutor; @@ -525,40 +528,88 @@ test.each([ }, ); -test('preserves Apple reinstall partial-failure ordering', async () => { - const order: string[] = []; - const resolveAppBundleId = vi.fn(async () => { - order.push('uninstall'); - return 'com.example.replaced'; - }); - const prepareArtifact = vi.fn(async () => { - order.push('prepare'); - throw new Error('replacement artifact is invalid'); +function reinstallHarness(options: { + prepare?: (signal: AbortSignal) => Promise; + uninstallExitCode?: number; + signal?: AbortSignal; +}) { + const events: string[] = []; + const signal = options.signal ?? new AbortController().signal; + const executor: AppleAppDeploymentExecutor = { + withInvalidatedAppResolutionCache: async (_device, operation) => await operation(), + resolveAppBundleId: async () => 'com.example.replaced', + prepareArtifact: (async ( + _input: unknown, + { signal: prepareSignal }: { signal: AbortSignal }, + ) => { + events.push('prepare'); + await options.prepare?.(prepareSignal); + return { + installablePath: '/tmp/App.app', + cleanup: async () => { + events.push('cleanup'); + }, + }; + }) as AppleAppDeploymentExecutor['prepareArtifact'], + }; + const run = xcrunLikeRun((request) => { + if (request.args[0] === 'uninstall') { + events.push('uninstall'); + return { stdout: '', stderr: 'boom', exitCode: options.uninstallExitCode ?? 0 }; + } + if (request.args[0] === 'install') events.push('install'); + return bootedSimulatorListResult(request); }); - const executor = { - prepareArtifact, - resolveAppBundleId, - withInvalidatedAppResolutionCache: withoutInvalidatingAppResolutionCache, - } as AppleAppDeploymentExecutor; - const host = deploymentHost(executor); const operations = createAppleAppDeploymentOperations({ - host, + host: deploymentHost(executor, run), device: appleDevice(), - signal: new AbortController().signal, + signal, }); - - await expect( - operations.deployApp?.({ + const reinstall = () => + operations.deployApp!({ app: 'com.example.replaced', appPath: '/tmp/replacement.app', replaceExisting: true, - }), - ).rejects.toThrow('replacement artifact is invalid'); + }); + return { events, reinstall }; +} + +test('reinstall keeps the installed app when the replacement cannot be prepared', async () => { + const { events, reinstall } = reinstallHarness({ + prepare: async () => { + throw new Error('replacement artifact is invalid'); + }, + }); + + await expect(reinstall()).rejects.toThrow('replacement artifact is invalid'); - expect(order).toEqual(['uninstall', 'prepare']); + expect(events).toEqual(['prepare']); }); -test('clears a concurrently repopulated fuzzy resolution after a partial-failed Apple reinstall', async () => { +test('reinstall keeps the installed app when cancelled during preparation', async () => { + const controller = new AbortController(); + const { events, reinstall } = reinstallHarness({ + signal: controller.signal, + prepare: async (signal) => { + controller.abort(new Error('cancelled')); + signal.throwIfAborted(); + }, + }); + + await expect(reinstall()).rejects.toThrow('cancelled'); + + expect(events).toEqual(['prepare']); +}); + +test('reinstall releases the prepared replacement when uninstall fails', async () => { + const { events, reinstall } = reinstallHarness({ uninstallExitCode: 1 }); + + await expect(reinstall()).rejects.toMatchObject({ code: 'COMMAND_FAILED' }); + + expect(events).toEqual(['prepare', 'uninstall', 'cleanup']); +}); + +test('clears a concurrently repopulated fuzzy resolution after a preparation-failed Apple reinstall', async () => { const cachedResolutions = new Map([['Maps', 'com.example.stale-before-uninstall']]); let nextResolution = 'com.example.current'; const resolveFuzzyTarget = vi.fn(async (target: string) => { @@ -686,7 +737,7 @@ test.each([ ); test.each([false, true])( - 'reinstall clears the old app before preparing and installing with a hosted installer: %s', + 'reinstall prepares the replacement before clearing the old app and installing with a hosted installer: %s', async (hosted) => { const events: string[] = []; const artifact = { @@ -741,8 +792,8 @@ test.each([false, true])( ).toEqual({ bundleId: 'com.example.app', launchTarget: 'com.example.app' }); expect(events).toEqual([ 'invalidate-before', - 'uninstall', 'materialize', + 'uninstall', hosted ? 'hosted-install' : 'native-install', 'cleanup', 'invalidate-after', diff --git a/packages/platform-apple/src/deployment/runtime.ts b/packages/platform-apple/src/deployment/runtime.ts index 376c1bb4dd..d58e2d19e5 100644 --- a/packages/platform-apple/src/deployment/runtime.ts +++ b/packages/platform-apple/src/deployment/runtime.ts @@ -102,18 +102,15 @@ async function deployAppleApp( signal: AbortSignal, install?: AppDeploymentInstaller, ): Promise { - // Preserve reinstall's established partial-failure boundary: the old route resolved and - // removed the selected app before it materialized the replacement artifact. That ordering is - // observable when artifact preparation fails, so it belongs to the platform deployment facet. if (input.replaceExisting) { return await host.appleDeployment.withInvalidatedAppResolutionCache(device, async () => { const bundleId = await host.appleDeployment.resolveAppBundleId(device, input.app); - await uninstallAppleApp(host, device, bundleId, signal); const artifact = await host.appleDeployment.prepareArtifact( { source: { kind: 'path', path: input.appPath } }, { appIdentifierHint: input.app, signal }, ); try { + await uninstallAppleApp(host, device, bundleId, signal); if (install) await install(artifact, signal); else await installAppleApp(host, device, artifact.installablePath, signal); return { bundleId, launchTarget: bundleId }; diff --git a/test/integration/provider-scenarios/ios-lifecycle.test.ts b/test/integration/provider-scenarios/ios-lifecycle.test.ts index 1c4bc2536f..c8e8900ad4 100644 --- a/test/integration/provider-scenarios/ios-lifecycle.test.ts +++ b/test/integration/provider-scenarios/ios-lifecycle.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; import { assertFlatToolCall, assertRpcOk } from './assertions.ts'; @@ -402,6 +403,22 @@ test('Provider-backed integration iOS physical reinstall uses scripted devicectl PROVIDER_SCENARIO_IOS_REINSTALL_DEVICE.id, appPath, ]); + + const callsBeforeCorrupt = appleTool.calls.length; + const corruptIpa = path.join(path.dirname(appPath), 'corrupt.ipa'); + fs.writeFileSync(corruptIpa, 'not a zip archive'); + const corrupt = await daemon.callCommand('reinstall', ['com.example.demo', corruptIpa], { + platform: 'ios', + udid: PROVIDER_SCENARIO_IOS_REINSTALL_DEVICE.id, + }); + assert.notEqual(corrupt.statusCode, 200, JSON.stringify(corrupt.json)); + assert.ok(corrupt.json?.error, JSON.stringify(corrupt.json)); + const laterCalls = appleTool.calls.slice(callsBeforeCorrupt); + assert.equal( + laterCalls.some((call) => call.includes('uninstall') || call.includes('install')), + false, + `Corrupt replacement must not reach uninstall or install: ${JSON.stringify(laterCalls)}`, + ); }, ); }); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index a93e539340..0b86af9c20 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -685,6 +685,7 @@ agent-device reinstall com.example.app ./build/MyApp.app --platform ios ``` - `reinstall ` uninstalls and installs in one command, for login/logout resets and deterministic test setup. Device coverage, formats, and remote upload match `install`. +- On iOS, `reinstall` reads the new build before it removes the installed app, so a build that is invalid or unreadable leaves the app and its data in place. If the install itself fails after the uninstall, the app stays removed. ## App uninstall From c75dc272f3e49de90e3d01f321ed97ccafb9f96d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:26:12 +0100 Subject: [PATCH 2/8] fix(ios): scope reinstall guarantees to preparation failures --- packages/command-surface/src/management/install.ts | 2 +- .../platform-apple/src/deployment/runtime.test.ts | 11 ++++------- .../provider-scenarios/ios-lifecycle.test.ts | 5 ++++- website/docs/docs/commands.md | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/command-surface/src/management/install.ts b/packages/command-surface/src/management/install.ts index 6716632df4..2064050074 100644 --- a/packages/command-surface/src/management/install.ts +++ b/packages/command-surface/src/management/install.ts @@ -38,7 +38,7 @@ const installCommandMetadata = defineFieldCommandMetadata( const reinstallCommandMetadata = defineFieldCommandMetadata( 'reinstall', - 'Replace an installed app with a binary from a local path. This preserves the app identity while installing a new build on the selected device. Local Android and iOS install steps time out after 120s; the command allows 480s including device startup and uninstall. On iOS, a build that cannot be read leaves the installed app in place; a failure during install after the uninstall can still leave the app removed.', + 'Replace an installed app with a binary from a local path. This preserves the app identity while installing a new build on the selected device. Local Android and iOS install steps time out after 120s; the command allows 480s including device startup and uninstall. On iOS, a corrupt .ipa that cannot be unpacked leaves the installed app in place. An invalid app bundle or another install failure after uninstall can still leave the app removed.', { app: requiredField(stringField()), appPath: requiredField(stringField('Path to app binary.')), diff --git a/packages/platform-apple/src/deployment/runtime.test.ts b/packages/platform-apple/src/deployment/runtime.test.ts index 45c8c448f8..756e2e5a23 100644 --- a/packages/platform-apple/src/deployment/runtime.test.ts +++ b/packages/platform-apple/src/deployment/runtime.test.ts @@ -610,14 +610,14 @@ test('reinstall releases the prepared replacement when uninstall fails', async ( }); test('clears a concurrently repopulated fuzzy resolution after a preparation-failed Apple reinstall', async () => { - const cachedResolutions = new Map([['Maps', 'com.example.stale-before-uninstall']]); + const cachedResolutions = new Map([['Maps', 'com.example.stale-before-resolution']]); let nextResolution = 'com.example.current'; const resolveFuzzyTarget = vi.fn(async (target: string) => { const resolved = cachedResolutions.get(target) ?? nextResolution; cachedResolutions.set(target, resolved); return resolved; }); - const invalidateDuringUninstall = async (operation: () => Promise) => { + const invalidateDuringResolution = async (operation: () => Promise) => { cachedResolutions.clear(); try { return await operation(); @@ -627,7 +627,7 @@ test('clears a concurrently repopulated fuzzy resolution after a preparation-fai }; const resolveAppBundleId = vi.fn( async (_device: DeviceInfo, app: string) => - await invalidateDuringUninstall(async () => { + await invalidateDuringResolution(async () => { const bundleId = await resolveFuzzyTarget(app); expect(bundleId).toBe('com.example.current'); return bundleId; @@ -635,7 +635,7 @@ test('clears a concurrently repopulated fuzzy resolution after a preparation-fai ); const prepareArtifact = vi.fn(async () => { const repopulate = Promise.resolve().then(async () => { - nextResolution = 'com.example.stale-after-uninstall'; + nextResolution = 'com.example.stale-during-preparation'; await resolveFuzzyTarget('Maps'); }); await repopulate; @@ -670,9 +670,6 @@ test('clears a concurrently repopulated fuzzy resolution after a preparation-fai }), ).rejects.toThrow('replacement artifact is invalid'); - // The low-level uninstall scope clears its own cache, but a resolution racing artifact - // preparation can repopulate it. The whole reinstall scope must clear that stale value even - // when preparation fails before any install attempt. expect(cachedResolutions).toEqual(new Map()); expect(withInvalidatedAppResolutionCache).toHaveBeenCalledOnce(); expect(resolveFuzzyTarget).toHaveBeenCalledTimes(2); diff --git a/test/integration/provider-scenarios/ios-lifecycle.test.ts b/test/integration/provider-scenarios/ios-lifecycle.test.ts index c8e8900ad4..298906df20 100644 --- a/test/integration/provider-scenarios/ios-lifecycle.test.ts +++ b/test/integration/provider-scenarios/ios-lifecycle.test.ts @@ -412,7 +412,10 @@ test('Provider-backed integration iOS physical reinstall uses scripted devicectl udid: PROVIDER_SCENARIO_IOS_REINSTALL_DEVICE.id, }); assert.notEqual(corrupt.statusCode, 200, JSON.stringify(corrupt.json)); - assert.ok(corrupt.json?.error, JSON.stringify(corrupt.json)); + assert.match( + corrupt.json?.error?.message ?? '', + /End of central directory record signature not found/, + ); const laterCalls = appleTool.calls.slice(callsBeforeCorrupt); assert.equal( laterCalls.some((call) => call.includes('uninstall') || call.includes('install')), diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 0b86af9c20..62f85e1f2a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -685,7 +685,7 @@ agent-device reinstall com.example.app ./build/MyApp.app --platform ios ``` - `reinstall ` uninstalls and installs in one command, for login/logout resets and deterministic test setup. Device coverage, formats, and remote upload match `install`. -- On iOS, `reinstall` reads the new build before it removes the installed app, so a build that is invalid or unreadable leaves the app and its data in place. If the install itself fails after the uninstall, the app stays removed. +- On iOS, replacement archives are unpacked before the installed app is removed. If unpacking fails, the app and its data stay in place. An invalid app bundle or another install failure after uninstall can still leave the app removed. ## App uninstall From 2871a7f378a3d25f3c21f4e68bb56e9c94ce05ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:33:10 +0100 Subject: [PATCH 3/8] fix(android): prepare the replacement before uninstalling on reinstall A replacement that cannot be materialized no longer removes the installed app. Cancellation after preparation also stops before the uninstall. Co-Authored-By: Claude Sonnet 5.5 --- .../src/deployment/runtime.test.ts | 63 ++++++++++++++++--- .../src/deployment/runtime.ts | 10 +-- .../android-lifecycle.test.ts | 40 ++++++++++++ 3 files changed, 100 insertions(+), 13 deletions(-) diff --git a/packages/platform-android/src/deployment/runtime.test.ts b/packages/platform-android/src/deployment/runtime.test.ts index f64c74f727..ee7bb148c8 100644 --- a/packages/platform-android/src/deployment/runtime.test.ts +++ b/packages/platform-android/src/deployment/runtime.test.ts @@ -132,7 +132,7 @@ test('waits for Android readiness before inspecting an install artifact', async expect(order).toEqual(['ready', 'prepare']); }); -test('preserves reinstall partial-failure ordering and whole-operation cache invalidation', async () => { +test('keeps the installed app when reinstall preparation fails and still invalidates the cache', async () => { const order: string[] = []; const cacheCalls: DeviceInfo[] = []; const withInvalidatedAppResolutionCache = async ( @@ -155,12 +155,9 @@ test('preserves reinstall partial-failure ordering and whole-operation cache inv }, prepareArtifact: async () => { order.push('prepare'); - throw new Error('replacement artifact is invalid'); + throw new AppError('INVALID_ARGS', 'replacement artifact is invalid'); }, }); - native.uninstallAndroidPackage.mockImplementationOnce(async () => { - order.push('uninstall'); - }); await expect( createAndroidAppDeploymentOperations({ @@ -172,11 +169,59 @@ test('preserves reinstall partial-failure ordering and whole-operation cache inv appPath: '/tmp/replacement.apk', replaceExisting: true, }), - ).rejects.toThrow('replacement artifact is invalid'); + ).rejects.toMatchObject({ + code: 'INVALID_ARGS', + message: 'replacement artifact is invalid', + }); - expect(order).toEqual(['cache-before', 'resolve', 'uninstall', 'prepare', 'cache-after']); + expect(order).toEqual(['cache-before', 'resolve', 'prepare', 'cache-after']); expect(cacheCalls).toEqual([device]); + expect(native.uninstallAndroidPackage).not.toHaveBeenCalled(); + expect(native.installAndroidArtifact).not.toHaveBeenCalled(); +}); + +test('does not uninstall when reinstall is cancelled after preparation', async () => { + const controller = new AbortController(); + const cleanup = vi.fn(async () => {}); + const host = hostFixture({ + prepareArtifact: async () => { + controller.abort(new Error('cancelled')); + return { installablePath: '/tmp/new.apk', cleanup }; + }, + }); + + await expect( + createAndroidAppDeploymentOperations({ host, device, signal: controller.signal }).deployApp?.({ + app: 'com.example.app', + appPath: '/tmp/new.apk', + replaceExisting: true, + }), + ).rejects.toThrow('cancelled'); + + expect(native.uninstallAndroidPackage).not.toHaveBeenCalled(); expect(native.installAndroidArtifact).not.toHaveBeenCalled(); + expect(cleanup).toHaveBeenCalledOnce(); +}); + +test('cleans the prepared artifact when the reinstall uninstall fails', async () => { + const cleanup = vi.fn(async () => {}); + const host = hostFixture({ + prepareArtifact: async () => ({ installablePath: '/tmp/new.apk', cleanup }), + }); + native.uninstallAndroidPackage.mockRejectedValueOnce( + new AppError('COMMAND_FAILED', 'adb uninstall failed'), + ); + + await expect( + createAndroidAppDeploymentOperations({ + host, + device, + signal: new AbortController().signal, + }).deployApp?.({ app: 'com.example.app', appPath: '/tmp/new.apk', replaceExisting: true }), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: 'adb uninstall failed' }); + + expect(native.installAndroidArtifact).not.toHaveBeenCalled(); + expect(cleanup).toHaveBeenCalledOnce(); }); test('keeps ordinary Android install successful when identity is unavailable', async () => { @@ -262,7 +307,7 @@ test('uninstall resolves, removes and invalidates on the device readiness return }); test.each([false, true])( - 'reinstall removes data before the replacement is materialized with a hosted installer: %s', + 'reinstall materializes the replacement before removing data with a hosted installer: %s', async (hosted) => { const events: string[] = []; const signal = new AbortController().signal; @@ -312,8 +357,8 @@ test.each([false, true])( ).toEqual({ packageName: 'com.example.app', launchTarget: 'com.example.app' }); expect(events).toEqual([ 'invalidate-before', - 'uninstall', 'materialize', + 'uninstall', 'install', 'cleanup', 'invalidate-after', diff --git a/packages/platform-android/src/deployment/runtime.ts b/packages/platform-android/src/deployment/runtime.ts index 7c4bdd10fe..da74fb5b68 100644 --- a/packages/platform-android/src/deployment/runtime.ts +++ b/packages/platform-android/src/deployment/runtime.ts @@ -102,9 +102,9 @@ async function deployAndroidApp( install?: AppDeploymentInstaller, ): Promise { if (input.replaceExisting) { - // Reinstall resolves its fuzzy target during uninstall. Keep the old whole-operation - // cache boundary here in the Android deployment owner: clear before boot/resolve/uninstall - // and after materialization/install, including partial failures. + // Reinstall resolves its fuzzy target before uninstall. Keep the whole-operation cache + // boundary here in the Android deployment owner: clear before boot/resolve/prepare/uninstall + // and after install, including partial failures. return await host.androidDeployment.withInvalidatedAppResolutionCache(device, async () => { let artifact: MaterializedAppSource | undefined; try { @@ -112,11 +112,13 @@ async function deployAndroidApp( await ensureAndroidReady(host, device, { headless: false }, signal); } const packageName = await host.androidDeployment.resolveAppPackage(device, input.app); - await uninstallAndroidPackage(host, device, packageName, signal); + // Prepare before the destructive uninstall so a materialization failure keeps the app. artifact = await host.androidDeployment.prepareArtifact( { source: { kind: 'path', path: input.appPath } }, { resolveIdentity: false, signal }, ); + signal.throwIfAborted(); + await uninstallAndroidPackage(host, device, packageName, signal); if (install) await install(artifact, signal); else await installAndroidArtifact(host, device, artifact.installablePath, undefined, signal); diff --git a/test/integration/provider-scenarios/android-lifecycle.test.ts b/test/integration/provider-scenarios/android-lifecycle.test.ts index 928db61851..16d6554473 100644 --- a/test/integration/provider-scenarios/android-lifecycle.test.ts +++ b/test/integration/provider-scenarios/android-lifecycle.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; +import { runCmd } from '@agent-device/host-kit/command'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import { arrayEqual, @@ -302,6 +303,45 @@ test('Provider-backed integration Android external ANR fails with actionable con ); }); +test('Provider-backed Android reinstall keeps the installed app when the archive has no installable', async () => { + const world = await createAndroidSettingsWorld(); + try { + const payloadDir = path.join(world.tempRoot, 'no-installable-payload'); + fs.mkdirSync(payloadDir, { recursive: true }); + fs.writeFileSync(path.join(payloadDir, 'README.txt'), 'not an apk'); + const archivePath = path.join(world.tempRoot, 'NoInstallable.zip'); + const zipped = await runCmd('zip', ['-q', archivePath, 'README.txt'], { + cwd: payloadDir, + allowFailure: true, + }); + assert.equal(zipped.exitCode, 0, zipped.stderr); + + await world.daemon.client().apps.open({ app: 'settings', ...world.selection }); + const callsBefore = world.adbCalls.length; + await assert.rejects( + world.daemon + .client() + .apps.reinstall({ app: 'com.example.demo', appPath: archivePath, ...world.selection }), + (error: unknown) => + (error as { code?: string }).code === 'INVALID_ARGS' && + String((error as Error).message).includes( + 'Expected Android installable (.apk or .aab) source', + ), + ); + + const reinstallCalls = world.adbCalls.slice(callsBefore); + assert.equal( + reinstallCalls.some((call) => call[0] === 'uninstall'), + false, + 'a replacement that cannot be materialized must not reach adb uninstall', + ); + assert.equal(world.apkInstallCalls.length, 0); + assert.equal(world.bundleInstallCalls.length, 0); + } finally { + await world.close(); + } +}); + async function runAndroidSetupAndInstallWorkflow( world: AndroidSettingsWorld, client: AgentDeviceClient, From cf656232b5291a9a25673b80722c9bfcd05e125f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:43:35 +0100 Subject: [PATCH 4/8] fix(reinstall): align shared provider and help semantics --- .../command-surface/src/management/install.ts | 2 +- .../platform-android/src/deployment/runtime.ts | 3 --- .../provider-scenarios/android-lifecycle.test.ts | 16 ++++++---------- .../limrun-deployment-cancellation.test.ts | 2 +- website/docs/docs/commands.md | 2 +- 5 files changed, 9 insertions(+), 16 deletions(-) diff --git a/packages/command-surface/src/management/install.ts b/packages/command-surface/src/management/install.ts index 2064050074..2e35229dd3 100644 --- a/packages/command-surface/src/management/install.ts +++ b/packages/command-surface/src/management/install.ts @@ -38,7 +38,7 @@ const installCommandMetadata = defineFieldCommandMetadata( const reinstallCommandMetadata = defineFieldCommandMetadata( 'reinstall', - 'Replace an installed app with a binary from a local path. This preserves the app identity while installing a new build on the selected device. Local Android and iOS install steps time out after 120s; the command allows 480s including device startup and uninstall. On iOS, a corrupt .ipa that cannot be unpacked leaves the installed app in place. An invalid app bundle or another install failure after uninstall can still leave the app removed.', + 'Replace an installed app with a binary from a local path. This preserves the app identity while installing a new build on the selected device. Local Android and iOS install steps time out after 120s; the command allows 480s including device startup and uninstall. On iOS, a corrupt .ipa that cannot be unpacked leaves the installed app in place. On Android, an archive that cannot be unpacked or contains no .apk or .aab also leaves it in place. An invalid app bundle, corrupt APK or another install failure after uninstall can still leave the app removed.', { app: requiredField(stringField()), appPath: requiredField(stringField('Path to app binary.')), diff --git a/packages/platform-android/src/deployment/runtime.ts b/packages/platform-android/src/deployment/runtime.ts index da74fb5b68..6564e2cc35 100644 --- a/packages/platform-android/src/deployment/runtime.ts +++ b/packages/platform-android/src/deployment/runtime.ts @@ -102,9 +102,6 @@ async function deployAndroidApp( install?: AppDeploymentInstaller, ): Promise { if (input.replaceExisting) { - // Reinstall resolves its fuzzy target before uninstall. Keep the whole-operation cache - // boundary here in the Android deployment owner: clear before boot/resolve/prepare/uninstall - // and after install, including partial failures. return await host.androidDeployment.withInvalidatedAppResolutionCache(device, async () => { let artifact: MaterializedAppSource | undefined; try { diff --git a/test/integration/provider-scenarios/android-lifecycle.test.ts b/test/integration/provider-scenarios/android-lifecycle.test.ts index 16d6554473..1922ad9b14 100644 --- a/test/integration/provider-scenarios/android-lifecycle.test.ts +++ b/test/integration/provider-scenarios/android-lifecycle.test.ts @@ -304,8 +304,7 @@ test('Provider-backed integration Android external ANR fails with actionable con }); test('Provider-backed Android reinstall keeps the installed app when the archive has no installable', async () => { - const world = await createAndroidSettingsWorld(); - try { + await withProviderScenarioResource(createAndroidSettingsWorld, async (world) => { const payloadDir = path.join(world.tempRoot, 'no-installable-payload'); fs.mkdirSync(payloadDir, { recursive: true }); fs.writeFileSync(path.join(payloadDir, 'README.txt'), 'not an apk'); @@ -322,11 +321,10 @@ test('Provider-backed Android reinstall keeps the installed app when the archive world.daemon .client() .apps.reinstall({ app: 'com.example.demo', appPath: archivePath, ...world.selection }), - (error: unknown) => - (error as { code?: string }).code === 'INVALID_ARGS' && - String((error as Error).message).includes( - 'Expected Android installable (.apk or .aab) source', - ), + { + code: 'INVALID_ARGS', + message: /Expected Android installable \(\.apk or \.aab\) source/, + }, ); const reinstallCalls = world.adbCalls.slice(callsBefore); @@ -337,9 +335,7 @@ test('Provider-backed Android reinstall keeps the installed app when the archive ); assert.equal(world.apkInstallCalls.length, 0); assert.equal(world.bundleInstallCalls.length, 0); - } finally { - await world.close(); - } + }); }); async function runAndroidSetupAndInstallWorkflow( diff --git a/test/integration/provider-scenarios/limrun-deployment-cancellation.test.ts b/test/integration/provider-scenarios/limrun-deployment-cancellation.test.ts index 68b969ada3..d8b2bf777c 100644 --- a/test/integration/provider-scenarios/limrun-deployment-cancellation.test.ts +++ b/test/integration/provider-scenarios/limrun-deployment-cancellation.test.ts @@ -117,8 +117,8 @@ for (const platform of ['android', 'ios'] as const) { basisCacheDir: expect.any(String), }); expect(deployment.events).toEqual([ - ...(replaceExisting ? ['uninstall'] : []), 'prepare', + ...(replaceExisting ? ['uninstall'] : []), 'sync', 'cleanup', ]); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 62f85e1f2a..37fde10571 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -685,7 +685,7 @@ agent-device reinstall com.example.app ./build/MyApp.app --platform ios ``` - `reinstall ` uninstalls and installs in one command, for login/logout resets and deterministic test setup. Device coverage, formats, and remote upload match `install`. -- On iOS, replacement archives are unpacked before the installed app is removed. If unpacking fails, the app and its data stay in place. An invalid app bundle or another install failure after uninstall can still leave the app removed. +- On iOS and Android, replacement archives are unpacked before the installed app is removed. If unpacking fails, the app and its data stay in place. An Android archive with no `.apk` or `.aab` also leaves the installed app in place. An invalid app bundle, corrupt APK or another install failure after uninstall can still leave the app removed. ## App uninstall From 4e5d112bf67dbeea003b61bfc27ef3148493b557 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 22:57:14 +0100 Subject: [PATCH 5/8] test(android): isolate reinstall preparation scenario --- .../android-lifecycle.test.ts | 36 ---------------- .../android-reinstall.test.ts | 42 +++++++++++++++++++ 2 files changed, 42 insertions(+), 36 deletions(-) create mode 100644 test/integration/provider-scenarios/android-reinstall.test.ts diff --git a/test/integration/provider-scenarios/android-lifecycle.test.ts b/test/integration/provider-scenarios/android-lifecycle.test.ts index 1922ad9b14..928db61851 100644 --- a/test/integration/provider-scenarios/android-lifecycle.test.ts +++ b/test/integration/provider-scenarios/android-lifecycle.test.ts @@ -2,7 +2,6 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; -import { runCmd } from '@agent-device/host-kit/command'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import { arrayEqual, @@ -303,41 +302,6 @@ test('Provider-backed integration Android external ANR fails with actionable con ); }); -test('Provider-backed Android reinstall keeps the installed app when the archive has no installable', async () => { - await withProviderScenarioResource(createAndroidSettingsWorld, async (world) => { - const payloadDir = path.join(world.tempRoot, 'no-installable-payload'); - fs.mkdirSync(payloadDir, { recursive: true }); - fs.writeFileSync(path.join(payloadDir, 'README.txt'), 'not an apk'); - const archivePath = path.join(world.tempRoot, 'NoInstallable.zip'); - const zipped = await runCmd('zip', ['-q', archivePath, 'README.txt'], { - cwd: payloadDir, - allowFailure: true, - }); - assert.equal(zipped.exitCode, 0, zipped.stderr); - - await world.daemon.client().apps.open({ app: 'settings', ...world.selection }); - const callsBefore = world.adbCalls.length; - await assert.rejects( - world.daemon - .client() - .apps.reinstall({ app: 'com.example.demo', appPath: archivePath, ...world.selection }), - { - code: 'INVALID_ARGS', - message: /Expected Android installable \(\.apk or \.aab\) source/, - }, - ); - - const reinstallCalls = world.adbCalls.slice(callsBefore); - assert.equal( - reinstallCalls.some((call) => call[0] === 'uninstall'), - false, - 'a replacement that cannot be materialized must not reach adb uninstall', - ); - assert.equal(world.apkInstallCalls.length, 0); - assert.equal(world.bundleInstallCalls.length, 0); - }); -}); - async function runAndroidSetupAndInstallWorkflow( world: AndroidSettingsWorld, client: AgentDeviceClient, diff --git a/test/integration/provider-scenarios/android-reinstall.test.ts b/test/integration/provider-scenarios/android-reinstall.test.ts new file mode 100644 index 0000000000..c2f32b93f5 --- /dev/null +++ b/test/integration/provider-scenarios/android-reinstall.test.ts @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'vitest'; +import { runCmd } from '@agent-device/host-kit/command'; +import { createAndroidSettingsWorld } from './android-world.ts'; +import { withProviderScenarioResource } from './harness.ts'; + +test('Provider-backed Android reinstall keeps the installed app when the archive has no installable', async () => { + await withProviderScenarioResource(createAndroidSettingsWorld, async (world) => { + const payloadDir = path.join(world.tempRoot, 'no-installable-payload'); + fs.mkdirSync(payloadDir, { recursive: true }); + fs.writeFileSync(path.join(payloadDir, 'README.txt'), 'not an apk'); + const archivePath = path.join(world.tempRoot, 'NoInstallable.zip'); + const zipped = await runCmd('zip', ['-q', archivePath, 'README.txt'], { + cwd: payloadDir, + allowFailure: true, + }); + assert.equal(zipped.exitCode, 0, zipped.stderr); + + await world.daemon.client().apps.open({ app: 'settings', ...world.selection }); + const callsBefore = world.adbCalls.length; + await assert.rejects( + world.daemon + .client() + .apps.reinstall({ app: 'com.example.demo', appPath: archivePath, ...world.selection }), + { + code: 'INVALID_ARGS', + message: /Expected Android installable \(\.apk or \.aab\) source/, + }, + ); + + const reinstallCalls = world.adbCalls.slice(callsBefore); + assert.equal( + reinstallCalls.some((call) => call[0] === 'uninstall'), + false, + 'a replacement that cannot be materialized must not reach adb uninstall', + ); + assert.equal(world.apkInstallCalls.length, 0); + assert.equal(world.bundleInstallCalls.length, 0); + }); +}); From 88bfc20263d77baedc88db4c4cdb9349bc7fe740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 23:16:17 +0100 Subject: [PATCH 6/8] test(ios): align legacy Limrun reinstall preparation order --- src/core/interactors/limrun-ios-runner-parity.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/interactors/limrun-ios-runner-parity.test.ts b/src/core/interactors/limrun-ios-runner-parity.test.ts index a69791a79e..e5b5fad170 100644 --- a/src/core/interactors/limrun-ios-runner-parity.test.ts +++ b/src/core/interactors/limrun-ios-runner-parity.test.ts @@ -133,7 +133,7 @@ test('remote tools execute the shared text-size, status bar and biometric settin ]); }); -test('shared deployment resolves remote app names and uninstalls before uploading a replacement', async () => { +test('shared deployment prepares before uninstalling and uploading a replacement', async () => { const f = await fixture(); const { createAppleToolHost } = await import('../../platform-runtime-apple-tool-host.ts'); const { createAppleAppDeploymentExecutor } = @@ -183,8 +183,8 @@ test('shared deployment resolves remote app names and uninstalls before uploadin }), ).toMatchObject({ bundleId: 'com.apple.Preferences' }); expect(order).toEqual([ - 'uninstall:com.apple.Preferences', 'materialize', + 'uninstall:com.apple.Preferences', 'upload-and-install', 'cleanup', ]); From 24a20eb9ea017b8cd09193dbcad470b40f8fbc9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 13 Nov 2026 23:57:23 +0100 Subject: [PATCH 7/8] test(apple): cover cancellation after reinstall preparation --- .../platform-apple/src/deployment/runtime.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/platform-apple/src/deployment/runtime.test.ts b/packages/platform-apple/src/deployment/runtime.test.ts index 756e2e5a23..540e4934b8 100644 --- a/packages/platform-apple/src/deployment/runtime.test.ts +++ b/packages/platform-apple/src/deployment/runtime.test.ts @@ -601,6 +601,21 @@ test('reinstall keeps the installed app when cancelled during preparation', asyn expect(events).toEqual(['prepare']); }); +test('reinstall releases the prepared replacement when cancelled after preparation', async () => { + const controller = new AbortController(); + const cancellation = new Error('cancelled after preparation'); + const { events, reinstall } = reinstallHarness({ + signal: controller.signal, + prepare: async () => { + controller.abort(cancellation); + }, + }); + + await expect(reinstall()).rejects.toBe(cancellation); + + expect(events).toEqual(['prepare', 'cleanup']); +}); + test('reinstall releases the prepared replacement when uninstall fails', async () => { const { events, reinstall } = reinstallHarness({ uninstallExitCode: 1 }); From 9d7993318de5d202ecb7c653ff099baca1f43e8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 14 Nov 2026 00:49:18 +0100 Subject: [PATCH 8/8] test(apple): assert typed reinstall archive preparation failure --- .../provider-scenarios/ios-lifecycle.test.ts | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/test/integration/provider-scenarios/ios-lifecycle.test.ts b/test/integration/provider-scenarios/ios-lifecycle.test.ts index 298906df20..1873a030d6 100644 --- a/test/integration/provider-scenarios/ios-lifecycle.test.ts +++ b/test/integration/provider-scenarios/ios-lifecycle.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { test } from 'vitest'; +import { runCmd } from '@agent-device/host-kit/command'; import { assertFlatToolCall, assertRpcOk } from './assertions.ts'; import { createIosBottomTabsSnapshotWorld, @@ -404,23 +405,22 @@ test('Provider-backed integration iOS physical reinstall uses scripted devicectl appPath, ]); - const callsBeforeCorrupt = appleTool.calls.length; - const corruptIpa = path.join(path.dirname(appPath), 'corrupt.ipa'); - fs.writeFileSync(corruptIpa, 'not a zip archive'); - const corrupt = await daemon.callCommand('reinstall', ['com.example.demo', corruptIpa], { + const callsBeforeInvalidArchive = appleTool.calls.length; + const archiveDirectory = path.dirname(appPath); + fs.writeFileSync(path.join(archiveDirectory, 'README.txt'), 'no app bundle'); + const invalidIpa = path.join(archiveDirectory, 'no-app.ipa'); + await runCmd('zip', ['-q', invalidIpa, 'README.txt'], { cwd: archiveDirectory }); + const invalid = await daemon.callCommand('reinstall', ['com.example.demo', invalidIpa], { platform: 'ios', udid: PROVIDER_SCENARIO_IOS_REINSTALL_DEVICE.id, }); - assert.notEqual(corrupt.statusCode, 200, JSON.stringify(corrupt.json)); - assert.match( - corrupt.json?.error?.message ?? '', - /End of central directory record signature not found/, - ); - const laterCalls = appleTool.calls.slice(callsBeforeCorrupt); + assert.equal(invalid.statusCode, 400, JSON.stringify(invalid.json)); + assert.equal(invalid.json?.error?.data?.code, 'INVALID_ARGS', JSON.stringify(invalid.json)); + const laterCalls = appleTool.calls.slice(callsBeforeInvalidArchive); assert.equal( laterCalls.some((call) => call.includes('uninstall') || call.includes('install')), false, - `Corrupt replacement must not reach uninstall or install: ${JSON.stringify(laterCalls)}`, + `Archive without an app must not reach uninstall or install: ${JSON.stringify(laterCalls)}`, ); }, );