Skip to content
2 changes: 1 addition & 1 deletion packages/command-surface/src/management/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.')),
Expand Down
63 changes: 54 additions & 9 deletions packages/platform-android/src/deployment/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Result>(
Expand All @@ -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({
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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',
Expand Down
7 changes: 3 additions & 4 deletions packages/platform-android/src/deployment/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,21 +102,20 @@ async function deployAndroidApp(
install?: AppDeploymentInstaller,
): Promise<AppDeploymentResult> {
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 {
if (device.booted !== true) {
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);
Expand Down
131 changes: 97 additions & 34 deletions packages/platform-apple/src/deployment/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<void>;
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();
Comment thread
thymikee marked this conversation as resolved.
Resolved
},
});

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 <Result>(operation: () => Promise<Result>) => {
const invalidateDuringResolution = async <Result>(operation: () => Promise<Result>) => {
cachedResolutions.clear();
try {
return await operation();
Expand All @@ -576,15 +642,15 @@ 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;
}),
);
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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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',
Expand Down
5 changes: 1 addition & 4 deletions packages/platform-apple/src/deployment/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,15 @@ async function deployAppleApp(
signal: AbortSignal,
install?: AppDeploymentInstaller,
): Promise<AppDeploymentResult> {
// 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 };
Expand Down
4 changes: 2 additions & 2 deletions src/core/interactors/limrun-ios-runner-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } =
Expand Down Expand Up @@ -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',
]);
Expand Down
Loading
Loading