-
-
Notifications
You must be signed in to change notification settings - Fork 272
Expand file tree
/
Copy pathbuild_run_sim.ts
More file actions
521 lines (464 loc) · 18.3 KB
/
build_run_sim.ts
File metadata and controls
521 lines (464 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/**
* Simulator Build & Run Plugin: Build Run Simulator (Unified)
*
* Builds and runs an app from a project or workspace on a specific simulator by UUID or name.
* Accepts mutually exclusive `projectPath` or `workspacePath`.
* Accepts mutually exclusive `simulatorId` or `simulatorName`.
*/
import { z } from 'zod';
import { ToolResponse, SharedBuildParams, XcodePlatform } from '../../../types/common.ts';
import { log } from '../../../utils/logging/index.ts';
import { getDefaultCommandExecutor } from '../../../utils/execution/index.ts';
import { createSessionAwareTool } from '../../../utils/typed-tool-factory.ts';
import { createTextResponse } from '../../../utils/responses/index.ts';
import { executeXcodeBuildCommand } from '../../../utils/build/index.ts';
import type { CommandExecutor } from '../../../utils/execution/index.ts';
import { determineSimulatorUuid } from '../../../utils/simulator-utils.ts';
import { nullifyEmptyStrings } from '../../../utils/schema-helpers.ts';
// Unified schema: XOR between projectPath and workspacePath, and XOR between simulatorId and simulatorName
const baseOptions = {
scheme: z.string().describe('The scheme to use (Required)'),
simulatorId: z
.string()
.optional()
.describe(
'UUID of the simulator (from list_sims). Provide EITHER this OR simulatorName, not both',
),
simulatorName: z
.string()
.optional()
.describe(
"Name of the simulator (e.g., 'iPhone 16'). Provide EITHER this OR simulatorId, not both",
),
configuration: z.string().optional().describe('Build configuration (Debug, Release, etc.)'),
derivedDataPath: z
.string()
.optional()
.describe('Path where build products and other derived data will go'),
extraArgs: z.array(z.string()).optional().describe('Additional xcodebuild arguments'),
useLatestOS: z
.boolean()
.optional()
.describe('Whether to use the latest OS version for the named simulator'),
preferXcodebuild: z
.boolean()
.optional()
.describe(
'If true, prefers xcodebuild over the experimental incremental build system, useful for when incremental build system fails.',
),
};
const baseSchemaObject = z.object({
projectPath: z
.string()
.optional()
.describe('Path to .xcodeproj file. Provide EITHER this OR workspacePath, not both'),
workspacePath: z
.string()
.optional()
.describe('Path to .xcworkspace file. Provide EITHER this OR projectPath, not both'),
...baseOptions,
});
const baseSchema = z.preprocess(nullifyEmptyStrings, baseSchemaObject);
const buildRunSimulatorSchema = baseSchema
.refine((val) => val.projectPath !== undefined || val.workspacePath !== undefined, {
message: 'Either projectPath or workspacePath is required.',
})
.refine((val) => !(val.projectPath !== undefined && val.workspacePath !== undefined), {
message: 'projectPath and workspacePath are mutually exclusive. Provide only one.',
})
.refine((val) => val.simulatorId !== undefined || val.simulatorName !== undefined, {
message: 'Either simulatorId or simulatorName is required.',
})
.refine((val) => !(val.simulatorId !== undefined && val.simulatorName !== undefined), {
message: 'simulatorId and simulatorName are mutually exclusive. Provide only one.',
});
export type BuildRunSimulatorParams = z.infer<typeof buildRunSimulatorSchema>;
// Internal logic for building Simulator apps.
async function _handleSimulatorBuildLogic(
params: BuildRunSimulatorParams,
executor: CommandExecutor,
executeXcodeBuildCommandFn: typeof executeXcodeBuildCommand = executeXcodeBuildCommand,
): Promise<ToolResponse> {
const projectType = params.projectPath ? 'project' : 'workspace';
const filePath = params.projectPath ?? params.workspacePath;
// Log warning if useLatestOS is provided with simulatorId
if (params.simulatorId && params.useLatestOS !== undefined) {
log(
'warning',
`useLatestOS parameter is ignored when using simulatorId (UUID implies exact device/OS)`,
);
}
log(
'info',
`Starting iOS Simulator build for scheme ${params.scheme} from ${projectType}: ${filePath}`,
);
// Create SharedBuildParams object with required configuration property
const sharedBuildParams: SharedBuildParams = {
workspacePath: params.workspacePath,
projectPath: params.projectPath,
scheme: params.scheme,
configuration: params.configuration ?? 'Debug',
derivedDataPath: params.derivedDataPath,
extraArgs: params.extraArgs,
};
return executeXcodeBuildCommandFn(
sharedBuildParams,
{
platform: XcodePlatform.iOSSimulator,
simulatorId: params.simulatorId,
simulatorName: params.simulatorName,
useLatestOS: params.simulatorId ? false : params.useLatestOS,
logPrefix: 'iOS Simulator Build',
},
params.preferXcodebuild as boolean,
'build',
executor,
);
}
// Exported business logic function for building and running iOS Simulator apps.
export async function build_run_simLogic(
params: BuildRunSimulatorParams,
executor: CommandExecutor,
executeXcodeBuildCommandFn: typeof executeXcodeBuildCommand = executeXcodeBuildCommand,
): Promise<ToolResponse> {
const projectType = params.projectPath ? 'project' : 'workspace';
const filePath = params.projectPath ?? params.workspacePath;
log(
'info',
`Starting iOS Simulator build and run for scheme ${params.scheme} from ${projectType}: ${filePath}`,
);
try {
// --- Build Step ---
const buildResult = await _handleSimulatorBuildLogic(
params,
executor,
executeXcodeBuildCommandFn,
);
if (buildResult.isError) {
return buildResult; // Return the build error
}
// --- Get App Path Step ---
// Create the command array for xcodebuild with -showBuildSettings option
const command = ['xcodebuild', '-showBuildSettings'];
// Add the workspace or project
if (params.workspacePath) {
command.push('-workspace', params.workspacePath);
} else if (params.projectPath) {
command.push('-project', params.projectPath);
}
// Add the scheme and configuration
command.push('-scheme', params.scheme);
command.push('-configuration', params.configuration ?? 'Debug');
// Handle destination for simulator
let destinationString: string;
if (params.simulatorId) {
destinationString = `platform=iOS Simulator,id=${params.simulatorId}`;
} else if (params.simulatorName) {
destinationString = `platform=iOS Simulator,name=${params.simulatorName}${(params.useLatestOS ?? true) ? ',OS=latest' : ''}`;
} else {
// This shouldn't happen due to validation, but handle it
destinationString = 'platform=iOS Simulator';
}
command.push('-destination', destinationString);
// Add derived data path if provided
if (params.derivedDataPath) {
command.push('-derivedDataPath', params.derivedDataPath);
}
// Add extra args if provided
if (params.extraArgs && params.extraArgs.length > 0) {
command.push(...params.extraArgs);
}
// Execute the command directly
const result = await executor(command, 'Get App Path', true, undefined);
// If there was an error with the command execution, return it
if (!result.success) {
return createTextResponse(
`Build succeeded, but failed to get app path: ${result.error ?? 'Unknown error'}`,
true,
);
}
// Parse the output to extract the app path
const buildSettingsOutput = result.output;
// Try both approaches to get app path - first the project approach (CODESIGNING_FOLDER_PATH)
let appBundlePath: string | null = null;
// Project approach: Extract CODESIGNING_FOLDER_PATH from build settings to get app path
const appPathMatch = buildSettingsOutput.match(/CODESIGNING_FOLDER_PATH = (.+\.app)/);
if (appPathMatch?.[1]) {
appBundlePath = appPathMatch[1].trim();
} else {
// Workspace approach: Extract BUILT_PRODUCTS_DIR and FULL_PRODUCT_NAME
const builtProductsDirMatch = buildSettingsOutput.match(
/^\s*BUILT_PRODUCTS_DIR\s*=\s*(.+)$/m,
);
const fullProductNameMatch = buildSettingsOutput.match(/^\s*FULL_PRODUCT_NAME\s*=\s*(.+)$/m);
if (builtProductsDirMatch && fullProductNameMatch) {
const builtProductsDir = builtProductsDirMatch[1].trim();
const fullProductName = fullProductNameMatch[1].trim();
appBundlePath = `${builtProductsDir}/${fullProductName}`;
}
}
if (!appBundlePath) {
return createTextResponse(
`Build succeeded, but could not find app path in build settings.`,
true,
);
}
log('info', `App bundle path for run: ${appBundlePath}`);
// --- Find/Boot Simulator Step ---
// Use our helper to determine the simulator UUID
const uuidResult = await determineSimulatorUuid(
{ simulatorUuid: params.simulatorId, simulatorName: params.simulatorName },
executor,
);
if (uuidResult.error) {
return createTextResponse(`Build succeeded, but ${uuidResult.error.content[0].text}`, true);
}
if (uuidResult.warning) {
log('warning', uuidResult.warning);
}
const simulatorUuid = uuidResult.uuid;
if (!simulatorUuid) {
return createTextResponse(
'Build succeeded, but no simulator specified and failed to find a suitable one.',
true,
);
}
// Check simulator state and boot if needed
try {
log('info', `Checking simulator state for UUID: ${simulatorUuid}`);
const simulatorListResult = await executor(
['xcrun', 'simctl', 'list', 'devices', 'available', '--json'],
'List Simulators',
);
if (!simulatorListResult.success) {
throw new Error(simulatorListResult.error ?? 'Failed to list simulators');
}
const simulatorsData = JSON.parse(simulatorListResult.output) as {
devices: Record<string, unknown[]>;
};
let targetSimulator: { udid: string; name: string; state: string } | null = null;
// Find the target simulator
for (const runtime in simulatorsData.devices) {
const devices = simulatorsData.devices[runtime];
if (Array.isArray(devices)) {
for (const device of devices) {
if (
typeof device === 'object' &&
device !== null &&
'udid' in device &&
'name' in device &&
'state' in device &&
typeof device.udid === 'string' &&
typeof device.name === 'string' &&
typeof device.state === 'string' &&
device.udid === simulatorUuid
) {
targetSimulator = {
udid: device.udid,
name: device.name,
state: device.state,
};
break;
}
}
if (targetSimulator) break;
}
}
if (!targetSimulator) {
return createTextResponse(
`Build succeeded, but could not find simulator with UUID: ${simulatorUuid}`,
true,
);
}
// Boot if needed
if (targetSimulator.state !== 'Booted') {
log('info', `Booting simulator ${targetSimulator.name}...`);
const bootResult = await executor(
['xcrun', 'simctl', 'boot', simulatorUuid],
'Boot Simulator',
);
if (!bootResult.success) {
throw new Error(bootResult.error ?? 'Failed to boot simulator');
}
} else {
log('info', `Simulator ${simulatorUuid} is already booted`);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('error', `Error checking/booting simulator: ${errorMessage}`);
return createTextResponse(
`Build succeeded, but error checking/booting simulator: ${errorMessage}`,
true,
);
}
// --- Open Simulator UI Step ---
try {
log('info', 'Opening Simulator app');
const openResult = await executor(['open', '-a', 'Simulator'], 'Open Simulator App');
if (!openResult.success) {
throw new Error(openResult.error ?? 'Failed to open Simulator app');
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('warning', `Warning: Could not open Simulator app: ${errorMessage}`);
// Don't fail the whole operation for this
}
// --- Install App Step ---
try {
log('info', `Installing app at path: ${appBundlePath} to simulator: ${simulatorUuid}`);
const installResult = await executor(
['xcrun', 'simctl', 'install', simulatorUuid, appBundlePath],
'Install App',
);
if (!installResult.success) {
throw new Error(installResult.error ?? 'Failed to install app');
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('error', `Error installing app: ${errorMessage}`);
return createTextResponse(
`Build succeeded, but error installing app on simulator: ${errorMessage}`,
true,
);
}
// --- Get Bundle ID Step ---
let bundleId;
try {
log('info', `Extracting bundle ID from app: ${appBundlePath}`);
// Try multiple methods to get bundle ID - first PlistBuddy, then plutil, then defaults
let bundleIdResult = null;
// Method 1: PlistBuddy (most reliable)
try {
bundleIdResult = await executor(
[
'/usr/libexec/PlistBuddy',
'-c',
'Print :CFBundleIdentifier',
`${appBundlePath}/Info.plist`,
],
'Get Bundle ID with PlistBuddy',
);
if (bundleIdResult.success) {
bundleId = bundleIdResult.output.trim();
}
} catch {
// Continue to next method
}
// Method 2: plutil (workspace approach)
if (!bundleId) {
try {
bundleIdResult = await executor(
['plutil', '-extract', 'CFBundleIdentifier', 'raw', `${appBundlePath}/Info.plist`],
'Get Bundle ID with plutil',
);
if (bundleIdResult?.success) {
bundleId = bundleIdResult.output?.trim();
}
} catch {
// Continue to next method
}
}
// Method 3: defaults (fallback)
if (!bundleId) {
try {
bundleIdResult = await executor(
['defaults', 'read', `${appBundlePath}/Info`, 'CFBundleIdentifier'],
'Get Bundle ID with defaults',
);
if (bundleIdResult?.success) {
bundleId = bundleIdResult.output?.trim();
}
} catch {
// All methods failed
}
}
if (!bundleId) {
throw new Error('Could not extract bundle ID from Info.plist using any method');
}
log('info', `Bundle ID for run: ${bundleId}`);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('error', `Error getting bundle ID: ${errorMessage}`);
return createTextResponse(
`Build and install succeeded, but error getting bundle ID: ${errorMessage}`,
true,
);
}
// --- Launch App Step ---
try {
log('info', `Launching app with bundle ID: ${bundleId} on simulator: ${simulatorUuid}`);
const launchResult = await executor(
['xcrun', 'simctl', 'launch', simulatorUuid, bundleId],
'Launch App',
);
if (!launchResult.success) {
throw new Error(launchResult.error ?? 'Failed to launch app');
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('error', `Error launching app: ${errorMessage}`);
return createTextResponse(
`Build and install succeeded, but error launching app on simulator: ${errorMessage}`,
true,
);
}
// --- Success ---
log('info', '✅ iOS simulator build & run succeeded.');
const target = params.simulatorId
? `simulator UUID '${params.simulatorId}'`
: `simulator name '${params.simulatorName}'`;
const sourceType = params.projectPath ? 'project' : 'workspace';
const sourcePath = params.projectPath ?? params.workspacePath;
return {
content: [
{
type: 'text',
text: `✅ iOS simulator build and run succeeded for scheme ${params.scheme} from ${sourceType} ${sourcePath} targeting ${target}.
The app (${bundleId}) is now running in the iOS Simulator.
If you don't see the simulator window, it may be hidden behind other windows. The Simulator app should be open.
Next Steps:
- Option 1: Capture structured logs only (app continues running):
start_simulator_log_capture({ simulatorUuid: '${simulatorUuid}', bundleId: '${bundleId}' })
- Option 2: Capture both console and structured logs (app will restart):
start_simulator_log_capture({ simulatorUuid: '${simulatorUuid}', bundleId: '${bundleId}', captureConsole: true })
- Option 3: Launch app with logs in one step (for a fresh start):
launch_app_with_logs_in_simulator({ simulatorUuid: '${simulatorUuid}', bundleId: '${bundleId}' })
When done with any option, use: stop_sim_log_cap({ logSessionId: 'SESSION_ID' })`,
},
],
isError: false,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('error', `Error in iOS Simulator build and run: ${errorMessage}`);
return createTextResponse(`Error in iOS Simulator build and run: ${errorMessage}`, true);
}
}
const publicSchemaObject = baseSchemaObject.omit({
projectPath: true,
workspacePath: true,
scheme: true,
configuration: true,
simulatorId: true,
simulatorName: true,
useLatestOS: true,
} as const);
export default {
name: 'build_run_sim',
description: 'Builds and runs an app on an iOS simulator.',
schema: publicSchemaObject.shape,
handler: createSessionAwareTool<BuildRunSimulatorParams>({
internalSchema: buildRunSimulatorSchema as unknown as z.ZodType<BuildRunSimulatorParams>,
logicFunction: build_run_simLogic,
getExecutor: getDefaultCommandExecutor,
requirements: [
{ allOf: ['scheme'], message: 'scheme is required' },
{ oneOf: ['projectPath', 'workspacePath'], message: 'Provide a project or workspace' },
{ oneOf: ['simulatorId', 'simulatorName'], message: 'Provide simulatorId or simulatorName' },
],
exclusivePairs: [
['projectPath', 'workspacePath'],
['simulatorId', 'simulatorName'],
],
}),
};