Run a virtual iPhone on an Apple Silicon Mac.
Swift
Show Launchpad consoles and logs in a Ghostty terminal
Lakr233dd37c7b3aaa2
diff --git a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex b02a19a7..403549ec 100644--- a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "01b56dbe07461c056f9f787f47fe980bea82d0877db7a293439df58ce597d835",+ "originHash" : "a6866c860e660ef27df596c0ba8795342d386b1b265f3a7cc212d640cd67c649","pins" : [{"identity" : "applemobiledevicelibrary",@@ -46,6 +46,15 @@"version" : "0.1.3"}},+ {+ "identity" : "libghostty-spm",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/libghostty-spm.git",+ "state" : {+ "revision" : "b7f888e3baf8585ea9d590ab1a45b49475e00d1c",+ "version" : "1.6.20260922"+ }+ },{"identity" : "libimg4-spm","kind" : "remoteSourceControl",@@ -64,6 +73,15 @@"version" : "0.52.2"}},+ {+ "identity" : "msdisplaylink",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/MSDisplayLink.git",+ "state" : {+ "revision" : "87eb0af130744c8cbe2e31b6e1a5bcd659f1c220",+ "version" : "2.2.0"+ }+ },{"identity" : "objectarchivekit","kind" : "remoteSourceControl",diff --git a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxprojindex 72d367b3..026bba60 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj+++ b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj@@ -6,6 +6,7 @@objects = {/* Begin PBXBuildFile section */5A1000000000000000000061 /* com.vphone.launchpad.helper in Embed Privileged Helper */ = {isa = PBXBuildFile; fileRef = 5A1000000000000000000032 /* com.vphone.launchpad.helper */; };+ 5A1000000000000000000062 /* GhosttyTerminal in Frameworks */ = {isa = PBXBuildFile; productRef = 5A10000000000000000000B1 /* GhosttyTerminal */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */5A1000000000000000000071 /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A1000000000000000000012; remoteInfo = VPhoneLaunchpadHelper; };@@ -32,7 +33,7 @@5A1000000000000000000023 /* VPhoneLaunchpadShared */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadShared; sourceTree = "<group>"; };/* End PBXFileSystemSynchronizedRootGroup section *//* Begin PBXFrameworksBuildPhase section */- 5A1000000000000000000041 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };+ 5A1000000000000000000041 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (5A1000000000000000000062 /* GhosttyTerminal in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; };5A1000000000000000000042 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };/* End PBXFrameworksBuildPhase section *//* Begin PBXGroup section */@@ -50,6 +51,7 @@dependencies = (5A1000000000000000000072 /* PBXTargetDependency */, );fileSystemSynchronizedGroups = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );name = VPhoneLaunchpad;+ packageProductDependencies = (5A10000000000000000000B1 /* GhosttyTerminal */, );productName = VPhoneLaunchpad;productReference = 5A1000000000000000000031 /* vphone-launchpad.app */;productType = "com.apple.product-type.application";@@ -76,6 +78,7 @@developmentRegion = en;knownRegions = (en, Base, );mainGroup = 5A1000000000000000000002;+ packageReferences = (5A10000000000000000000A1 /* XCRemoteSwiftPackageReference "libghostty-spm" */, );productRefGroup = 5A1000000000000000000003 /* Products */;projectDirPath = "";projectRoot = "";@@ -105,6 +108,12 @@5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000083 /* Debug */, 5A1000000000000000000084 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };5A1000000000000000000093 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadHelper" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000085 /* Debug */, 5A1000000000000000000086 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };/* End XCConfigurationList section */+/* Begin XCRemoteSwiftPackageReference section */+ 5A10000000000000000000A1 /* XCRemoteSwiftPackageReference "libghostty-spm" */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/Lakr233/libghostty-spm.git"; requirement = {kind = upToNextMajorVersion; minimumVersion = 1.6.20260922; }; };+/* End XCRemoteSwiftPackageReference section */+/* Begin XCSwiftPackageProductDependency section */+ 5A10000000000000000000B1 /* GhosttyTerminal */ = {isa = XCSwiftPackageProductDependency; package = 5A10000000000000000000A1 /* XCRemoteSwiftPackageReference "libghostty-spm" */; productName = GhosttyTerminal; };+/* End XCSwiftPackageProductDependency section */};rootObject = 5A1000000000000000000001 /* Project object */;}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvednew file mode 100644index 00000000..34075008--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -0,0 +1,24 @@+{+ "originHash" : "56a89e8cf2be81f633e09acd014341691afac471fbe6fdc029e3c5f89d66ddd8",+ "pins" : [+ {+ "identity" : "libghostty-spm",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/libghostty-spm.git",+ "state" : {+ "revision" : "b7f888e3baf8585ea9d590ab1a45b49475e00d1c",+ "version" : "1.6.20260922"+ }+ },+ {+ "identity" : "msdisplaylink",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/MSDisplayLink.git",+ "state" : {+ "revision" : "87eb0af130744c8cbe2e31b6e1a5bcd659f1c220",+ "version" : "2.2.0"+ }+ }+ ],+ "version" : 3+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swiftindex 5d42829b..ecbe3ee2 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift@@ -73,7 +73,7 @@await shot("05-machines", suffix)if let machine = model.machines.selected {await standalone("05b-machine-inspector", suffix, size: NSSize(width: 380, height: 980)) {- VPhoneLaunchpadMachineInspector(machine: machine) { _ in }+ VPhoneLaunchpadMachineInspector(machine: machine, onShowProgress: { _ in }, onOpenConsole: { _ in }).environment(model)}}@@ -89,6 +89,7 @@}await sheet(.clone("frida-lab"), "10-clone", suffix)await sheet(.export("frida-lab"), "11-export", suffix)+ await sheet(.console("research-01"), "12-console", suffix)}NSApp.terminate(nil)}@@ -213,6 +214,11 @@keepArtifacts: false,)+ /// What a log terminal shows in snapshot mode instead of the file.+ static func log(for url: URL) -> [String] {+ url.lastPathComponent.hasSuffix("-create.log") ? creationLog : console+ }+static let console = ["[vphone] Loaded VM manifest from ~/.vphone/machines/research-01/config.plist","[vphone] Starting guest (PV=3, 8 CPU, 8192 MB)",diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swiftindex 7f1d1195..d7f441df 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift@@ -40,30 +40,3 @@ struct VPhoneLaunchpadStatusIcon: View {}}-// MARK: - Log--/// Command output. The one place the app uses a monospaced face. It sits-/// directly in its form row: no inset, background or border of its own.-struct VPhoneLaunchpadLogView: View {- let lines: [String]-- var body: some View {- ScrollViewReader { proxy in- ScrollView([.vertical, .horizontal]) {- LazyVStack(alignment: .leading, spacing: 1) {- ForEach(Array(lines.enumerated()), id: \.offset) { index, line in- Text(line)- .id(index)- }- }- .font(.system(.caption, design: .monospaced))- .textSelection(.enabled)- .frame(maxWidth: .infinity, alignment: .leading)- }- .scrollContentBackground(.hidden)- .onChange(of: lines.count) { _, count in- proxy.scrollTo(count - 1, anchor: .bottom)- }- }- }-}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swiftnew file mode 100644index 00000000..6987308b--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift@@ -0,0 +1,199 @@+import Foundation+import GhosttyTerminal+import SwiftUI++// MARK: - Theme++/// The one terminal look for every console and log. The light palette is the+/// project's; the dark side keeps the same ANSI colours on a dark ground.+/// `TerminalSurfaceView` picks the side from the SwiftUI colour scheme.+enum VPhoneLaunchpadTerminalTheme {+ static let configuration = TerminalConfiguration {+ $0.withCursorStyle(.block)+ $0.withCursorStyleBlink(true)+ $0.withFontSize(10)+ $0.withFontThicken(true)+ $0.withCustom("window-padding-color", "extend")+ }++ static let theme = TerminalTheme(+ light: TerminalConfiguration {+ $0.withBackground("feffff")+ $0.withForeground("000000")+ $0.withCursorColor("98989d")+ $0.withCursorText("ffffff")+ $0.withSelectionBackground("abd8ff")+ $0.withSelectionForeground("000000")+ palette(&$0)+ },+ dark: TerminalConfiguration {+ $0.withBackground("1e1e1e")+ $0.withForeground("ffffff")+ $0.withCursorColor("98989d")+ $0.withCursorText("000000")+ $0.withSelectionBackground("3f638b")+ $0.withSelectionForeground("ffffff")+ palette(&$0)+ },+ )++ private static func palette(_ builder: inout TerminalConfiguration.Builder) {+ let colors = [+ "#1a1a1a", "#cc372e", "#26a439", "#cdac08", "#0869cb", "#9647bf", "#479ec2", "#98989d",+ "#464646", "#ff453a", "#32d74b", "#e5bc00", "#0a84ff", "#bf5af2", "#69c9f2", "#ffffff",+ ]+ for (index, color) in colors.enumerated() {+ builder.withPalette(index, color: color)+ }+ }+}++// MARK: - Log terminal++/// A log file shown in a Ghostty terminal.+///+/// The file is the only source. The view replays its tail when it appears+/// and follows it off the main actor while it stays on screen; Ghostty+/// parses on its own queue. No output passes through the app model, so a+/// chatty guest or restore never invalidates a SwiftUI view. Keystrokes go+/// nowhere: the terminal is read only.+struct VPhoneLaunchpadLogTerminal: View {+ let url: URL+ @StateObject private var terminal = TerminalViewState(+ theme: VPhoneLaunchpadTerminalTheme.theme,+ terminalConfiguration: VPhoneLaunchpadTerminalTheme.configuration,+ )+ @State private var session = InMemoryTerminalSession(write: { _ in }, resize: { _ in })++ var body: some View {+ TerminalSurfaceView(context: terminal)+ .task(id: url) {+ terminal.configuration = TerminalSurfaceOptions(backend: .inMemory(session))+ #if DEBUG+ if VPhoneLaunchpadPreview.isActive {+ session.receive(VPhoneLaunchpadPreview.log(for: url).joined(separator: "\r\n"))+ return+ }+ #endif+ await VPhoneLaunchpadLogTail.follow(url, into: session)+ }+ }+}++// MARK: - Tail++/// Follows a log file into a terminal session until the task is cancelled.+/// Polls, like the child process's own tail: the writer may be a process an+/// earlier Launchpad session started.+nonisolated enum VPhoneLaunchpadLogTail {+ /// How much of an existing log the terminal replays when it opens.+ static let replayBytes: UInt64 = 4 << 20+ static let chunkBytes = 1 << 20++ @concurrent+ static func follow(_ url: URL, into session: InMemoryTerminalSession) async {+ var file: UInt64?+ var offset: UInt64 = 0+ var newline = VPhoneLaunchpadNewlineTranslator()+ var reportedMissing = false++ while !Task.isCancelled {+ if let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),+ let number = (attributes[.systemFileNumber] as? NSNumber)?.uint64Value,+ let size = (attributes[.size] as? NSNumber)?.uint64Value,+ let handle = try? FileHandle(forReadingFrom: url)+ {+ // A new run replaces the file. Start the terminal over.+ var skipsPartialLine = false+ if file != number || size < offset {+ if file != nil || reportedMissing {+ session.receive("\u{1B}c")+ }+ file = number+ offset = size > replayBytes ? size - replayBytes : 0+ skipsPartialLine = offset > 0+ newline = VPhoneLaunchpadNewlineTranslator()+ }+ try? handle.seek(toOffset: offset)+ while !Task.isCancelled, var chunk = try? handle.read(upToCount: chunkBytes), !chunk.isEmpty {+ offset += UInt64(chunk.count)+ if skipsPartialLine {+ guard let end = chunk.firstIndex(of: 0x0A) else {+ continue+ }+ chunk = chunk[chunk.index(after: end)...]+ skipsPartialLine = false+ }+ session.receive(newline.translate(chunk))+ }+ try? handle.close()+ } else if file == nil, !reportedMissing {+ reportedMissing = true+ session.receive("\u{1B}[2m\(String(localized: "No output yet."))\u{1B}[0m\r\n")+ }+ try? await Task.sleep(for: .milliseconds(250))+ }+ }+}++/// Log files end lines with a bare line feed, which a terminal treats as+/// "down one row" without returning to the first column.+nonisolated struct VPhoneLaunchpadNewlineTranslator {+ private var previous: UInt8 = 0++ mutating func translate(_ data: Data) -> Data {+ var output = Data(capacity: data.count + data.count / 32)+ for byte in data {+ if byte == 0x0A, previous != 0x0D {+ output.append(0x0D)+ }+ output.append(byte)+ previous = byte+ }+ return output+ }+}++// MARK: - Writer++/// Appends lines to a log file on a serial queue, so command output is+/// written from the thread that read it and never waits on the main actor.+/// Keeps the last few lines for error details.+nonisolated final class VPhoneLaunchpadLogWriter: @unchecked Sendable {+ let url: URL+ private let queue = DispatchQueue(label: "com.vphone.launchpad.log")+ private let lock = NSLock()+ private var handle: FileHandle?+ private var recent: [String] = []++ /// Starts an empty log at `url`, replacing any earlier one.+ init(url: URL) {+ self.url = url+ queue.async { [self] in+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ FileManager.default.createFile(atPath: url.path, contents: nil)+ handle = try? FileHandle(forWritingTo: url)+ }+ }++ deinit {+ try? handle?.close()+ }++ func write(_ line: String) {+ lock.withLock {+ recent.append(line)+ if recent.count > 12 {+ recent.removeFirst(recent.count - 12)+ }+ }+ queue.async { [self] in+ try? handle?.write(contentsOf: Data("\(line)\n".utf8))+ }+ }++ /// The last lines written, for an error's detail text.+ var tail: String {+ lock.withLock { recent.joined(separator: "\n") }+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swiftindex 686c020e..b08d217d 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift@@ -93,18 +93,17 @@ struct VPhoneLaunchpadCommandLine {}/// Runs to completion. Cancelling the calling task sends SIGINT.+ /// `onLine` runs on the reader thread, never on the main actor.func run(_ arguments: [String],recordInHistory: Bool = true,- onLine: (@MainActor @Sendable (String) -> Void)? = nil,+ onLine: (@Sendable (String) -> Void)? = nil,) async throws -> VPhoneLaunchpadCommandResult {let entry = recordInHistory ? history.record(Self.display(arguments)) : nillet collector = VPhoneLaunchpadLineCollector()let child = try VPhoneLaunchpadChildProcess(executable: executable, arguments: arguments) { line incollector.append(line)- if let onLine {- DispatchQueue.main.async { MainActor.assumeIsolated { onLine(line) } }- }+ onLine?(line)}let status = await withTaskCancellationHandler {await child.wait()@@ -121,7 +120,7 @@ struct VPhoneLaunchpadCommandLine {@discardableResultfunc runChecked(_ arguments: [String],- onLine: (@MainActor @Sendable (String) -> Void)? = nil,+ onLine: (@Sendable (String) -> Void)? = nil,) async throws -> VPhoneLaunchpadCommandResult {let result = try await run(arguments, onLine: onLine)try Task.checkCancellation()@@ -135,20 +134,21 @@ struct VPhoneLaunchpadCommandLine {}/// Starts a long-running command such as `vm launch` and returns at once.- /// Its output goes to `logFile`, so it outlives Launchpad.+ /// Its output goes to `logFile`, so it outlives Launchpad. `onLine` runs on+ /// the reader thread: a guest console can print faster than the main+ /// thread should wake for.func start(_ arguments: [String],logFile: URL,- onLine: @escaping @MainActor @Sendable (String) -> Void,+ onLine: @escaping @Sendable (String) -> Void,) throws -> VPhoneLaunchpadChildProcess {let entry = history.record(Self.display(arguments))let child = try VPhoneLaunchpadChildProcess(executable: executable,arguments: arguments,logFile: logFile,- ) { line in- DispatchQueue.main.async { MainActor.assumeIsolated { onLine(line) } }- }+ onLine: onLine,+ )let history = historyTask {let status = await child.wait()diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swiftindex ed17c025..5a73d748 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift@@ -191,18 +191,17 @@ final class VPhoneLaunchpadHelperClient {}}- /// Runs `cfw install` as root. Output lines go to `onLine`.+ /// Runs `cfw install` as root. Output lines go to `onLine`, on the XPC+ /// connection's queue.func installCustomFirmware(bundleVersion: String,machineName: String,libraryRoot: String,forceDyldSharedCacheMaxSlide: Bool,keepArtifacts: Bool,- onLine: @escaping @MainActor @Sendable (String) -> Void,+ onLine: @escaping @Sendable (String) -> Void,) async throws -> Int32 {- receiver.setHandler { line in- DispatchQueue.main.async { MainActor.assumeIsolated { onLine(line) } }- }+ receiver.setHandler(onLine)defer { receiver.setHandler(nil) }return try await withTaskCancellationHandler {try await request { proxy, done indiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex 52709cdc..c09c425c 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -1,6 +1,40 @@{"sourceLanguage" : "en","strings" : {+ "%@ Console" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ Console"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ のコンソール"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 콘솔"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Bảng điều khiển %@"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ 控制台"+ }+ }+ }+ },"%@ could not be started." : {"localizations" : {"en" : {@@ -5295,6 +5329,40 @@}}},+ "No output yet." : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "No output yet."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "まだ出力はありません。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "아직 출력이 없습니다."+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Chưa có đầu ra."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "暂无输出。"+ }+ }+ }+ },"No policy exception" : {"localizations" : {"en" : {@@ -5635,6 +5703,40 @@}}},+ "Open Console" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Open Console"+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "コンソールを開く"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "콘솔 열기"+ }+ },+ "vi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mở bảng điều khiển"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开控制台"+ }+ }+ }+ },"Open Settings" : {"localizations" : {"en" : {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadConsoleView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadConsoleView.swiftnew file mode 100644index 00000000..ec11c00b--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadConsoleView.swift@@ -0,0 +1,19 @@+import SwiftUI++/// A machine's console: the log `vm launch` writes, in a terminal that fills+/// the sheet.+struct VPhoneLaunchpadConsoleView: View {+ let name: String+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ VPhoneLaunchpadLogTerminal(url: VPhoneLaunchpadMachineLibrary.consoleLog(name))+ .frame(minWidth: 900, maxWidth: .infinity, minHeight: 560, maxHeight: .infinity)+ .navigationTitle("\(name) Console")+ .toolbar {+ ToolbarItem(placement: .confirmationAction) {+ Button("Close") { dismiss() }+ }+ }+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swiftindex bd204081..fee3f291 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadCreationPipeline.swift@@ -69,7 +69,9 @@ final class VPhoneLaunchpadCreationPipeline {private(set) var statuses: [Step: VPhoneLaunchpadStatus] = [:]private(set) var durations: [Step: TimeInterval] = [:]private(set) var current: Step?- private(set) var log: [String] = []+ /// The creation log. The sheet shows it in a terminal; the model keeps+ /// only the last few lines, for error details.+ private let log: VPhoneLaunchpadLogWriterprivate(set) var failure: VPhoneLaunchpadError?private(set) var isRunning = false@@ -79,7 +81,7 @@ final class VPhoneLaunchpadCreationPipeline {private weak var library: VPhoneLaunchpadMachineLibrary?private var task: Task<Void, Never>?private var dfu: VPhoneLaunchpadChildProcess?- private var dfuLines: [String] = []+ private var dfuPanicked = falsenonisolated static let panicPattern = #"(^|[^p])(panic|kernel panic|panic\.apple\.com|stackshot succeeded)"#@@ -95,6 +97,11 @@ final class VPhoneLaunchpadCreationPipeline {self.bundles = bundlesself.helper = helperself.library = library+ log = VPhoneLaunchpadLogWriter(url: VPhoneLaunchpadMachineLibrary.consoleLog(options.name, suffix: "-create"))+ }++ var logFile: URL {+ log.url}var isFinished: Bool {@@ -178,10 +185,7 @@ final class VPhoneLaunchpadCreationPipeline {}private func append(_ line: String) {- log.append(line)- if log.count > 3000 {- log.removeFirst(log.count - 3000)- }+ log.write(line)}// MARK: - Steps@@ -193,7 +197,8 @@ final class VPhoneLaunchpadCreationPipeline {let name = options.namelet library = ["--library-root", libraryRoot.path]let machine = libraryRoot.appendingPathComponent(name, isDirectory: true)- let output: @MainActor @Sendable (String) -> Void = { [weak self] line in self?.append(line) }+ let log = log+ let output: @Sendable (String) -> Void = { line in log.write(line) }func run(_ arguments: [String]) async throws {append("$ \(VPhoneLaunchpadCommandLine.display(arguments))")@@ -219,13 +224,15 @@ final class VPhoneLaunchpadCreationPipeline {case .bootDFU:let arguments = ["vm", "launch", name, "--dfu"] + libraryappend("$ \(VPhoneLaunchpadCommandLine.display(arguments))")- dfuLines = []+ dfuPanicked = falsedfu = try commandLine.start(arguments,logFile: VPhoneLaunchpadMachineLibrary.consoleLog(name, suffix: "-dfu"),) { [weak self] line in- self?.dfuLines.append(line)- self?.append("dfu \(line)")+ log.write("dfu \(line)")+ if Self.isPanic(line) {+ Task { @MainActor in self?.dfuPanicked = true }+ }}let identity = machine.appendingPathComponent("udid-prediction.txt")for _ in 0 ..< 30 {@@ -262,7 +269,7 @@ final class VPhoneLaunchpadCreationPipeline {case .stopDFU:append("waiting up to 30s for the post-restore reboot")for _ in 0 ..< 30 {- if dfu?.isRunning != true || dfuLines.contains(where: Self.isPanic) {+ if dfu?.isRunning != true || dfuPanicked {break}try await Task.sleep(for: .seconds(1))@@ -286,7 +293,7 @@ final class VPhoneLaunchpadCreationPipeline {onLine: output,)guard status == 0 else {- throw VPhoneLaunchpadError(String(localized: "Unable to install CFW. Check the log for details."), detail: log.suffix(12).joined(separator: "\n"))+ throw VPhoneLaunchpadError(String(localized: "Unable to install CFW. Check the log for details."), detail: log.tail)}case .firstBoot:@@ -309,7 +316,7 @@ final class VPhoneLaunchpadCreationPipeline {append("waiting up to 300s for vphoned")for _ in 0 ..< 300 {try Task.checkCancellation()- if (library.consoles[name] ?? []).contains(where: Self.isPanic) {+ if library.panicked.contains(name) {throw VPhoneLaunchpadError(String(localized: "The machine had a kernel panic during first boot."), detail: String(localized: "See the machine's console."))}guard child.isRunning else {@@ -326,7 +333,7 @@ final class VPhoneLaunchpadCreationPipeline {private func requireDFURunning() throws {guard dfu?.isRunning == true else {- throw VPhoneLaunchpadError(String(localized: "The machine stopped while in DFU mode."), detail: dfuLines.suffix(12).joined(separator: "\n"))+ throw VPhoneLaunchpadError(String(localized: "The machine stopped while in DFU mode."), detail: log.tail)}}@@ -433,7 +440,6 @@ final class VPhoneLaunchpadCreationPipeline {statuses[.restore] = .runningcurrent = .restoreisRunning = true- log = VPhoneLaunchpadPreview.creationLog}}#endifdiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swiftindex 122d309e..9532a7cf 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift@@ -29,6 +29,7 @@ struct VPhoneLaunchpadMachineStateLabel: View {struct VPhoneLaunchpadMachineInspector: View {let machine: VPhoneLaunchpadMachinelet onShowProgress: (String) -> Void+ let onOpenConsole: (String) -> Void@Environment(VPhoneLaunchpadModel.self) private var modelprivate var library: VPhoneLaunchpadMachineLibrary {@@ -82,8 +83,11 @@ struct VPhoneLaunchpadMachineInspector: View {}Section("Console") {- VPhoneLaunchpadLogView(lines: library.consoles[machine.name] ?? [])- .frame(minHeight: 160)+ Button {+ onOpenConsole(machine.name)+ } label: {+ Label("Open Console", systemImage: "arrow.up.right")+ }}Section("Recent Commands") {@@ -91,8 +95,6 @@ struct VPhoneLaunchpadMachineInspector: View {}}.formStyle(.grouped)- .onAppear { library.loadConsoleIfNeeded(machine.name) }- .onChange(of: machine.name) { _, name in library.loadConsoleIfNeeded(name) }}private func value(_ title: LocalizedStringKey, _ value: String) -> some View {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swiftindex 360e4623..c77e468b 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift@@ -14,7 +14,9 @@ final class VPhoneLaunchpadMachineLibrary {private(set) var machines: [VPhoneLaunchpadMachine] = []private(set) var listError: String?private(set) var startedAt: [String: Date] = [:]- private(set) var consoles: [String: [String]] = [:]+ /// Machines whose console printed a panic since Launchpad last started+ /// them. The console text itself stays in the log file.+ private(set) var panicked: Set<String> = []private(set) var creations: [String: VPhoneLaunchpadCreationPipeline] = [:]private(set) var globalActivity: String?var selection: String?@@ -145,31 +147,15 @@ final class VPhoneLaunchpadMachineLibrary {.appendingPathComponent("\(name)\(suffix).log")}- func appendConsole(_ name: String, _ line: String) {- var lines = consoles[name] ?? []- lines.append(line)- if lines.count > 500 {- lines.removeFirst(lines.count - 500)- }- consoles[name] = lines- }-- /// Shows the tail of a previous session's console log for a machine that- /// Launchpad did not start in this session.- func loadConsoleIfNeeded(_ name: String) {- guard consoles[name] == nil,- let handle = try? FileHandle(forReadingFrom: Self.consoleLog(name))- else {+ /// Adds a line of Launchpad's own to the console log, after the process+ /// that wrote it has exited.+ private func appendConsoleLog(_ name: String, _ line: String) {+ guard let handle = try? FileHandle(forWritingTo: Self.consoleLog(name)) else {return}defer { try? handle.close() }- let size = (try? handle.seekToEnd()) ?? 0- try? handle.seek(toOffset: size > 65536 ? size - 65536 : 0)- var lines: [String] = []- var splitter = VPhoneLaunchpadLineSplitter()- splitter.feed((try? handle.readToEnd()) ?? Data()) { lines.append($0) }- splitter.flush { lines.append($0) }- consoles[name] = Array(lines.suffix(200))+ _ = try? handle.seekToEnd()+ try? handle.write(contentsOf: Data("\n\(line)\n".utf8))}// MARK: - Start and stop@@ -182,10 +168,12 @@ final class VPhoneLaunchpadMachineLibrary {if headless {arguments.append("--headless")}- consoles[name] = []+ panicked.remove(name)do {let child = try commandLine.start(arguments, logFile: Self.consoleLog(name)) { [weak self] line in- self?.appendConsole(name, line)+ if VPhoneLaunchpadCreationPipeline.isPanic(line) {+ Task { @MainActor in self?.panicked.insert(name) }+ }}launched[name] = childstartedAt[name] = Date()@@ -194,8 +182,8 @@ final class VPhoneLaunchpadMachineLibrary {if launched[name] === child {launched[name] = nilstartedAt[name] = nil+ appendConsoleLog(name, "vm launch exited with status \(status)")}- appendConsole(name, "vm launch exited with status \(status)")await refresh()}} catch {@@ -315,7 +303,6 @@ final class VPhoneLaunchpadMachineLibrary {machines = VPhoneLaunchpadPreview.machinesexternallyRunning = ["research-01"]startedAt = ["research-01": Date().addingTimeInterval(-6130)]- consoles = ["research-01": VPhoneLaunchpadPreview.console]creations = ["ios27-rc": creation]selection = "research-01"}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swiftindex 6912ccbe..1f96507b 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift@@ -9,6 +9,7 @@ struct VPhoneLaunchpadMachinesView: View {case rename(String)case clone(String)case export(String)+ case console(String)var id: String {switch self {@@ -18,6 +19,7 @@ struct VPhoneLaunchpadMachinesView: View {case let .rename(name): "rename-\(name)"case let .clone(name): "clone-\(name)"case let .export(name): "export-\(name)"+ case let .console(name): "console-\(name)"}}}@@ -43,7 +45,11 @@ struct VPhoneLaunchpadMachinesView: View {.inspector(isPresented: $showsInspector) {Group {if let machine = library.selected {- VPhoneLaunchpadMachineInspector(machine: machine) { name in sheet = .creation(name) }+ VPhoneLaunchpadMachineInspector(+ machine: machine,+ onShowProgress: { name in sheet = .creation(name) },+ onOpenConsole: { name in sheet = .console(name) },+ )} else {ContentUnavailableView("No Selection", systemImage: "iphone")}@@ -156,6 +162,7 @@ struct VPhoneLaunchpadMachinesView: View {Button("Show in Finder") {NSWorkspace.shared.activateFileViewerSelecting([library.libraryRoot.appendingPathComponent(machine.name)])}+ Button("Open Console") { sheet = .console(machine.name) }Button("Show Console Log") {NSWorkspace.shared.open(VPhoneLaunchpadMachineLibrary.consoleLog(machine.name))}@@ -243,6 +250,8 @@ struct VPhoneLaunchpadMachinesView: View {}case let .export(name):VPhoneLaunchpadExportView(name: name)+ case let .console(name):+ VPhoneLaunchpadConsoleView(name: name)}}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swiftindex 4be105f3..943fb73c 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadNewMachineView.swift@@ -242,7 +242,7 @@ struct VPhoneLaunchpadCreationView: View {}}Section("Log") {- VPhoneLaunchpadLogView(lines: creation.log)+ VPhoneLaunchpadLogTerminal(url: creation.logFile).frame(minHeight: 200)}}