diff --git a/packages/command-surface/src/management/install.ts b/packages/command-surface/src/management/install.ts index ad2cb4f6f3..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.', + '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.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..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 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. return await host.androidDeployment.withInvalidatedAppResolutionCache(device, async () => { let artifact: MaterializedAppSource | undefined; try { @@ -112,11 +109,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/packages/platform-apple/src/deployment/runtime.test.ts b/packages/platform-apple/src/deployment/runtime.test.ts index 82502afb1f..540e4934b8 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,48 +528,111 @@ 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 }; +} - expect(order).toEqual(['uninstall', 'prepare']); +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(events).toEqual(['prepare']); +}); + +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 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('clears a concurrently repopulated fuzzy resolution after a partial-failed Apple reinstall', async () => { - const cachedResolutions = new Map([['Maps', 'com.example.stale-before-uninstall']]); +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-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(); @@ -576,7 +642,7 @@ test('clears a concurrently repopulated fuzzy resolution after a partial-failed }; 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; @@ -584,7 +650,7 @@ test('clears a concurrently repopulated fuzzy resolution after a partial-failed ); 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; @@ -619,9 +685,6 @@ test('clears a concurrently repopulated fuzzy resolution after a partial-failed }), ).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); @@ -686,7 +749,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 +804,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/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', ]); 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); + }); +}); diff --git a/test/integration/provider-scenarios/ios-lifecycle.test.ts b/test/integration/provider-scenarios/ios-lifecycle.test.ts index 1c4bc2536f..1873a030d6 100644 --- a/test/integration/provider-scenarios/ios-lifecycle.test.ts +++ b/test/integration/provider-scenarios/ios-lifecycle.test.ts @@ -1,6 +1,8 @@ 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, @@ -402,6 +404,24 @@ test('Provider-backed integration iOS physical reinstall uses scripted devicectl PROVIDER_SCENARIO_IOS_REINSTALL_DEVICE.id, appPath, ]); + + 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.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, + `Archive without an app must not reach uninstall or install: ${JSON.stringify(laterCalls)}`, + ); }, ); }); 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 a93e539340..37fde10571 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 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