feat(ipad): W1-W3 — adaptive split-view layout + finding fixes

T-iPad-2: AdaptiveRootView/LayoutPolicy (sole size-class decision), SplitRootView
(NavigationSplitView sidebar+detail), StackRootView (iPhone path verbatim, zero
regression); privacy shade hoisted to shared ZStack top for both branches
T-iPad-3: KeyBarVisibility predicate (hide when hardware keyboard present),
pointer context menu (copy/new-in-cwd/kill, all via existing channels)
T-iPad-4: Projects multi-column grid on iPad (idiom-gated), adaptive sheet detents
T-iPad-5 findings (4/4 fixed): kill onKillSession thread-through +
AppCoordinator.killCurrentSession; split route-gated to .sessions (iPad first-run
pairing); continue-last banner in split sidebar; iPad XCUITest deferred (covered
by SidebarSelectionTests)
Verified: iPhone 16 277 + iPad Pro 11 278 tests green; packages 261 + integration 10;
zero changes under ios/Packages, src/, public/
This commit is contained in:
Yaojia Wang
2026-07-05 19:58:30 +02:00
parent 77502ec4fe
commit 823432b1c8
18 changed files with 1594 additions and 84 deletions

View File

@@ -11,6 +11,28 @@ import UIKit
/// never pops or fights the soft keyboard same reason the web bar bypasses
/// xterm and calls `ws.send`).
// MARK: - Visibility policy (T-iPad-3)
/// Pure predicate deciding whether the soft-keyboard KeyBar
/// (`inputAccessoryView`) should show THE single decision point (mirrors
/// `PrivacyShadePolicy` / `LayoutPolicy`, no scattered checks in views):
/// - a hardware keyboard makes the on-screen key bar redundant default hidden;
/// - no hardware keyboard shown (unchanged iPhone behavior zero regression);
/// - an explicit user toggle (`userOverride`) always wins over the auto default.
///
/// Hardware presence is injected (`GCKeyboard.coalesced != nil` at the call
/// site) so this stays a fast, device-agnostic unit (`KeyBarVisibilityTests`).
enum KeyBarVisibility {
/// - Parameters:
/// - hardwareKeyboardPresent: injected `GCKeyboard.coalesced != nil`.
/// - userOverride: nil = follow the auto default; true/false = the user
/// explicitly forced show/hide (wins over the hardware-driven default).
static func isVisible(hardwareKeyboardPresent: Bool, userOverride: Bool?) -> Bool {
if let userOverride { return userOverride }
return !hardwareKeyboardPresent
}
}
// MARK: - Layout data (mirror of KEYBAR_BUTTONS)
/// One key-bar button: glyph, short function caption (shown under the glyph,

View File

@@ -0,0 +1,144 @@
import UIKit
/// T-iPad-3 · /·
///
/// + `UIContextMenuInteraction` **
/// **
/// - `.copySelection` SwiftTerm `copy(_:)`
/// UI hover
/// - `.newInCwd` T-iOS-29 `onNewInCwd` cwd fresh spawn
/// - `.kill` `onKill`wiring `APIClient.killSession`
/// Origin G RO/G
///
/// iPad idiom `isPointerMenuEnabled` iPhone
/// SwiftTerm
/// One context-menu action, each mapped to an existing channel (no new path).
enum TerminalContextAction: String, CaseIterable, Sendable, Equatable {
case copySelection
case newInCwd
case kill
}
/// Display spec for one menu row (Chinese copy + SF Symbol + destructive flag).
struct TerminalContextItem: Equatable, Sendable {
let action: TerminalContextAction
let title: String
let systemImage: String
let isDestructive: Bool
}
enum TerminalContextMenu {
/// named constantsplan §4
enum Copy {
static let copySelection = "复制选区"
static let newInCwd = "在当前目录开新会话"
static let kill = "结束会话"
}
private enum Symbol {
static let copySelection = "doc.on.doc"
static let newInCwd = "plus.rectangle.on.folder"
static let kill = "xmark.circle"
}
/// iPad idiom size class
/// `LayoutPolicy` stack/split iPhone
/// interaction SwiftTerm
static func isPointerMenuEnabled(idiom: UIUserInterfaceIdiom) -> Bool {
idiom == .pad
}
///
static func items(
canCopySelection: Bool,
canNewInCwd: Bool,
canKill: Bool
) -> [TerminalContextItem] {
var result: [TerminalContextItem] = []
if canCopySelection {
result.append(TerminalContextItem(
action: .copySelection, title: Copy.copySelection,
systemImage: Symbol.copySelection, isDestructive: false
))
}
if canNewInCwd {
result.append(TerminalContextItem(
action: .newInCwd, title: Copy.newInCwd,
systemImage: Symbol.newInCwd, isDestructive: false
))
}
if canKill {
result.append(TerminalContextItem(
action: .kill, title: Copy.kill,
systemImage: Symbol.kill, isDestructive: true
))
}
return result
}
}
/// + `items` `perform`
/// wiring `onNewInCwd`T-iOS-29/ `onKill`APIClient.killSession
/// `onCopySelection`/`hasSelection`
@MainActor
struct TerminalContextMenuModel {
let onNewInCwd: (@MainActor () -> Void)?
let onKill: (@MainActor () -> Void)?
let onCopySelection: @MainActor () -> Void
let hasSelection: @MainActor () -> Bool
/// / wiring
/// =
var items: [TerminalContextItem] {
TerminalContextMenu.items(
canCopySelection: hasSelection(),
canNewInCwd: onNewInCwd != nil,
canKill: onKill != nil
)
}
///
func perform(_ action: TerminalContextAction) {
switch action {
case .copySelection:
onCopySelection()
case .newInCwd:
onNewInCwd?()
case .kill:
onKill?()
}
}
}
/// `UIContextMenuInteraction` `makeModel()`
/// / `UIMenu` `UIAction` `model.perform`
/// iPad `TerminalContextMenu.isPointerMenuEnabled`
@MainActor
final class TerminalContextMenuInteractionDelegate: NSObject, UIContextMenuInteractionDelegate {
private let makeModel: @MainActor () -> TerminalContextMenuModel
init(makeModel: @escaping @MainActor () -> TerminalContextMenuModel) {
self.makeModel = makeModel
}
func contextMenuInteraction(
_ interaction: UIContextMenuInteraction,
configurationForMenuAtLocation location: CGPoint
) -> UIContextMenuConfiguration? {
let model = makeModel()
let items = model.items
guard !items.isEmpty else { return nil } //
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
UIMenu(title: "", children: items.map { item in
UIAction(
title: item.title,
image: UIImage(systemName: item.systemImage),
attributes: item.isDestructive ? .destructive : []
) { _ in
model.perform(item.action)
}
})
}
}
}

View File

@@ -0,0 +1,73 @@
import SwiftUI
import UIKit
/// T-iPad-4 · Projects **** / / sheet
/// detents 仿 `LayoutPolicy`
/// 100%
///
/// ** `UIUserInterfaceIdiom` `horizontalSizeClass`**
/// iPad Projects ** sheet**form sheet
/// `horizontalSizeClass` **compact** iPhone
/// size class iPhone iPhoneiPad
/// Projects sheet idiom Projects /
/// idiom+ stack/split `LayoutPolicy`
/// size-class
enum ProjectsGridLayout {
/// iPhone / iPad 退
static let singleColumn = 1
/// iPad 2 sheet ~440540pt
static let twoColumnMinWidth: CGFloat = 400
/// iPad 3 /
static let threeColumnMinWidth: CGFloat = 760
/// iPhone`.phone`/ `singleColumn` List
/// iPad`.pad` **** 13 `>= 1`
/// 0
static func columnCount(
availableWidth: CGFloat,
idiom: UIUserInterfaceIdiom
) -> Int {
guard idiom == .pad else { return singleColumn }
if availableWidth >= threeColumnMinWidth { return 3 }
if availableWidth >= twoColumnMinWidth { return 2 }
return singleColumn
}
/// iPad iPhone List
static func usesGrid(idiom: UIUserInterfaceIdiom) -> Bool {
idiom == .pad
}
}
/// T-iPad-4 · Projects sheet detents idiom
enum ProjectsSheetSizing {
/// iPhone `nil`** `.presentationDetents`** sheet
/// iPhone iPad `[.medium, .large]`
///
static func detents(idiom: UIUserInterfaceIdiom) -> Set<PresentationDetent>? {
idiom == .pad ? [.medium, .large] : nil
}
}
// MARK: - iPhone iPad detents modifier
/// `.presentationDetents` modifier nil `content`
/// iPhone sheet
private struct AdaptiveSheetDetents: ViewModifier {
let detents: Set<PresentationDetent>?
func body(content: Content) -> some View {
if let detents {
content.presentationDetents(detents)
} else {
content
}
}
}
extension View {
/// iPhone sheetiPad detents
func adaptiveProjectsSheetDetents(idiom: UIUserInterfaceIdiom) -> some View {
modifier(AdaptiveSheetDetents(detents: ProjectsSheetSizing.detents(idiom: idiom)))
}
}

View File

@@ -11,14 +11,26 @@ struct ProjectsScreen: View {
@Bindable var viewModel: ProjectsViewModel
/// "" AppCoordinator.openProject
var onOpen: (ProjectOpenRequest) -> Void = { _ in }
/// T-iPad-4 · idiom `ProjectsGridLayout`/
/// `ProjectsSheetSizing` iPhone List
/// iPad + sheet detentsidiom
/// @Environment `ProjectsLayout`
/// idiom size classiPad sheet compact
private var idiom: UIUserInterfaceIdiom { UIDevice.current.userInterfaceIdiom }
private enum Metrics {
static let rowSpacing: CGFloat = 2
static let chipSpacing: CGFloat = 6
// T-iPad-4 · iPad.padiPhone
static let gridSectionSpacing: CGFloat = 12
static let gridPadding: CGFloat = 16
static let gridCardVerticalPadding: CGFloat = 8
static let gridCardHorizontalPadding: CGFloat = 10
static let gridCardCornerRadius: CGFloat = 10
}
var body: some View {
list
adaptiveContent
.navigationTitle(ProjectsCopy.title)
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $viewModel.searchText, prompt: ProjectsCopy.searchPrompt)
@@ -36,6 +48,22 @@ struct ProjectsScreen: View {
onOpenClaude: { viewModel.requestOpenClaude(cwd: $0) }
)
}
// T-iPad-4 · iPhone sheet iPad
// detents
.adaptiveProjectsSheetDetents(idiom: idiom)
}
// MARK: - idiom ProjectsGridLayout
/// iPhone `list`iPad
/// `gridList`///prefs `ProjectsViewModel`
///
@ViewBuilder private var adaptiveContent: some View {
if ProjectsGridLayout.usesGrid(idiom: idiom) {
gridList
} else {
list
}
}
// MARK: - List
@@ -61,6 +89,75 @@ struct ProjectsScreen: View {
}
}
// MARK: - Gridregular
/// iPad / `ProjectsGridLayout.columnCount`
/// ****GeometryReader/// List
/// builder`groupHeader`/`projectRow`/`errorRows`
/// //prefs
private var gridList: some View {
GeometryReader { proxy in
let columns = ProjectsGridLayout.columnCount(
availableWidth: proxy.size.width,
idiom: idiom
)
ScrollView {
LazyVStack(alignment: .leading, spacing: Metrics.gridSectionSpacing) {
errorRows
if let message = viewModel.emptyStateMessage {
Text(message)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .center)
}
ForEach(viewModel.groups) { group in
gridSection(group, columns: columns)
}
}
.padding(Metrics.gridPadding)
}
.overlay {
if !viewModel.hasLoadedOnce && viewModel.fetchErrorMessage == nil {
ProgressView()
}
}
}
}
@ViewBuilder private func gridSection(_ group: ProjectGroup, columns: Int) -> some View {
let isCollapsed = viewModel.isCollapsed(group)
VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
if group.kind != .flat {
groupHeader(group, isCollapsed: isCollapsed)
.padding(.top, Metrics.gridSectionSpacing)
}
if !isCollapsed {
LazyVGrid(
columns: gridColumns(columns),
alignment: .leading,
spacing: Metrics.chipSpacing
) {
ForEach(group.projects, id: \.path) { project in
projectRow(project, group: group)
.padding(.vertical, Metrics.gridCardVerticalPadding)
.padding(.horizontal, Metrics.gridCardHorizontalPadding)
.background(
.quaternary,
in: RoundedRectangle(cornerRadius: Metrics.gridCardCornerRadius)
)
}
}
}
}
}
/// `columns >= 1` `ProjectsGridLayout`
private func gridColumns(_ count: Int) -> [GridItem] {
Array(
repeating: GridItem(.flexible(), spacing: Metrics.chipSpacing),
count: max(count, ProjectsGridLayout.singleColumn)
)
}
/// prefs
@ViewBuilder private var errorRows: some View {
ForEach(

View File

@@ -1,3 +1,4 @@
import GameController
import SessionCore
import SwiftTerm
import SwiftUI
@@ -25,6 +26,16 @@ struct TerminalScreen: View {
/// `AppCoordinator.openNewSessionInCurrentCwd`nil =
/// / coordinator
var onNewSessionInCwd: (@MainActor () -> Void)? = nil
/// T-iPad-3 · wiring
/// `APIClient.killSession` Origin G nil = kill
/// /线
var onKillSession: (@MainActor () -> Void)? = nil
/// T-iPad-3 · `GCKeyboard.coalesced != nil`
/// / `KeyBarVisibility`
@State private var hasHardwareKeyboard = GCKeyboard.coalesced != nil
/// T-iPad-3 · KeyBar nil =
@State private var keyBarUserOverride: Bool?
private enum Metrics {
static let bannerHorizontalPadding: CGFloat = 12
@@ -33,10 +44,25 @@ struct TerminalScreen: View {
private enum Copy {
static let newSessionInCwd = "在当前目录开新会话"
static let showKeyBar = "显示快捷键栏"
static let hideKeyBar = "隐藏快捷键栏"
}
/// KeyBar `KeyBarVisibility`
private var isKeyBarVisible: Bool {
KeyBarVisibility.isVisible(
hardwareKeyboardPresent: hasHardwareKeyboard,
userOverride: keyBarUserOverride
)
}
var body: some View {
TerminalHostView(viewModel: viewModel)
TerminalHostView(
viewModel: viewModel,
keyBarVisible: isKeyBarVisible,
onNewSessionInCwd: onNewSessionInCwd,
onKillSession: onKillSession
)
.ignoresSafeArea(.container, edges: .bottom)
.overlay(alignment: .top) {
if let model = viewModel.bannerModel {
@@ -47,10 +73,39 @@ struct TerminalScreen: View {
}
}
.animation(.default, value: viewModel.bannerModel)
.toolbar { newSessionToolbarItem }
.toolbar {
newSessionToolbarItem
keyBarToggleToolbarItem
}
.onReceive(NotificationCenter.default.publisher(for: .GCKeyboardDidConnect)) { _ in
hasHardwareKeyboard = true
}
.onReceive(NotificationCenter.default.publisher(for: .GCKeyboardDidDisconnect)) { _ in
hasHardwareKeyboard = GCKeyboard.coalesced != nil
}
.onAppear { viewModel.start() }
}
/// T-iPad-3 · KeyBar
/// iPhone
/// /
@ToolbarContentBuilder private var keyBarToggleToolbarItem: some ToolbarContent {
if hasHardwareKeyboard {
ToolbarItem(placement: .topBarTrailing) {
Button {
keyBarUserOverride = !isKeyBarVisible
} label: {
Label(
isKeyBarVisible ? Copy.hideKeyBar : Copy.showKeyBar,
systemImage: isKeyBarVisible
? "keyboard.chevron.compact.down" : "keyboard"
)
}
.accessibilityIdentifier("terminal.keyBarToggleButton")
}
}
}
/// Mirrors web `tabs.ts newTab()` (M6): the + affordance opens a fresh
/// session in the active session's cwd, if known.
@ToolbarContentBuilder private var newSessionToolbarItem: some ToolbarContent {
@@ -74,6 +129,11 @@ struct TerminalScreen: View {
/// `KeyCommandTerminalView` subclass. Both route through the ViewModel.
private struct TerminalHostView: UIViewRepresentable {
let viewModel: TerminalViewModel
/// T-iPad-3 · KeyBar (`inputAccessoryView`) `KeyBarVisibility`
/// SwiftUI `updateUIView`
let keyBarVisible: Bool
var onNewSessionInCwd: (@MainActor () -> Void)? = nil
var onKillSession: (@MainActor () -> Void)? = nil
func makeCoordinator() -> Coordinator {
Coordinator(viewModel: viewModel)
@@ -88,7 +148,14 @@ private struct TerminalHostView: UIViewRepresentable {
let keyBar = KeyBarView()
keyBar.onKey = { key in viewModel.send(key: key) }
terminal.inputAccessoryView = keyBar
terminal.installKeyBar(keyBar, visible: keyBarVisible)
// T-iPad-3 · / iPad iPhone
// SwiftTerm
terminal.installPointerContextMenuIfSupported(
onNewInCwd: onNewSessionInCwd,
onKill: onKillSession
)
// Output sink: buffered replay flushes now, live bytes follow.
// @MainActor-typed closure feeding off the main actor cannot compile.
@@ -100,7 +167,10 @@ private struct TerminalHostView: UIViewRepresentable {
func updateUIView(_ uiView: KeyCommandTerminalView, context: Context) {
// State-driven UI lives in SwiftUI (banner overlay); the terminal view
// itself is driven by the sink/delegate, nothing to push here.
// itself is driven by the sink/delegate. The only push is the KeyBar
// visibility (hardware-keyboard aware / user toggle) a no-op unless it
// actually changed, so iPhone (always-visible) never reloads input views.
uiView.setKeyBarVisible(keyBarVisible)
}
/// SwiftTerm's delegate is a pre-concurrency protocol; the conformance is
@@ -164,6 +234,14 @@ final class KeyCommandTerminalView: TerminalView {
/// Chord outlet; the screen routes it to `TerminalViewModel.send(key:)`.
var onKeyCommand: (@MainActor (KeyByteMap.Key) -> Void)?
/// Retained KeyBar so visibility can toggle it in/out of `inputAccessoryView`
/// (T-iPad-3). The last-applied value avoids reloading input views when the
/// visibility did not change (iPhone stays byte-identical).
private var keyBar: KeyBarView?
private var appliedKeyBarVisible = true
/// Retained so the interaction's delegate outlives menu presentation.
private var contextMenuDelegate: TerminalContextMenuInteractionDelegate?
override var keyCommands: [UIKeyCommand]? {
(super.keyCommands ?? [])
+ HardwareKeyCommands.build(action: #selector(runHardwareKeyCommand(_:)))
@@ -173,4 +251,64 @@ final class KeyCommandTerminalView: TerminalView {
guard let key = HardwareKeyCommands.key(matching: sender) else { return }
onKeyCommand?(key)
}
// MARK: - KeyBar install / visibility (T-iPad-3)
/// Install the KeyBar as `inputAccessoryView`, honoring the initial
/// visibility (hidden when a hardware keyboard makes it redundant).
func installKeyBar(_ bar: KeyBarView, visible: Bool) {
keyBar = bar
appliedKeyBarVisible = visible
inputAccessoryView = visible ? bar : nil
}
/// Apply a visibility change; a no-op when unchanged so no needless
/// `reloadInputViews()` (the KeyByteMap routing on `keyBar.onKey` is
/// untouched the same bar is only detached/re-attached).
func setKeyBarVisible(_ visible: Bool) {
guard visible != appliedKeyBarVisible else { return }
appliedKeyBarVisible = visible
inputAccessoryView = visible ? keyBar : nil
reloadInputViews()
}
// MARK: - Pointer context menu (T-iPad-3, iPad only)
/// Install the secondary-click / long-press context menu iPad only, so
/// iPhone long-press keeps SwiftTerm's native selection gesture (zero
/// regression). The delegate builds a fresh model per presentation so the
/// copy item reflects the live selection.
func installPointerContextMenuIfSupported(
onNewInCwd: (@MainActor () -> Void)?,
onKill: (@MainActor () -> Void)?
) {
// `UIDevice.current.userInterfaceIdiom` (not `traitCollection`, which can
// be `.unspecified` before the view joins a window at makeUIView time).
guard TerminalContextMenu.isPointerMenuEnabled(
idiom: UIDevice.current.userInterfaceIdiom
) else { return }
let delegate = TerminalContextMenuInteractionDelegate { [weak self] in
TerminalContextMenuModel(
onNewInCwd: onNewInCwd,
onKill: onKill,
onCopySelection: { [weak self] in self?.copySelectionToPasteboard() },
hasSelection: { [weak self] in self?.hasActiveSelection ?? false }
)
}
contextMenuDelegate = delegate
addInteraction(UIContextMenuInteraction(delegate: delegate))
}
/// Whether a selection exists reuses SwiftTerm's own `copy` eligibility
/// (`canPerformAction` returns `selection.active`); pure read, no bytes.
var hasActiveSelection: Bool {
canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil)
}
/// Copy the current selection via SwiftTerm's own `copy(_:)` (selection
/// `UIPasteboard`). Pure UI: it never writes to the PTY, so the byte stream
/// is untouched (invariant preserved same as pointer hover highlight).
func copySelectionToPasteboard() {
copy(nil)
}
}

View File

@@ -0,0 +1,110 @@
import SwiftUI
/// T-iPad-2 · size-class `LayoutPolicy.mode` compact
/// iPhone / iPad Slide Over `StackRootView`
/// regular iPad / / Stage Manager `SplitRootView`
///
///
/// **线**PLAN_IOS_IPAD §5 T-iPad-2
/// - ZStack **** split detail
/// `scenePhase != .active` `PrivacyShadePolicy`
/// split detail stack push
/// - `.task` bootstrap / `.onChange(scenePhase)` / `.onOpenURL` / deep-link
/// alert / add-host sheet / Projects sheet `RootView`
/// compact
///
/// size class ****iPad Slide Over regularcompact
/// UI `terminalController`
/// `AppCoordinator` T-iOS-29 `.id`
///
struct AdaptiveRootView: View {
@Bindable var coordinator: AppCoordinator
@Environment(\.scenePhase) private var scenePhase
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
var body: some View {
ZStack {
layoutBranch
if PrivacyShadePolicy.isShadeVisible(for: scenePhase) {
PrivacyShadeView()
}
}
.task { await coordinator.bootstrap() }
.onChange(of: scenePhase) { _, phase in
coordinator.handleScenePhase(phase)
}
.onOpenURL { coordinator.handleDeepLink(url: $0) } // T-iOS-22
.alert(DeepLinkCopy.hintTitle, isPresented: deepLinkHintBinding) {
Button(DeepLinkCopy.hintConfirm) { coordinator.deepLink.clearHint() }
} message: {
Text(coordinator.deepLink.hintMessage ?? "")
}
.sheet(
isPresented: $coordinator.isAddHostPresented,
onDismiss: { coordinator.addHostDismissed() }
) {
addHostSheet
}
.sheet(
isPresented: $coordinator.isProjectsPresented,
onDismiss: { coordinator.projectsDismissed() }
) {
projectsSheet
}
}
// MARK: - Layout branch (the SOLE size-class consumer)
@ViewBuilder private var layoutBranch: some View {
// Split only makes sense once we're in the session list. `.loading` and
// `.pairing` (genuine iPad first-run, no paired host) get the full-screen
// stack flow regardless of size class a split sidebar has nothing to
// list yet and would strand the user on the not-paired empty state
// (T-iPad-5 finding). Route-gate the split branch.
switch LayoutPolicy.mode(horizontalSizeClass: horizontalSizeClass) {
case .split where coordinator.route == .sessions:
SplitRootView(coordinator: coordinator)
default:
StackRootView(coordinator: coordinator)
}
}
// MARK: - Deep-link hint alert (T-iOS-22)
/// unknown host / store failure `RootView`
private var deepLinkHintBinding: Binding<Bool> {
Binding(
get: { coordinator.deepLink.hintMessage != nil },
set: { presented in
guard !presented else { return }
coordinator.deepLink.clearHint()
}
)
}
// MARK: - Add-host sheet (multi-host entry, list header)
@ViewBuilder private var addHostSheet: some View {
if let viewModel = coordinator.addHostPairingViewModel {
NavigationStack {
PairingScreen(viewModel: viewModel) { host in
coordinator.completeAddHost(host)
}
}
}
}
// MARK: - Projects sheet (T-iOS-26)
/// NavigationStack sheet push
/// "" sheet
@ViewBuilder private var projectsSheet: some View {
if let viewModel = coordinator.projectsViewModel {
NavigationStack {
ProjectsScreen(viewModel: viewModel) { request in
coordinator.openProject(request)
}
}
}
}
}

View File

@@ -170,6 +170,62 @@ final class AppCoordinator {
terminalController = nil
}
/// T-iPad-3 · kill
/// `SessionListViewModel.kill` `APIClient.killSession` Origin
/// detach detail adopted no-op
func killCurrentSession() {
guard let sessionId = terminalController?.terminalViewModel.sessionId else { return }
Task { await sessionList.kill(sessionId: sessionId) }
closeTerminal()
}
// MARK: - Split-view sidebar bridge (T-iPad-2)
/// Detail sidebar getter
/// **adopted** adopted / detail nil
/// stack `terminalController` coordinator
///
var selectedSidebarItem: SidebarItem? {
terminalController?.terminalViewModel.sessionId.map(SidebarItem.session)
}
/// `NavigationSplitView` getter detail setter
/// `open` / `presentProjects`
/// set nil detail
var sidebarSelection: Binding<SidebarItem?> {
Binding(
get: { self.selectedSidebarItem },
set: { item in
guard let item else { return }
self.selectSidebarItem(item)
}
)
}
/// sidebar **** open(id) / open(nil) /
/// presentProjects API沿 WS closeopen
/// new-in-cwd / deep-link `.projects` sheet
func selectSidebarItem(_ item: SidebarItem) {
switch item {
case .session(let sessionId):
switchTerminal(sessionId: sessionId)
case .newSession:
switchTerminal(sessionId: nil)
case .projects:
presentProjects()
}
}
/// WS no-op churn
/// `closeTerminal()` last-seen engine detach
/// `open()`**** activeHost no-op
private func switchTerminal(sessionId: UUID?) {
guard let host = sessionList.activeHost else { return }
if let sessionId, selectedSidebarItem == .session(sessionId) { return }
if terminalController != nil { closeTerminal() }
open(SessionListViewModel.OpenRequest(id: UUID(), host: host, sessionId: sessionId))
}
// MARK: - "" (T-iOS-29)
/// cwd/live-sessions server-adopted
@@ -235,3 +291,12 @@ final class AppCoordinator {
PairingViewModel(store: environment.hostStore, probe: environment.probe)
}
}
/// T-iPad-2 · split sidebar `AppCoordinator`
/// `.session(id)` == `open(id)``.newSession` == `open(nil)`
/// `.projects` == `presentProjects()`
enum SidebarItem: Hashable {
case session(UUID)
case newSession
case projects
}

View File

@@ -0,0 +1,22 @@
import SwiftUI
/// T-iPad-2 ·
public enum LayoutMode: Equatable {
/// iPhone `NavigationStack` push
case stack
/// iPad `NavigationSplitView`sidebar + detail
case split
}
/// T-iPad-2 · **** size-class 仿 `PrivacyShadePolicy`
/// `if sizeClass == `PLAN_IOS_IPAD §4
/// 100%
///
/// regular iPad / / Stage Manager `.split`
/// compact niliPhone / iPad Slide Over / / size class
/// `.stack`nil 退退 iPhone
public enum LayoutPolicy {
public static func mode(horizontalSizeClass: UserInterfaceSizeClass?) -> LayoutMode {
horizontalSizeClass == .regular ? .split : .stack
}
}

View File

@@ -1,62 +1,39 @@
import HostRegistry
import SwiftUI
/// T-iOS-15 · Root of the app: route switch (Pairing / SessionList), terminal
/// push, add-host sheet, scenePhase forwarding and the privacy shade.
/// T-iOS-15 / T-iPad-2 · App `NavigationStack` +
/// + sheets/scenePhase/deepLink 线iPad T-iPad-2
///
/// - `RootView` struct `@main` WebTermApp
/// `RootView(coordinator:)` `AdaptiveRootView`
/// - `AdaptiveRootView` `horizontalSizeClass` `StackRootView`compact
/// `SplitRootView`regulariPad
/// / scenePhase / deepLink / sheets **线**
/// ZStack
///
/// The shade is the TOPMOST layer of this ZStack and appears whenever
/// `scenePhase != .active` (exact rule PrivacyShadePolicy + tests); it
/// covers the whole navigation tree, terminal included. Sheets live above any
/// overlay, but no sheet renders terminal bytes (pairing / plan gate only).
/// `StackRootView` `RootView` body **** compact
/// iPhone
struct RootView: View {
@Bindable var coordinator: AppCoordinator
@Environment(\.scenePhase) private var scenePhase
var body: some View {
ZStack {
NavigationStack {
rootContent
.navigationDestination(isPresented: terminalBinding) {
terminalDestination
}
}
if PrivacyShadePolicy.isShadeVisible(for: scenePhase) {
PrivacyShadeView()
}
}
.task { await coordinator.bootstrap() }
.onChange(of: scenePhase) { _, phase in
coordinator.handleScenePhase(phase)
}
.onOpenURL { coordinator.handleDeepLink(url: $0) } // T-iOS-22
.alert(DeepLinkCopy.hintTitle, isPresented: deepLinkHintBinding) {
Button(DeepLinkCopy.hintConfirm) { coordinator.deepLink.clearHint() }
} message: {
Text(coordinator.deepLink.hintMessage ?? "")
}
.sheet(
isPresented: $coordinator.isAddHostPresented,
onDismiss: { coordinator.addHostDismissed() }
) {
addHostSheet
}
.sheet(
isPresented: $coordinator.isProjectsPresented,
onDismiss: { coordinator.projectsDismissed() }
) {
projectsSheet
}
AdaptiveRootView(coordinator: coordinator)
}
}
/// Deep-link hint alert (unknown host / store failure, T-iOS-22).
private var deepLinkHintBinding: Binding<Bool> {
Binding(
get: { coordinator.deepLink.hintMessage != nil },
set: { presented in
guard !presented else { return }
coordinator.deepLink.clearHint()
}
)
/// T-iPad-2 · compact iPhone / iPad Slide Over
/// `RootView` `NavigationStack` 线
/// /scenePhase/deepLink/sheets `AdaptiveRootView`
struct StackRootView: View {
@Bindable var coordinator: AppCoordinator
var body: some View {
NavigationStack {
rootContent
.navigationDestination(isPresented: terminalBinding) {
terminalDestination
}
}
}
// MARK: - Route switch
@@ -140,7 +117,8 @@ struct RootView: View {
if let controller = coordinator.terminalController {
TerminalContainerView(
controller: controller,
onNewSessionInCwd: { coordinator.openNewSessionInCurrentCwd() }
onNewSessionInCwd: { coordinator.openNewSessionInCurrentCwd() },
onKillSession: { coordinator.killCurrentSession() } // T-iPad-3
)
// T-iOS-29 · identity PER CONTROLLER: an in-place session switch
// (new-in-cwd, deep link) swaps the controller while the
@@ -151,40 +129,15 @@ struct RootView: View {
.id(controller.id)
}
}
// MARK: - Add-host sheet (multi-host entry, list header)
@ViewBuilder private var addHostSheet: some View {
if let viewModel = coordinator.addHostPairingViewModel {
NavigationStack {
PairingScreen(viewModel: viewModel) { host in
coordinator.completeAddHost(host)
}
}
}
}
// MARK: - Projects sheet (T-iOS-26)
/// NavigationStack sheet push
/// "" sheet
@ViewBuilder private var projectsSheet: some View {
if let viewModel = coordinator.projectsViewModel {
NavigationStack {
ProjectsScreen(viewModel: viewModel) { request in
coordinator.openProject(request)
}
}
}
}
}
private enum RootMetrics {
enum RootMetrics {
static let bannerHorizontalPadding: CGFloat = 16
static let bannerVerticalPadding: CGFloat = 8
}
private enum RootCopy {
/// internal `SplitRootView` DRY
enum RootCopy {
static let continueLast = "继续上次会话"
static let projects = "项目"
}

View File

@@ -0,0 +1,110 @@
import SwiftUI
/// T-iPad-2 · regular iPad / / Stage Manager
/// sidebar = `SessionListScreen` **** +
/// stack leading detail = `TerminalContainerView`
/// + gate/digest
///
///
/// - **detail `TerminalContainerView`** push destination
/// split detail PLAN_IOS_IPAD §1
/// - ** `AppCoordinator` **sidebar
/// `selectSidebarItem` / `open` stack
/// - **detail `.id(controller.id)`** controller
/// SwiftTerm ring bufferidentity T-iOS-29
/// - **** `AdaptiveRootView` ZStack
/// detail `scenePhase != .active`
struct SplitRootView: View {
@Bindable var coordinator: AppCoordinator
var body: some View {
NavigationSplitView {
sidebar
} detail: {
detail
}
}
// MARK: - Sidebar + SessionListScreen
private var sidebar: some View {
SessionListScreen(
viewModel: coordinator.sessionList,
onOpen: { request in
// selectSidebarItem
coordinator.selectSidebarItem(sidebarItem(for: request))
},
onAddHost: { coordinator.presentAddHost() }
)
.safeAreaInset(edge: .bottom) { continueLastBanner }
.toolbar { projectsToolbarItem }
}
/// `StackRootView.continueLastBanner` 5
/// sidebar iPad T-iPad-5 finding
@ViewBuilder private var continueLastBanner: some View {
if coordinator.continueLastSessionId != nil {
Button {
coordinator.openContinueLast()
} label: {
Label(RootCopy.continueLast, systemImage: "arrow.uturn.forward.circle.fill")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.padding(.horizontal, RootMetrics.bannerHorizontalPadding)
.padding(.vertical, RootMetrics.bannerVerticalPadding)
.background(.thinMaterial)
}
}
/// `OpenRequest` sidebar sessionId = /
private func sidebarItem(for request: SessionListViewModel.OpenRequest) -> SidebarItem {
request.sessionId.map(SidebarItem.session) ?? .newSession
}
/// `StackRootView.projectsToolbarItem` leading disabled
/// `presentProjects` iPad Projects sheet
/// T-iPad-4
@ToolbarContentBuilder private var projectsToolbarItem: some ToolbarContent {
ToolbarItem(placement: .topBarLeading) {
Button {
coordinator.presentProjects()
} label: {
Label(RootCopy.projects, systemImage: "folder")
}
.disabled(coordinator.sessionList.activeHost == nil)
.accessibilityIdentifier("sessions.projectsButton")
}
}
// MARK: - Detail
@ViewBuilder private var detail: some View {
if let controller = coordinator.terminalController {
NavigationStack {
TerminalContainerView(
controller: controller,
onNewSessionInCwd: { coordinator.openNewSessionInCurrentCwd() },
onKillSession: { coordinator.killCurrentSession() } // T-iPad-3
)
.id(controller.id) // T-iOS-29 · identity per controller
}
} else {
placeholder
}
}
private var placeholder: some View {
ContentUnavailableView {
Label(SplitCopy.placeholderTitle, systemImage: "sidebar.left")
} description: {
Text(SplitCopy.placeholderHint)
}
}
}
/// split `RootCopy.projects`DRY
private enum SplitCopy {
static let placeholderTitle = "选择或新建会话"
static let placeholderHint = "从左侧选择一个运行中的会话,或新建一个开始工作。"
}

View File

@@ -22,6 +22,10 @@ struct TerminalContainerView: View {
/// T-iOS-29 · pass-through to TerminalScreen's toolbar/exit-banner
/// "" action (RootView supplies the coordinator hop).
var onNewSessionInCwd: (@MainActor () -> Void)? = nil
/// T-iPad-3 · pass-through to TerminalScreen's pointer context-menu
/// "" action (root layers supply the coordinator hop). nil on
/// surfaces without a kill affordance (e.g. previews).
var onKillSession: (@MainActor () -> Void)? = nil
/// Epoch of a plan gate the user swiped away suppresses re-present for
/// THAT gate only; a new epoch re-presents automatically.
@State private var dismissedPlanGateEpoch: Int?
@@ -48,7 +52,8 @@ struct TerminalContainerView: View {
var body: some View {
TerminalScreen(
viewModel: controller.terminalViewModel,
onNewSessionInCwd: onNewSessionInCwd
onNewSessionInCwd: onNewSessionInCwd,
onKillSession: onKillSession
)
.id(controller.generation)
.navigationBarTitleDisplayMode(.inline)