Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: fold scaffoldIOS into xcodeScaffold (#5724)

Adam Eivy7fd9f31a8338
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index aab01a5bb9..02d86756ba 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -284,7 +284,6 @@ describe('every cwd-passing spawn pins PWD', () => {
['services/dbAdmin.js', 'psql/pg_dump, not an AI CLI'],
['routes/scaffold.js', 'npm/git scaffolding, not an AI CLI'],
['routes/scaffoldVite.js', 'npm scaffolding, not an AI CLI'],
- ['routes/scaffoldIOS.js', 'xcodegen, not an AI CLI'],
['services/xcodeScaffold.js', 'xcodegen, not an AI CLI'],
['routes/apps/launch.js', "detached launch into the user's own terminal; the CLI reads process.cwd()"],
]);
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
index 932d292125..18a70f0ddb 100644
--- a/server/routes/scaffold.js
+++ b/server/routes/scaffold.js
@@ -13,7 +13,6 @@ import { ensureDir, expandHome } from '../lib/fileUtils.js';
import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';
import { scaffoldVite } from './scaffoldVite.js';
import { scaffoldExpress } from './scaffoldExpress.js';
-import { scaffoldIOS } from './scaffoldIOS.js';
import { scaffoldXcode } from '../services/xcodeScaffold.js';
import { toTargetName } from '../services/xcodeScripts.js';
import { scaffoldPortOS } from './scaffoldPortOS.js';
@@ -286,7 +285,7 @@ async function scaffoldApp(req, res) {
} else if (template === 'express-api') {
await scaffoldExpress(repoPath, dirName, apiPort, addStep);
} else if (template === 'ios-native') {
- await scaffoldIOS(repoPath, name, dirName, addStep);
+ await scaffoldXcode(repoPath, name, dirName, addStep, { platforms: ['ios'] });
} else if (template === 'xcode-multiplatform') {
await scaffoldXcode(repoPath, name, dirName, addStep);
} else if (template === 'portos-stack') {
@@ -561,12 +560,7 @@ Thumbs.db
} else if (template === 'vite-express') {
pm2Names = [`${dirName}-ui`, `${dirName}-api`];
startCmds = ['npm run dev:all'];
- } else if (template === 'ios-native') {
- const tn = toTargetName(name);
- pm2Names = [];
- startCmds = [`open ${tn}.xcodeproj`];
- buildCmd = `xcodebuild build -project ${tn}.xcodeproj -scheme ${tn} -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO`;
- } else if (template === 'xcode-multiplatform') {
+ } else if (template === 'ios-native' || template === 'xcode-multiplatform') {
const tn = toTargetName(name);
pm2Names = [];
startCmds = [`open ${tn}.xcodeproj`];
diff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.js
index 997ff057ba..ffff41da05 100644
--- a/server/routes/scaffold.test.js
+++ b/server/routes/scaffold.test.js
@@ -51,7 +51,6 @@ vi.mock('../lib/workspaceRoots.js', () => ({
vi.mock('./scaffoldVite.js', () => ({ scaffoldVite: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./scaffoldExpress.js', () => ({ scaffoldExpress: vi.fn().mockResolvedValue(undefined) }));
-vi.mock('./scaffoldIOS.js', () => ({ scaffoldIOS: vi.fn().mockResolvedValue(undefined) }));
vi.mock('../services/xcodeScaffold.js', () => ({ scaffoldXcode: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./scaffoldPortOS.js', () => ({ scaffoldPortOS: vi.fn().mockResolvedValue(undefined) }));
vi.mock('../services/xcodeScripts.js', () => ({ toTargetName: vi.fn(() => 'TestApp') }));
@@ -207,4 +206,19 @@ describe('POST /api/scaffold — request validation before filesystem mutation (
expect.any(Function)
);
});
+
+ it('routes the ios-native template to the same service, iOS-only', async () => {
+ const res = await request(app)
+ .post('/api/scaffold')
+ .send({ ...validBody, template: 'ios-native' });
+
+ expect(res.status).toBe(200);
+ expect(scaffoldXcode).toHaveBeenCalledWith(
+ join('/tmp/workspace', 'my-app'),
+ 'My App',
+ 'my-app',
+ expect.any(Function),
+ { platforms: ['ios'] }
+ );
+ });
});
diff --git a/server/routes/scaffoldIOS.js b/server/routes/scaffoldIOS.js
deleted file mode 100644
index ad6b664a49..0000000000
--- a/server/routes/scaffoldIOS.js
+++ /dev/null
@@ -1,211 +0,0 @@
-import { chmod, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { promisify } from 'util';
-import { exec } from '../lib/childProcess.js';
-import { ensureDir, ensureDirs } from '../lib/fileUtils.js';
-import { writeAgentInstructions } from '../lib/agentInstructionsFile.js';
-import {
- XCODE_TEAM_ID, XCODE_BUNDLE_PREFIX, XCODE_ENV_EXAMPLE,
- generateDeployScript, toBundleId, toTargetName,
-} from '../services/xcodeScripts.js';
-
-const execAsync = promisify(exec);
-
-export async function scaffoldIOS(repoPath, name, dirName, addStep) {
- const bundleId = toBundleId(name);
- const teamId = XCODE_TEAM_ID;
- const targetName = toTargetName(name);
-
- // project.yml (XcodeGen source of truth)
- await writeFile(join(repoPath, 'project.yml'), `name: ${targetName}
-options:
- bundleIdPrefix: ${XCODE_BUNDLE_PREFIX}
- deploymentTarget:
- iOS: "17.0"
- xcodeVersion: "16.0"
- generateEmptyDirectories: true
-
-settings:
- base:
- DEVELOPMENT_TEAM: ${teamId}
- MARKETING_VERSION: "1.0.0"
- CURRENT_PROJECT_VERSION: 1
- SWIFT_VERSION: "5.9"
-
-targets:
- ${targetName}:
- type: application
- platform: iOS
- sources:
- - path: ${targetName}
- excludes:
- - Preview Content/PreviewAssets.xcassets
- - path: ${targetName}/Preview Content/PreviewAssets.xcassets
- buildPhase: none
- settings:
- base:
- PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}
- INFOPLIST_FILE: ${targetName}/Info.plist
- ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
- INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
- INFOPLIST_KEY_UISupportedInterfaceOrientations: "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"
- INFOPLIST_KEY_UILaunchScreen_Generation: true
- DEVELOPMENT_ASSET_PATHS: "\\"${targetName}/Preview Content\\""
- GENERATE_INFOPLIST_FILE: true
- scheme:
- testTargets:
- - ${targetName}Tests
-
- ${targetName}Tests:
- type: bundle.unit-test
- platform: iOS
- sources:
- - path: ${targetName}Tests
- dependencies:
- - target: ${targetName}
- settings:
- base:
- PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}Tests
- GENERATE_INFOPLIST_FILE: true
- TEST_HOST: "$(BUILT_PRODUCTS_DIR)/${targetName}.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/${targetName}"
- BUNDLE_LOADER: "$(TEST_HOST)"
-`);
-
- // Create source directories
- const srcDir = join(repoPath, targetName);
- const previewDir = join(srcDir, 'Preview Content');
- const testsDir = join(repoPath, `${targetName}Tests`);
-
- await ensureDirs([srcDir, previewDir, testsDir]);
-
- // Info.plist
- await writeFile(join(srcDir, 'Info.plist'), `<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>NSMicrophoneUsageDescription</key>
- <string>This app needs microphone access for audio recording.</string>
-</dict>
-</plist>
-`);
-
- // App entry point
- await writeFile(join(srcDir, `${targetName}App.swift`), `import SwiftUI
-
-@main
-struct ${targetName}App: App {
- var body: some Scene {
- WindowGroup {
- ContentView()
- }
- }
-}
-`);
-
- // ContentView
- await writeFile(join(srcDir, 'ContentView.swift'), `import SwiftUI
-
-struct ContentView: View {
- var body: some View {
- NavigationStack {
- VStack(spacing: 20) {
- Image(systemName: "app.fill")
- .font(.system(size: 60))
- .foregroundStyle(.blue)
-
- Text("${name}")
- .font(.largeTitle)
- .fontWeight(.bold)
-
- Text("Built with PortOS")
- .font(.subheadline)
- .foregroundStyle(.secondary)
- }
- .navigationTitle("${name}")
- }
- }
-}
-`);
-
- // Assets.xcassets
- await ensureDir(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset'));
- await writeFile(join(srcDir, 'Assets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
- await writeFile(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), `{
- "images": [{"idiom": "universal", "platform": "ios", "size": "1024x1024"}],
- "info": {"version": 1, "author": "xcode"}
-}`);
-
- // Preview Assets
- await ensureDir(join(previewDir, 'PreviewAssets.xcassets'));
- await writeFile(join(previewDir, 'PreviewAssets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
-
- // Unit test
- await writeFile(join(testsDir, `${targetName}Tests.swift`), `import XCTest
-@testable import ${targetName}
-
-final class ${targetName}Tests: XCTestCase {
- func testAppLaunches() {
- XCTAssertTrue(true, "App scaffold is functional")
- }
-}
-`);
-
- // Shared Xcode deployment assets
- await writeFile(join(repoPath, '.env.example'), XCODE_ENV_EXAMPLE);
- const deployPath = join(repoPath, 'deploy.sh');
- await writeFile(deployPath, generateDeployScript(targetName, bundleId));
- if (process.platform !== 'win32') await chmod(deployPath, 0o755);
-
- // AGENTS.md (+ the Claude Code bridge)
- await writeAgentInstructions(repoPath, `# ${name}
-
-iOS native app built with SwiftUI and XcodeGen.
-
-## Tech Stack
-
-- **SwiftUI** + **SwiftData** (iOS 17.0+)
-- **XcodeGen** for project generation (\`project.yml\` is the source of truth, not the \`.xcodeproj\`)
-- Bundle ID: \`${bundleId}\`, Team: \`${teamId}\`
-
-## Build Commands
-
-\`\`\`bash
-# Generate Xcode project (required after changing project.yml)
-xcodegen generate
-
-# Build
-xcodebuild build -project ${targetName}.xcodeproj -scheme ${targetName} \\
- -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
-
-# Run tests
-xcodebuild test -project ${targetName}.xcodeproj -scheme ${targetName} \\
- -only-testing:${targetName}Tests \\
- -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
-\`\`\`
-
-## TestFlight Deployment
-
-Local deploy via \`./deploy.sh\`:
-
-\`\`\`bash
-./deploy.sh # full: tests + archive + upload
-./deploy.sh --skip-tests # skip tests for faster iteration
-\`\`\`
-
-Requires \`.env\` file with App Store Connect API credentials (see \`.env.example\`).
-`);
-
- addStep('Create iOS project', 'done');
-
- // Run xcodegen if available
- const { stderr: xgenErr } = await execAsync('xcodegen generate', { cwd: repoPath })
- .catch(err => ({ stderr: err.message }));
-
- if (xgenErr && !xgenErr.includes('Created project')) {
- addStep('Generate Xcode project', 'error', xgenErr);
- } else {
- addStep('Generate Xcode project', 'done');
- }
-}
diff --git a/server/services/xcodeScaffold.js b/server/services/xcodeScaffold.js
index 7a1fa53692..5981f38d9e 100644
--- a/server/services/xcodeScaffold.js
+++ b/server/services/xcodeScaffold.js
@@ -12,37 +12,40 @@ import {
const execAsync = promisify(exec);
-/**
- * Scaffold a multi-platform Xcode project (iOS + macOS + watchOS)
- * with XcodeGen, deploy script, and screenshot automation.
- */
-export async function scaffoldXcode(repoPath, name, dirName, addStep) {
- const bundleId = toBundleId(name);
- const teamId = XCODE_TEAM_ID;
- const targetName = toTargetName(name);
- const watchTarget = `${targetName}_Watch`;
+/** Every platform this scaffolder knows how to emit, in `project.yml` order. */
+const XCODE_PLATFORMS = ['ios', 'macos', 'watchos'];
+
+/** `options.deploymentTarget` line per platform. */
+const DEPLOYMENT_TARGET_LINES = {
+ ios: ' iOS: "17.0"',
+ macos: ' macOS: "14.0"',
+ watchos: ' watchOS: "10.0"',
+};
+
+const appIconContents = platform => `{
+ "images": [{"idiom": "universal", "platform": "${platform}", "size": "1024x1024"}],
+ "info": {"version": 1, "author": "xcode"}
+}`;
- // project.yml — XcodeGen source of truth with iOS, macOS, and watchOS targets
- await writeFile(join(repoPath, 'project.yml'), `name: ${targetName}
-options:
- bundleIdPrefix: ${XCODE_BUNDLE_PREFIX}
- deploymentTarget:
- iOS: "17.0"
- macOS: "14.0"
- watchOS: "10.0"
- xcodeVersion: "16.0"
- generateEmptyDirectories: true
+const EMPTY_ASSET_CATALOG = '{"info":{"version":1,"author":"xcode"}}';
-settings:
- base:
- DEVELOPMENT_TEAM: ${teamId}
- MARKETING_VERSION: "1.0.0"
- CURRENT_PROJECT_VERSION: 1
- SWIFT_VERSION: "5.9"
-
-targets:
- # --- iOS Target ---
- ${targetName}:
+/**
+ * Build `project.yml` from a shared preamble plus one target block per platform.
+ * Target blocks only carry `# --- ... ---` headers in a multi-target project —
+ * a single-platform project has nothing to disambiguate.
+ */
+function buildProjectYml({ targetName, watchTarget, bundleId, teamId, platforms, multi }) {
+ const deploymentTargets = XCODE_PLATFORMS
+ .filter(p => platforms.includes(p))
+ .map(p => DEPLOYMENT_TARGET_LINES[p])
+ .join('\n');
+ const sharedSource = multi ? '\n - path: Shared' : '';
+ const uiTestScheme = multi ? `\n - ${targetName}UITests` : '';
+
+ const blocks = [];
+ const addBlock = (label, body) => blocks.push(multi ? ` # --- ${label} ---\n${body}` : body);
+
+ addBlock('iOS Target', ` ${targetName}:
type: application
platform: iOS
sources:
@@ -50,8 +53,7 @@ targets:
excludes:
- Preview Content/PreviewAssets.xcassets
- path: ${targetName}/Preview Content/PreviewAssets.xcassets
- buildPhase: none
- - path: Shared
+ buildPhase: none${sharedSource}
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}
@@ -65,11 +67,10 @@ targets:
GENERATE_INFOPLIST_FILE: true
scheme:
testTargets:
- - ${targetName}Tests
- - ${targetName}UITests
+ - ${targetName}Tests${uiTestScheme}`);
- # --- macOS Target ---
- ${targetName} macOS:
+ if (platforms.includes('macos')) {
+ addBlock('macOS Target', ` ${targetName} macOS:
type: application
platform: macOS
sources:
@@ -86,10 +87,11 @@ targets:
PRODUCT_NAME: ${targetName}
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO
- GENERATE_INFOPLIST_FILE: true
+ GENERATE_INFOPLIST_FILE: true`);
+ }
- # --- watchOS Target ---
- ${watchTarget}:
+ if (platforms.includes('watchos')) {
+ addBlock('watchOS Target', ` ${watchTarget}:
type: application
platform: watchOS
sources:
@@ -103,10 +105,10 @@ targets:
GENERATE_INFOPLIST_FILE: true
dependencies:
- target: ${targetName}
- embed: false
+ embed: false`);
+ }
- # --- Unit Tests ---
- ${targetName}Tests:
+ addBlock('Unit Tests', ` ${targetName}Tests:
type: bundle.unit-test
platform: iOS
sources:
@@ -118,10 +120,10 @@ targets:
PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}Tests
GENERATE_INFOPLIST_FILE: true
TEST_HOST: "$(BUILT_PRODUCTS_DIR)/${targetName}.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/${targetName}"
- BUNDLE_LOADER: "$(TEST_HOST)"
+ BUNDLE_LOADER: "$(TEST_HOST)"`);
- # --- UI Tests (screenshot automation) ---
- ${targetName}UITests:
+ if (multi) {
+ addBlock('UI Tests (screenshot automation)', ` ${targetName}UITests:
type: bundle.ui-testing
platform: iOS
sources:
@@ -132,10 +134,200 @@ targets:
base:
PRODUCT_BUNDLE_IDENTIFIER: ${bundleId}UITests
GENERATE_INFOPLIST_FILE: true
- TEST_TARGET_NAME: ${targetName}
+ TEST_TARGET_NAME: ${targetName}`);
+ }
+
+ return `name: ${targetName}
+options:
+ bundleIdPrefix: ${XCODE_BUNDLE_PREFIX}
+ deploymentTarget:
+${deploymentTargets}
+ xcodeVersion: "16.0"
+ generateEmptyDirectories: true
+
+settings:
+ base:
+ DEVELOPMENT_TEAM: ${teamId}
+ MARKETING_VERSION: "1.0.0"
+ CURRENT_PROJECT_VERSION: 1
+ SWIFT_VERSION: "5.9"
+
+targets:
+${blocks.join('\n\n')}
+`;
+}
+
+/**
+ * `ContentView.swift` — the multi-platform variant renders through the `Shared`
+ * module's `AppConstants`, so it is only valid when `Shared` is emitted.
+ */
+const buildContentView = ({ name, multi }) => (multi ? `import SwiftUI
+
+struct ContentView: View {
+ var body: some View {
+ #if os(macOS)
+ NavigationSplitView {
+ List {
+ NavigationLink("Home", destination: HomeView())
+ }
+ .navigationSplitViewColumnWidth(min: 180, ideal: 200)
+ } detail: {
+ HomeView()
+ }
+ #else
+ NavigationStack {
+ HomeView()
+ }
+ #endif
+ }
+}
+
+struct HomeView: View {
+ var body: some View {
+ VStack(spacing: 20) {
+ Image(systemName: "app.fill")
+ .font(.system(size: 60))
+ .foregroundStyle(.blue)
+
+ Text(AppConstants.appName)
+ .font(.largeTitle)
+ .fontWeight(.bold)
+
+ Text("Built with PortOS")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+ .navigationTitle(AppConstants.appName)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+}
+` : `import SwiftUI
+
+struct ContentView: View {
+ var body: some View {
+ NavigationStack {
+ VStack(spacing: 20) {
+ Image(systemName: "app.fill")
+ .font(.system(size: 60))
+ .foregroundStyle(.blue)
+
+ Text("${name}")
+ .font(.largeTitle)
+ .fontWeight(.bold)
+
+ Text("Built with PortOS")
+ .font(.subheadline)
+ .foregroundStyle(.secondary)
+ }
+ .navigationTitle("${name}")
+ }
+ }
+}
`);
- // Create source directories
+function buildAgentInstructions({ name, bundleId, teamId, targetName, platforms, multi }) {
+ const platformVersions = [
+ platforms.includes('ios') && 'iOS 17.0+',
+ platforms.includes('macos') && 'macOS 14.0+',
+ platforms.includes('watchos') && 'watchOS 10.0+',
+ ].filter(Boolean).join(', ');
+
+ const summary = multi
+ ? `Multi-platform native app built with SwiftUI (${platforms.map(p => ({ ios: 'iOS', macos: 'macOS', watchos: 'watchOS' })[p]).join(' + ')}) and XcodeGen.`
+ : 'iOS native app built with SwiftUI and XcodeGen.';
+
+ const macBuild = platforms.includes('macos') ? `
+
+# Build macOS
+xcodebuild build -project ${targetName}.xcodeproj -scheme "${targetName} macOS" \\
+ CODE_SIGNING_ALLOWED=NO` : '';
+
+ const deployFlags = multi
+ ? `./deploy.sh # every platform the project has a scheme for (default)
+./deploy.sh --ios # iOS only
+./deploy.sh --macos # macOS only
+./deploy.sh --watch # watchOS only (standalone watch apps)
+./deploy.sh --all # explicit "all available" (same as default)
+./deploy.sh --skip-tests # skip tests for faster iteration`
+ : `./deploy.sh # full: tests + archive + upload
+./deploy.sh --skip-tests # skip tests for faster iteration`;
+
+ const screenshots = multi ? `
+
+## Screenshot Automation
+
+\`\`\`bash
+./take_screenshots.sh # iOS/iPad, all languages
+./take_screenshots.sh en # single language
+./take_screenshots.sh --iphone-only${platforms.includes('macos') ? `
+./take_screenshots_macos.sh # macOS screenshots` : ''}
+\`\`\`
+
+Screenshots are saved to \`screenshots/{locale}/{device}/\` for upload to App Store Connect.` : '';
+
+ return `# ${name}
+
+${summary}
+
+## Tech Stack
+
+- **SwiftUI** + **SwiftData** (${platformVersions})
+- **XcodeGen** for project generation (\`project.yml\` is the source of truth, not the \`.xcodeproj\`)
+- Bundle ID: \`${bundleId}\`, Team: \`${teamId}\`
+
+## Build Commands
+
+\`\`\`bash
+# Generate Xcode project (required after changing project.yml)
+xcodegen generate
+
+# Build${multi ? ' iOS' : ''}
+xcodebuild build -project ${targetName}.xcodeproj -scheme ${targetName} \\
+ -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO${macBuild}
+
+# Run tests
+xcodebuild test -project ${targetName}.xcodeproj -scheme ${targetName} \\
+ -only-testing:${targetName}Tests \\
+ -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
+\`\`\`
+
+## TestFlight Deployment
+
+Local deploy via \`./deploy.sh\`:
+
+\`\`\`bash
+${deployFlags}
+\`\`\`
+
+Requires \`.env\` file with App Store Connect API credentials (see \`.env.example\`).${screenshots}
+`;
+}
+
+/**
+ * Scaffold an Xcode project with XcodeGen, a deploy script and (for
+ * multi-platform projects) screenshot automation.
+ *
+ * `platforms` selects which targets are emitted — `['ios']` reproduces the
+ * `ios-native` template, the default reproduces `xcode-multiplatform`. iOS is
+ * always emitted: it hosts the unit-test target every variant ships.
+ */
+export async function scaffoldXcode(repoPath, name, dirName, addStep, { platforms = XCODE_PLATFORMS } = {}) {
+ const bundleId = toBundleId(name);
+ const teamId = XCODE_TEAM_ID;
+ const targetName = toTargetName(name);
+ const watchTarget = `${targetName}_Watch`;
+ const hasMacos = platforms.includes('macos');
+ const hasWatchos = platforms.includes('watchos');
+ // A second platform is what pulls in the `Shared` module, the UI-test target
+ // and the screenshot automation — iOS on its own needs none of them.
+ const multi = hasMacos || hasWatchos;
+
+ await writeFile(
+ join(repoPath, 'project.yml'),
+ buildProjectYml({ targetName, watchTarget, bundleId, teamId, platforms, multi })
+ );
+
+ // Source directories
const srcDir = join(repoPath, targetName);
const sharedDir = join(repoPath, 'Shared');
const watchDir = join(repoPath, watchTarget);
@@ -143,19 +335,30 @@ targets:
const testsDir = join(repoPath, `${targetName}Tests`);
const uiTestsDir = join(repoPath, `${targetName}UITests`);
- await ensureDirs([srcDir, sharedDir, watchDir, previewDir, testsDir, uiTestsDir]);
-
- // Info.plist (iOS)
+ await ensureDirs([
+ srcDir,
+ multi && sharedDir,
+ hasWatchos && watchDir,
+ previewDir,
+ testsDir,
+ multi && uiTestsDir,
+ ].filter(Boolean));
+
+ // Info.plist (iOS). The iOS-only template ships a microphone usage string;
+ // the multi-platform one leaves the dictionary empty.
await writeFile(join(srcDir, 'Info.plist'), `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
-<dict/>
+${multi ? '<dict/>' : `<dict>
+ <key>NSMicrophoneUsageDescription</key>
+ <string>This app needs microphone access for audio recording.</string>
+</dict>`}
</plist>
`);
- // macOS entitlements
- await writeFile(join(repoPath, `${targetName}-macOS.entitlements`), `<?xml version="1.0" encoding="UTF-8"?>
+ if (hasMacos) {
+ await writeFile(join(repoPath, `${targetName}-macOS.entitlements`), `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
@@ -167,17 +370,20 @@ targets:
</dict>
</plist>
`);
+ }
- // Shared module (cross-platform models/logic)
- await writeFile(join(sharedDir, 'AppConstants.swift'), `import Foundation
+ if (multi) {
+ // Shared module (cross-platform models/logic)
+ await writeFile(join(sharedDir, 'AppConstants.swift'), `import Foundation
enum AppConstants {
static let appName = "${targetName}"
static let bundleId = "${bundleId}"
}
`);
+ }
- // iOS/macOS App entry point (multi-platform)
+ // App entry point
await writeFile(join(srcDir, `${targetName}App.swift`), `import SwiftUI
@main
@@ -185,59 +391,18 @@ struct ${targetName}App: App {
var body: some Scene {
WindowGroup {
ContentView()
- }
+ }${hasMacos ? `
#if os(macOS)
.defaultSize(width: 900, height: 600)
- #endif
+ #endif` : ''}
}
}
`);
- // ContentView with platform conditionals
- await writeFile(join(srcDir, 'ContentView.swift'), `import SwiftUI
+ await writeFile(join(srcDir, 'ContentView.swift'), buildContentView({ name, multi }));
-struct ContentView: View {
- var body: some View {
- #if os(macOS)
- NavigationSplitView {
- List {
- NavigationLink("Home", destination: HomeView())
- }
- .navigationSplitViewColumnWidth(min: 180, ideal: 200)
- } detail: {
- HomeView()
- }
- #else
- NavigationStack {
- HomeView()
- }
- #endif
- }
-}
-
-struct HomeView: View {
- var body: some View {
- VStack(spacing: 20) {
- Image(systemName: "app.fill")
- .font(.system(size: 60))
- .foregroundStyle(.blue)
-
- Text(AppConstants.appName)
- .font(.largeTitle)
- .fontWeight(.bold)
-
- Text("Built with PortOS")
- .font(.subheadline)
- .foregroundStyle(.secondary)
- }
- .navigationTitle(AppConstants.appName)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- }
-}
-`);
-
- // watchOS App
- await writeFile(join(watchDir, `${watchTarget}App.swift`), `import SwiftUI
+ if (hasWatchos) {
+ await writeFile(join(watchDir, `${watchTarget}App.swift`), `import SwiftUI
@main
struct ${watchTarget}App: App {
@@ -249,7 +414,7 @@ struct ${watchTarget}App: App {
}
`);
- await writeFile(join(watchDir, 'WatchContentView.swift'), `import SwiftUI
+ await writeFile(join(watchDir, 'WatchContentView.swift'), `import SwiftUI
struct WatchContentView: View {
var body: some View {
@@ -264,24 +429,21 @@ struct WatchContentView: View {
}
}
`);
+ }
// Asset catalogs
await ensureDir(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset'));
- await writeFile(join(srcDir, 'Assets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
- await writeFile(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), `{
- "images": [{"idiom": "universal", "platform": "ios", "size": "1024x1024"}],
- "info": {"version": 1, "author": "xcode"}
-}`);
+ await writeFile(join(srcDir, 'Assets.xcassets', 'Contents.json'), EMPTY_ASSET_CATALOG);
+ await writeFile(join(srcDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), appIconContents('ios'));
- await ensureDir(join(watchDir, 'Assets.xcassets', 'AppIcon.appiconset'));
- await writeFile(join(watchDir, 'Assets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
- await writeFile(join(watchDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), `{
- "images": [{"idiom": "universal", "platform": "watchos", "size": "1024x1024"}],
- "info": {"version": 1, "author": "xcode"}
-}`);
+ if (hasWatchos) {
+ await ensureDir(join(watchDir, 'Assets.xcassets', 'AppIcon.appiconset'));
+ await writeFile(join(watchDir, 'Assets.xcassets', 'Contents.json'), EMPTY_ASSET_CATALOG);
+ await writeFile(join(watchDir, 'Assets.xcassets', 'AppIcon.appiconset', 'Contents.json'), appIconContents('watchos'));
+ }
await ensureDir(join(previewDir, 'PreviewAssets.xcassets'));
- await writeFile(join(previewDir, 'PreviewAssets.xcassets', 'Contents.json'), '{"info":{"version":1,"author":"xcode"}}');
+ await writeFile(join(previewDir, 'PreviewAssets.xcassets', 'Contents.json'), EMPTY_ASSET_CATALOG);
// Unit tests
await writeFile(join(testsDir, `${targetName}Tests.swift`), `import XCTest
@@ -294,8 +456,9 @@ final class ${targetName}Tests: XCTestCase {
}
`);
- // UI Tests with screenshot stubs
- await writeFile(join(uiTestsDir, 'ScreenshotTests.swift'), `import XCTest
+ if (multi) {
+ // UI Tests with screenshot stubs
+ await writeFile(join(uiTestsDir, 'ScreenshotTests.swift'), `import XCTest
final class ScreenshotTests: XCTestCase {
@@ -370,82 +533,32 @@ final class ScreenshotTests: XCTestCase {
}
}
`);
+ }
- // .env.example
+ // Shared Xcode deployment assets
await writeFile(join(repoPath, '.env.example'), XCODE_ENV_EXAMPLE);
// Scripts (from generators in xcodeScripts service)
- await writeFile(join(repoPath, 'deploy.sh'), generateDeployScript(targetName, bundleId));
- await writeFile(join(repoPath, 'take_screenshots.sh'), generateScreenshotScript(targetName, bundleId));
- await writeFile(join(repoPath, 'take_screenshots_macos.sh'), generateMacScreenshotScript(targetName, bundleId));
-
+ const scripts = [
+ ['deploy.sh', generateDeployScript(targetName, bundleId)],
+ multi && ['take_screenshots.sh', generateScreenshotScript(targetName, bundleId)],
+ hasMacos && ['take_screenshots_macos.sh', generateMacScreenshotScript(targetName, bundleId)],
+ ].filter(Boolean);
+
+ for (const [file, contents] of scripts) {
+ await writeFile(join(repoPath, file), contents);
+ }
if (process.platform !== 'win32') {
- await Promise.all([
- chmod(join(repoPath, 'deploy.sh'), 0o755),
- chmod(join(repoPath, 'take_screenshots.sh'), 0o755),
- chmod(join(repoPath, 'take_screenshots_macos.sh'), 0o755),
- ]);
+ await Promise.all(scripts.map(([file]) => chmod(join(repoPath, file), 0o755)));
}
// AGENTS.md (+ the Claude Code bridge)
- await writeAgentInstructions(repoPath, `# ${name}
-
-Multi-platform native app built with SwiftUI (iOS + macOS + watchOS) and XcodeGen.
-
-## Tech Stack
-
-- **SwiftUI** + **SwiftData** (iOS 17.0+, macOS 14.0+, watchOS 10.0+)
-- **XcodeGen** for project generation (\`project.yml\` is the source of truth, not the \`.xcodeproj\`)
-- Bundle ID: \`${bundleId}\`, Team: \`${teamId}\`
-
-## Build Commands
-
-\`\`\`bash
-# Generate Xcode project (required after changing project.yml)
-xcodegen generate
-
-# Build iOS
-xcodebuild build -project ${targetName}.xcodeproj -scheme ${targetName} \\
- -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
-
-# Build macOS
-xcodebuild build -project ${targetName}.xcodeproj -scheme "${targetName} macOS" \\
- CODE_SIGNING_ALLOWED=NO
-
-# Run tests
-xcodebuild test -project ${targetName}.xcodeproj -scheme ${targetName} \\
- -only-testing:${targetName}Tests \\
- -destination 'platform=iOS Simulator,name=iPhone 16' CODE_SIGNING_ALLOWED=NO
-\`\`\`
-
-## TestFlight Deployment
-
-Local deploy via \`./deploy.sh\`:
-
-\`\`\`bash
-./deploy.sh # every platform the project has a scheme for (default)
-./deploy.sh --ios # iOS only
-./deploy.sh --macos # macOS only
-./deploy.sh --watch # watchOS only (standalone watch apps)
-./deploy.sh --all # explicit "all available" (same as default)
-./deploy.sh --skip-tests # skip tests for faster iteration
-\`\`\`
-
-Requires \`.env\` file with App Store Connect API credentials (see \`.env.example\`).
-
-## Screenshot Automation
-
-\`\`\`bash
-./take_screenshots.sh # iOS/iPad, all languages
-./take_screenshots.sh en # single language
-./take_screenshots.sh --iphone-only
-./take_screenshots_macos.sh # macOS screenshots
-\`\`\`
-
-Screenshots are saved to \`screenshots/{locale}/{device}/\` for upload to App Store Connect.
-`);
+ await writeAgentInstructions(
+ repoPath,
+ buildAgentInstructions({ name, bundleId, teamId, targetName, platforms, multi })
+ );
- addStep('Create multi-platform Xcode project', 'done');
+ addStep(multi ? 'Create multi-platform Xcode project' : 'Create iOS project', 'done');
// Run xcodegen if available
const { stderr: xgenErr } = await execAsync('xcodegen generate', { cwd: repoPath })
diff --git a/server/services/xcodeScaffold.test.js b/server/services/xcodeScaffold.test.js
new file mode 100644
index 0000000000..6e4baec28d
--- /dev/null
+++ b/server/services/xcodeScaffold.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtemp, rm, readdir, readFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join, relative, sep } from 'path';
+
+// xcodegen is an external binary that may or may not exist on the machine
+// running the suite — stub the spawn so the scaffolder's file emission is what
+// is under test, not the generator's availability.
+vi.mock('../lib/childProcess.js', async importOriginal => ({
+ ...await importOriginal(),
+ exec: vi.fn((cmd, opts, cb) => cb(null, { stdout: 'Created project', stderr: '' }))
+}));
+
+import { scaffoldXcode } from './xcodeScaffold.js';
+
+/** Every emitted file, repo-relative with POSIX separators, sorted. */
+async function listFiles(root) {
+ const entries = await readdir(root, { recursive: true, withFileTypes: true });
+ return entries
+ .filter(e => e.isFile())
+ .map(e => relative(root, join(e.parentPath ?? e.path, e.name)).split(sep).join('/'))
+ .sort();
+}
+
+describe('scaffoldXcode', () => {
+ let repoPath;
+ const steps = [];
+ const addStep = (name, status) => steps.push([name, status]);
+
+ beforeEach(async () => {
+ steps.length = 0;
+ repoPath = await mkdtemp(join(tmpdir(), 'portos-xcode-scaffold-'));
+ });
+
+ afterEach(async () => {
+ await rm(repoPath, { recursive: true, force: true });
+ });
+
+ it('emits an iOS-only project for platforms: ["ios"]', async () => {
+ await scaffoldXcode(repoPath, 'Sample App', 'sample-app', addStep, { platforms: ['ios'] });
+
+ expect(await listFiles(repoPath)).toEqual([
+ '.env.example',
+ 'AGENTS.md',
+ 'CLAUDE.md',
+ 'Sample_App/Assets.xcassets/AppIcon.appiconset/Contents.json',
+ 'Sample_App/Assets.xcassets/Contents.json',
+ 'Sample_App/ContentView.swift',
+ 'Sample_App/Info.plist',
+ 'Sample_App/Preview Content/PreviewAssets.xcassets/Contents.json',
+ 'Sample_App/Sample_AppApp.swift',
+ 'Sample_AppTests/Sample_AppTests.swift',
+ 'deploy.sh',
+ 'project.yml',
+ ]);
+
+ const projectYml = await readFile(join(repoPath, 'project.yml'), 'utf8');
+ expect(projectYml).toContain(' Sample_App:\n type: application\n platform: iOS');
+ expect(projectYml).toContain(' Sample_AppTests:');
+ expect(projectYml).not.toContain('macOS');
+ expect(projectYml).not.toContain('watchOS');
+ expect(projectYml).not.toContain('UITests');
+ // No Shared module means ContentView must not reference AppConstants.
+ expect(await readFile(join(repoPath, 'Sample_App/ContentView.swift'), 'utf8'))
+ .not.toContain('AppConstants');
+ expect(steps).toContainEqual(['Create iOS project', 'done']);
+ });
+
+ it('emits iOS + macOS + watchOS targets by default', async () => {
+ await scaffoldXcode(repoPath, 'Sample App', 'sample-app', addStep);
+
+ const files = await listFiles(repoPath);
+ expect(files).toContain('Shared/AppConstants.swift');
+ expect(files).toContain('Sample_App_Watch/WatchContentView.swift');
+ expect(files).toContain('Sample_App-macOS.entitlements');
+ expect(files).toContain('Sample_AppUITests/ScreenshotTests.swift');
+ expect(files).toContain('take_screenshots.sh');
+ expect(files).toContain('take_screenshots_macos.sh');
+
+ const projectYml = await readFile(join(repoPath, 'project.yml'), 'utf8');
+ expect(projectYml).toContain(' Sample_App:\n type: application\n platform: iOS');
+ expect(projectYml).toContain(' Sample_App macOS:\n type: application\n platform: macOS');
+ expect(projectYml).toContain(' Sample_App_Watch:\n type: application\n platform: watchOS');
+ expect(projectYml).toContain(' Sample_AppTests:');
+ expect(projectYml).toContain(' Sample_AppUITests:');
+ expect(steps).toContainEqual(['Create multi-platform Xcode project', 'done']);
+ });
+});