feat(ios): W3 UI layer + integration CI + ntfy docs

T-iOS-11: TerminalScreen/KeyBar/TerminalViewModel + KeyByteMap (byte-for-byte keybar.ts, arrows excluded from UIKeyCommand to preserve DECCKM)
T-iOS-12: PairingScreen/VM — confirm-before-network (zero-call assertions), §5.4 four-tier warnings, Host construction per contract ruling
T-iOS-13: SessionListScreen/VM — Tunables-paced polling with leak-free teardown, optimistic kill+rollback, pending via overlay (LiveSessionInfo has no pending field)
T-iOS-14: GateBanner/PlanGateSheet/AwayDigestView/GateViewModel — three-way mapping from SessionCore Affordance single source, tap-epoch guard, per-epoch haptics
T-iOS-16: IntegrationTests vs real Node server (10 tests: origin guards, mirror, kill-close vs exit-frame differential, 16MiB+ESC/C0 replay) + ios.yml own-sources coverage gate (red-once demoed)
T-iOS-17: ios/README.md ntfy chapter (read-only verification, file:line cites)
Verified: 224 unit + 10 integration tests green; 5/5 semantic spot-checks; zero Owns violations
This commit is contained in:
Yaojia Wang
2026-07-05 00:13:14 +02:00
parent 5c8c87fb7a
commit 5098643355
33 changed files with 5946 additions and 616 deletions

View File

@@ -0,0 +1,319 @@
import Foundation
import Observation
import SessionCore
import UIKit
import WireProtocol
/// Haptic seam (T-iOS-14): gate-arrival feedback is injected so tests can
/// assert "exactly once per gate epoch" without UIKit hardware.
@MainActor
protocol HapticSignaling {
/// A NEW gate (fresh epoch) is waiting for the user's decision.
func gateDidArrive()
}
/// Production haptics: notification-style buzz a gate is Claude asking for a
/// decision (THE steering primitive), not a mere UI tick.
@MainActor
final class GateHaptics: HapticSignaling {
private let generator = UINotificationFeedbackGenerator()
func gateDidArrive() {
generator.notificationOccurred(.warning)
}
}
/// T-iOS-14 · Gate + away-digest state (plan §3.5): a STANDALONE
/// `@MainActor @Observable` VM consuming the SAME `SessionEvent` stream as
/// `TerminalViewModel` `.gate`/`.digest` are its domain, everything else is
/// ignored here. TerminalScreen wiring (who fans the stream out) is T-iOS-15.
///
/// Stale-tap guard (FIRST line): every rendered gate button carries the epoch
/// of the gate it was rendered against; `decide` compares that epoch and the
/// affordance against the LATEST gate event received and silently drops a
/// mismatch, so a slow tap can never resolve a NEWER gate than the one that
/// was on screen (mirrors the web's pendingEpoch nonce,
/// public/terminal-session.ts:98-102). The engine's `GateTracker.canDecide`
/// is the SECOND line (SessionEngine type doc) both must agree to send.
///
/// Plan-gate mapping is frozen in SessionCore
/// (`GateState.Affordance.clientMessage`, mirror of public/tabs.ts:345-347):
/// Approve+Auto acceptEdits, Approve+Review default, Keep Planning
/// reject. There is NO allowAutoMode gating anywhere the web client never
/// gates the plan three-way, and `uiConfig` is reserved for a future
/// permission-mode picker (plan §3.1 note).
@MainActor
@Observable
final class GateViewModel {
// MARK: - Observable UI state
/// The latest gate event received (nil = lifted). This is what taps are
/// validated against.
private(set) var currentGate: GateState?
/// Visible away digest (nil = nothing rendered; all-zero digests never
/// become visible).
private(set) var digest: AwayDigest?
/// True once the user opened the recent-entries detail; expansion cancels
/// the auto-fade (a digest must never vanish while being read).
private(set) var isDigestExpanded = false
/// Tool gate two-button `GateBanner`.
var toolGate: GateState? { gate(of: .tool) }
/// Plan gate three-way `PlanGateSheet`.
var planGate: GateState? { gate(of: .plan) }
// MARK: - Dependencies & plumbing (not observed)
@ObservationIgnored private let engine: SessionEngine
@ObservationIgnored private let events: AsyncStream<SessionEvent>
@ObservationIgnored private let haptics: any HapticSignaling
@ObservationIgnored private let clock: any Clock<Duration>
@ObservationIgnored private var consumeTask: Task<Void, Never>?
@ObservationIgnored private var fadeTask: Task<Void, Never>?
/// Highest epoch that already buzzed the haptic fires ONCE per epoch
/// (sustained-pending refreshes reuse the epoch and stay silent).
@ObservationIgnored private var lastHapticEpoch = 0
/// Ordered decision queue: taps are synchronous, `engine.send` is async
/// one pump task preserves submission order (same pattern as
/// TerminalViewModel's send pump).
@ObservationIgnored private var decisionQueue: [ClientMessage] = []
@ObservationIgnored private var isPumping = false
// MARK: - Test-visible diagnostics & deterministic barriers (internal)
/// Events applied so far `waitUntilProcessed` barrier counter.
@ObservationIgnored private(set) var processedEventCount = 0
/// Decisions handed to the engine `waitUntilForwarded` barrier counter.
@ObservationIgnored private(set) var forwardedDecisionCount = 0
/// Taps dropped by the first-line guard (stale epoch / lifted gate /
/// affordance no longer offered).
@ObservationIgnored private(set) var droppedStaleDecisionCount = 0
/// Completed auto-fades `waitUntilFadeCompleted` barrier counter.
@ObservationIgnored private(set) var fadeCompletedCount = 0
/// Test tap, called after each event is applied (state already coherent).
@ObservationIgnored var onEventApplied: (@MainActor (SessionEvent) -> Void)?
private struct CountWaiter {
let target: Int
let continuation: CheckedContinuation<Void, Never>
}
@ObservationIgnored private var eventWaiters: [CountWaiter] = []
@ObservationIgnored private var decisionWaiters: [CountWaiter] = []
@ObservationIgnored private var fadeWaiters: [CountWaiter] = []
// MARK: - Lifecycle
/// - Parameters:
/// - engine: send-side dependency (decisions only open/close belong to
/// the T-iOS-15 lifecycle owner).
/// - events: the event stream to consume; the T-iOS-15 wiring passes a
/// fan-out branch of `engine.events` shared with `TerminalViewModel`.
/// - haptics: gate-arrival feedback (production: `GateHaptics`).
/// - clock: drives the digest auto-fade (production: `ContinuousClock`).
init(
engine: SessionEngine, events: AsyncStream<SessionEvent>,
haptics: any HapticSignaling, clock: any Clock<Duration>
) {
self.engine = engine
self.events = events
self.haptics = haptics
self.clock = clock
}
/// Begin consuming events. Idempotent a second call is a no-op.
func start() {
guard consumeTask == nil else { return }
consumeTask = Task { [weak self] in
guard let events = self?.events else { return }
for await event in events {
guard let self else { return }
self.apply(event)
}
self?.releaseAllWaiters() // stream over never leave a test hanging
}
}
/// Stop consuming (screen torn down); cancels the fade timer too.
func stop() {
consumeTask?.cancel()
consumeTask = nil
cancelFade()
releaseAllWaiters()
}
// MARK: - Decisions (Approve / Reject / plan three-way)
/// Resolve the held gate with `affordance`, tapped against the gate whose
/// `epoch` the button rendered. First-line stale guard: the epoch must
/// match the LATEST gate received AND the affordance must still be one the
/// current gate offers (a same-epoch kind morph invalidates old buttons).
/// Mismatch dropped, nothing is sent.
func decide(_ affordance: GateState.Affordance, epoch: Int) {
guard let gate = currentGate, gate.epoch == epoch,
gate.affordances.contains(affordance)
else {
droppedStaleDecisionCount += 1
return
}
decisionQueue = decisionQueue + [affordance.clientMessage]
pumpIfIdle()
}
// MARK: - Digest interactions
/// Show the recent-entries detail; cancels the auto-fade so the digest
/// never vanishes while being read (documented decision).
func expandDigest() {
guard digest != nil else { return }
isDigestExpanded = true
cancelFade()
}
/// Explicitly dismiss the digest (the on the summary row).
func dismissDigest() {
digest = nil
isDigestExpanded = false
cancelFade()
}
// MARK: - Event application (MainActor)
private func apply(_ event: SessionEvent) {
switch event {
case .gate(let gate):
applyGate(gate)
case .digest(let digest):
applyDigest(digest)
case .connection, .adopted, .output, .exited, .telemetry:
break // TerminalViewModel's domain (T-iOS-11)
}
processedEventCount += 1
onEventApplied?(event)
eventWaiters = drainWaiters(eventWaiters, reached: processedEventCount)
}
private func applyGate(_ gate: GateState?) {
currentGate = gate
guard let gate, gate.epoch > lastHapticEpoch else { return }
lastHapticEpoch = gate.epoch // exactly one buzz per epoch
haptics.gateDidArrive()
}
/// All-zero digest render nothing (spec). A visible digest starts
/// collapsed and auto-fades after `Tunables.digestFadeDelay` unless the
/// user expands it first.
private func applyDigest(_ incoming: AwayDigest) {
guard !incoming.isEmpty else { return }
cancelFade()
digest = incoming
isDigestExpanded = false
scheduleFade()
}
private func gate(of kind: GateKind) -> GateState? {
guard let currentGate, currentGate.kind == kind else { return nil }
return currentGate
}
// MARK: - Digest auto-fade (injected clock; zero real waits in tests)
private func scheduleFade() {
let clock = self.clock
fadeTask = Task { [weak self] in
do {
try await clock.sleep(for: Tunables.digestFadeDelay, tolerance: nil)
} catch {
return // cancelled: expanded, dismissed, replaced, or stopped
}
self?.completeFade()
}
}
private func completeFade() {
guard !isDigestExpanded else { return } // expand cancels; belt & braces
digest = nil
fadeTask = nil
fadeCompletedCount += 1
fadeWaiters = drainWaiters(fadeWaiters, reached: fadeCompletedCount)
}
private func cancelFade() {
fadeTask?.cancel()
fadeTask = nil
}
// MARK: - Ordered decision pump
private func pumpIfIdle() {
guard !isPumping else { return }
isPumping = true
Task { await self.pumpDecisions() }
}
private func pumpDecisions() async {
while let next = decisionQueue.first {
decisionQueue = Array(decisionQueue.dropFirst())
await engine.send(next)
forwardedDecisionCount += 1
decisionWaiters = drainWaiters(decisionWaiters, reached: forwardedDecisionCount)
}
isPumping = false
}
// MARK: - Deterministic test barriers (no polling, no real sleeps)
/// Suspends until at least `eventCount` events have been applied.
func waitUntilProcessed(eventCount target: Int) async {
await withCheckedContinuation { continuation in
guard processedEventCount < target else {
continuation.resume()
return
}
eventWaiters = eventWaiters + [CountWaiter(target: target, continuation: continuation)]
}
}
/// Suspends until at least `decisionCount` decisions reached the engine.
func waitUntilForwarded(decisionCount target: Int) async {
await withCheckedContinuation { continuation in
guard forwardedDecisionCount < target else {
continuation.resume()
return
}
decisionWaiters = decisionWaiters
+ [CountWaiter(target: target, continuation: continuation)]
}
}
/// Suspends until at least `count` auto-fades have completed.
func waitUntilFadeCompleted(count target: Int) async {
await withCheckedContinuation { continuation in
guard fadeCompletedCount < target else {
continuation.resume()
return
}
fadeWaiters = fadeWaiters + [CountWaiter(target: target, continuation: continuation)]
}
}
/// Resumes every waiter satisfied by `count`; returns the still-waiting
/// remainder (immutable style the caller reassigns).
private func drainWaiters(_ waiters: [CountWaiter], reached count: Int) -> [CountWaiter] {
let satisfied = waiters.filter { $0.target <= count }
for waiter in satisfied {
waiter.continuation.resume()
}
return waiters.filter { $0.target > count }
}
private func releaseAllWaiters() {
let all = eventWaiters + decisionWaiters + fadeWaiters
eventWaiters = []
decisionWaiters = []
fadeWaiters = []
for waiter in all {
waiter.continuation.resume()
}
}
}

View File

@@ -0,0 +1,398 @@
import APIClient
import Foundation
import HostRegistry
import Observation
import WireProtocol
/// T-iOS-12 · Pairing state machine (plan §7 / §5.4).
///
/// Flow: scan / manual URL **confirm gate** two-step probe
/// `Host{id,name}` into the `HostStore` + navigate signal.
///
/// Security invariants (plan §5 / task RED list):
/// - Scan payloads are UNTRUSTED external input: parsed exclusively through
/// `HostEndpoint` (single-point derivation no hand-assembly), non-http(s)
/// rejected with copy, and **zero network happens before the user confirms**
/// (probe already GETs the target; probe spawns a PTY on it).
/// - The §5.4 warning tiers render ON the confirm page; the public-host tier
/// is BLOCKING `confirmConnect` refuses to probe until the user has set
/// `hasAcknowledgedPublicRisk` explicitly.
/// - Every `PairingError` maps to inline copy + a recovery action
/// (`localNetworkDenied` Settings deep-link; `originRejected` surfaces the
/// probe's hint VERBATIM; `atsBlocked` uses the §3.4 wording).
///
/// Documented decisions:
/// - **Manual entry reuses the same confirm state as scanning** (task left it
/// free): one code path, and the §5.4 warning tiers apply uniformly to
/// typed URLs too. Convenience: input without `://` gets an `http://`
/// prefix before the `HostEndpoint` parse (scan payloads get NO such help).
/// - **Host classification is (re)implemented here**: APIClient's
/// `PairingError.isPrivateOrLocalHost` is internal AND too coarse for the
/// tiers (it collapses loopback/Tailscale/RFC1918 into one bucket).
/// Duplication noted for the T-iOS-38 dedup pass.
/// - `.local` (mDNS) hosts over http are shown the plaintext-LAN notice: they
/// resolve to LAN addresses, so the §5.4 "ws:// on an untrusted LAN" row
/// applies to them the same way.
///
/// §3.4 contract ruling (2026-07-04): the injected probe returns the validated
/// `HostEndpoint`; `Host{id: UUID(), name:}` is constructed HERE (id/name are
/// not the probe's to know). Production wiring (T-iOS-15) passes
/// `runPairingProbe` with the real transports.
@MainActor
@Observable
final class PairingViewModel {
/// The probe, injected as a closure so tests can both fake results AND
/// assert non-invocation before the user confirms (task RED list).
typealias Probe = @Sendable (HostEndpoint) async -> Result<HostEndpoint, PairingError>
// MARK: - UI state model
/// §5.4 warning tiers, decided from scheme + host class (see `warning(for:)`).
enum SecurityWarning: Equatable, Sendable {
/// https anywhere private-class, or wsloopback: nothing to warn about.
case none
/// ws100.64/10 or `*.ts.net`: WireGuard already encrypts no
/// plaintext warning, an optional positive badge instead.
case tailscaleEncrypted
/// wsRFC1918 / link-local / `.local`: NON-blocking notice keystrokes
/// and output are sniffable on the same LAN; prefer `tailscale serve`.
case plaintextLAN
/// Public host (http AND https alike, §5.4 table): strongest BLOCKING
/// warning anyone who can reach the port gets a shell.
case publicHostBlocking
var isBlocking: Bool { self == .publicHostBlocking }
}
/// The parsed-but-not-yet-probed target shown on the confirm page.
struct PendingHost: Equatable, Sendable {
let endpoint: HostEndpoint
let warning: SecurityWarning
/// `scheme://host[:port]` via `HostEndpoint`'s single-point derivation
/// (browser-Origin serialization) NEVER hand-assembled.
var displayAddress: String { endpoint.originHeader }
}
/// What the failure UI offers besides the message.
enum RecoveryAction: Equatable, Sendable {
case retry
/// iOS Local Network permission was denied deep-link to the app's
/// Settings pane (its toggle lives there).
case openLocalNetworkSettings
}
struct FailureDisplay: Equatable, Sendable {
let message: String
let action: RecoveryAction
}
enum Phase: Equatable {
case idle
case confirming(PendingHost)
case probing(PendingHost)
case failed(PendingHost, FailureDisplay)
case paired(HostRegistry.Host)
}
// MARK: - Observable state
private(set) var phase: Phase = .idle
/// Inline rejection copy for invalid scan/manual input (idle-state error).
private(set) var inputRejection: String?
/// Editable name shown on the confirm page; defaults to the endpoint host
/// and falls back to it when the user clears the field.
var hostName = ""
/// Explicit user acknowledgement for the blocking public-host warning.
var hasAcknowledgedPublicRisk = false
/// Set when confirm was attempted on a blocking warning WITHOUT the
/// acknowledgement the UI highlights the ack control.
private(set) var needsPublicRiskAcknowledgement = false
/// Navigate signal: set exactly once when pairing completes (T-iOS-15
/// observes it to move on to the session list).
private(set) var pairedHost: HostRegistry.Host?
// MARK: - Dependencies (not observed)
@ObservationIgnored private let store: any HostStore
@ObservationIgnored private let probe: Probe
init(store: any HostStore, probe: @escaping Probe) {
self.store = store
self.probe = probe
}
// MARK: - Input boundaries (untrusted, validated via HostEndpoint)
/// QR scan result (`public/qr.ts` encodes `location.origin`). Strict: the
/// payload must already be a full http(s) URL no scheme inference for
/// untrusted external input.
func handleScannedCode(_ payload: String) {
guard canAcceptNewTarget else { return }
let trimmed = payload.trimmingCharacters(in: .whitespacesAndNewlines)
guard let url = URL(string: trimmed), let endpoint = HostEndpoint(baseURL: url) else {
inputRejection = PairingCopy.scanRejected
return
}
enterConfirming(endpoint)
}
/// Manually typed URL. The user knows what they typed, but it still goes
/// through the SAME confirm state (uniform warning tiers documented
/// decision). Convenience: no `://` `http://` prefix before parsing.
func submitManualURL(_ text: String) {
guard canAcceptNewTarget else { return }
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
inputRejection = PairingCopy.manualRejected
return
}
let candidate = trimmed.contains(Self.schemeSeparator)
? trimmed
: Self.defaultManualScheme + trimmed
guard let url = URL(string: candidate), let endpoint = HostEndpoint(baseURL: url) else {
inputRejection = PairingCopy.manualRejected
return
}
enterConfirming(endpoint)
}
/// Back out of confirm/failed to a clean entry state. Never probes.
func cancel() {
phase = .idle
inputRejection = nil
hasAcknowledgedPublicRisk = false
needsPublicRiskAcknowledgement = false
}
// MARK: - Confirm probe store
/// The ONLY way network starts. No-op unless confirming; a blocking
/// warning without explicit acknowledgement refuses and flags the UI.
func confirmConnect() async {
guard case .confirming(let pending) = phase else { return }
if pending.warning.isBlocking && !hasAcknowledgedPublicRisk {
needsPublicRiskAcknowledgement = true
return
}
await runProbe(for: pending)
}
/// Re-run the full probe against the same endpoint after a failure.
func retry() async {
guard case .failed(let pending, _) = phase else { return }
await runProbe(for: pending)
}
private var canAcceptNewTarget: Bool {
switch phase {
case .idle, .confirming, .failed:
return true
case .probing, .paired:
return false
}
}
private func enterConfirming(_ endpoint: HostEndpoint) {
inputRejection = nil
hasAcknowledgedPublicRisk = false
needsPublicRiskAcknowledgement = false
hostName = endpoint.baseURL.host ?? ""
phase = .confirming(PendingHost(
endpoint: endpoint, warning: Self.warning(for: endpoint)
))
}
private func runProbe(for pending: PendingHost) async {
needsPublicRiskAcknowledgement = false
phase = .probing(pending)
switch await probe(pending.endpoint) {
case .failure(let error):
phase = .failed(pending, Self.display(for: error))
case .success(let endpoint):
await storePairedHost(endpoint: endpoint, pending: pending)
}
}
/// §3.4 ruling: `Host{id,name}` is constructed here, from the PROBED
/// endpoint. A store failure is surfaced explicitly (never swallowed);
/// retry re-runs the whole confirm flow.
private func storePairedHost(endpoint: HostEndpoint, pending: PendingHost) async {
let trimmedName = hostName.trimmingCharacters(in: .whitespacesAndNewlines)
let fallbackName = endpoint.baseURL.host ?? endpoint.originHeader
let host = HostRegistry.Host(
id: UUID(),
name: trimmedName.isEmpty ? fallbackName : trimmedName,
endpoint: endpoint
)
do {
_ = try await store.upsert(host)
} catch {
phase = .failed(pending, FailureDisplay(
message: PairingCopy.storeFailed, action: .retry
))
return
}
pairedHost = host
phase = .paired(host)
}
// MARK: - PairingError copy + action (task RED list, one case each)
static func display(for error: PairingError) -> FailureDisplay {
switch error {
case .localNetworkDenied:
return FailureDisplay(
message: PairingCopy.localNetworkDenied, action: .openLocalNetworkSettings
)
case .hostUnreachable(let underlying):
return FailureDisplay(
message: PairingCopy.hostUnreachable(underlying), action: .retry
)
case .httpOkButNotWebTerminal:
return FailureDisplay(message: PairingCopy.notWebTerminal, action: .retry)
case .originRejected(let hint):
// The probe already derived the complete actionable copy from
// endpoint.originHeader surface it VERBATIM, never re-derive.
return FailureDisplay(message: hint, action: .retry)
case .atsBlocked(let host):
return FailureDisplay(message: PairingCopy.atsBlocked(host: host), action: .retry)
case .tlsFailure:
return FailureDisplay(message: PairingCopy.tlsFailure, action: .retry)
case .timeout:
return FailureDisplay(message: PairingCopy.timeout, action: .retry)
}
}
// MARK: - §5.4 warning tiers
/// Decide the confirm-page warning from scheme + host class. Public hosts
/// block regardless of scheme (§5.4 table: https is included in the
/// public-host confirm warning); otherwise https clears every notice.
static func warning(for endpoint: HostEndpoint) -> SecurityWarning {
let hostClass = classifyHost(endpoint.baseURL.host ?? "")
if hostClass == .publicHost {
return .publicHostBlocking
}
if endpoint.baseURL.scheme?.lowercased() == Self.httpsScheme {
return .none
}
switch hostClass {
case .loopback:
return .none
case .tailscale:
return .tailscaleEncrypted
case .privateLAN:
return .plaintextLAN
case .publicHost:
return .publicHostBlocking // unreachable; keeps the switch total
}
}
/// Address classes relevant to §5.4. NOTE: near-duplicate of APIClient's
/// internal `isPrivateOrLocalHost` (finer-grained here) T-iOS-38 dedup.
enum HostClass: Equatable, Sendable {
case loopback
case tailscale
case privateLAN
case publicHost
}
static func classifyHost(_ rawHost: String) -> HostClass {
let host = rawHost.lowercased()
.trimmingCharacters(in: CharacterSet(charactersIn: "[]")) // IPv6 brackets
if host == Self.localhostName {
return .loopback
}
if host.hasSuffix(Self.tailscaleMagicDNSSuffix) {
return .tailscale
}
if host.hasSuffix(Self.mdnsSuffix) {
return .privateLAN
}
if let octets = ipv4Octets(host) {
return classifyIPv4(octets)
}
if host.contains(":") {
return classifyIPv6(host)
}
return .publicHost
}
private static func classifyIPv4(_ octets: [Int]) -> HostClass {
switch (octets[0], octets[1]) {
case (127, _):
return .loopback
case (10, _), (192, 168), (169, 254):
return .privateLAN // RFC1918 10/8, 192.168/16 · link-local 169.254/16
case (172, 16...31):
return .privateLAN // RFC1918 172.16/12
case (100, 64...127):
return .tailscale // CGNAT 100.64/10
default:
return .publicHost
}
}
private static func classifyIPv6(_ host: String) -> HostClass {
if host == Self.ipv6Loopback {
return .loopback
}
let isLinkLocal = host.hasPrefix(Self.ipv6LinkLocalPrefix)
let isULA = host.hasPrefix("fc") || host.hasPrefix("fd") // fc00::/7
return (isLinkLocal || isULA) ? .privateLAN : .publicHost
}
private static func ipv4Octets(_ host: String) -> [Int]? {
let parts = host.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == Self.ipv4OctetCount else { return nil }
let octets = parts.compactMap { Int($0) }
guard octets.count == Self.ipv4OctetCount,
octets.allSatisfy({ Self.ipv4OctetRange.contains($0) })
else { return nil }
return octets
}
// MARK: - Named constants (no magic values, plan §4)
private static let schemeSeparator = "://"
private static let defaultManualScheme = "http://"
private static let httpsScheme = "https"
private static let localhostName = "localhost"
private static let tailscaleMagicDNSSuffix = ".ts.net"
private static let mdnsSuffix = ".local"
private static let ipv6Loopback = "::1"
private static let ipv6LinkLocalPrefix = "fe80"
private static let ipv4OctetCount = 4
private static let ipv4OctetRange = 0...255
}
/// User-facing pairing copy (plan §3.4 taxonomy actionable wording; §5.2
/// Local-Network guidance including the iOS 18 restart caveat).
enum PairingCopy {
static let scanRejected =
"二维码不是 http(s) 地址,无法配对。请扫描 web 终端工具栏「Connect a device」弹出的二维码。"
static let manualRejected =
"无法解析这个地址。请输入完整 URL例如 http://192.168.1.5:3000"
static let storeFailed =
"主机已通过验证,但保存到本机失败,请重试。"
static let localNetworkDenied =
"无法访问本地网络——「本地网络」权限可能被拒绝。请到 设置 → 隐私与安全性 → 本地网络 打开 WebTerm 的开关"
+ "iOS 18 存在需要重启手机才生效的已知问题)。"
static let notWebTerminal =
"对方在响应 HTTP但不是 web-terminal——端口对吗"
static let tlsFailure =
"TLS 连接失败:证书无效或不受信任。"
static let timeout =
"连接超时。请确认主机在线、与手机在同一网络后重试。"
static func hostUnreachable(_ underlying: String) -> String {
"无法连接主机:\(underlying)"
}
/// §3.4 wording for the ATS cleartext block.
static func atsBlocked(host: String) -> String {
"明文 HTTP 被 ATS 拦截——\(host) 所在 IP 段不在 App 例外列表内,"
+ "请改用 https / tailscale serve或反馈该网段。"
}
}

View File

@@ -0,0 +1,351 @@
import APIClient
import Foundation
import HostRegistry
import Observation
import WireProtocol
/// T-iOS-13 · Session list state (merged chooser + dashboard, plan §7):
/// one glance answers "do I need to step in?" status dot / pending badge,
/// telemetry chips with staleness, swipe-to-kill, and the navigation signal
/// into `TerminalScreen`.
///
/// Polling: while the screen is visible, `GET /live-sessions` every
/// `Tunables.listPollInterval` (mirrors public/launcher.ts `REFRESH_MS`),
/// paced on an injected `Clock` (FakeClock in tests zero real waits).
/// `disappeared()` cancels the poll task; the leak test asserts the parked
/// sleeper is reclaimed.
///
/// Documented decisions:
/// - **Pending is an overlay, not a list field**: `LiveSessionInfo`
/// (src/types.ts:246-256) carries NO `pending` that signal only exists on
/// the WS status side-channel (the server's pendingApprovals), exactly like
/// the web dashboard reads it from attached tabs (public/tabs.ts snapshot()).
/// The T-iOS-15 wiring forwards gate/status events into
/// `setPendingApproval`; this VM owns the merge and the badge PRIORITY.
/// - **Kill is optimistic via a hidden-id set**: rows derive from the last
/// fetch minus `hiddenKilledIds`, so rollback restores the exact original
/// position, and a poll racing the DELETE cannot resurrect the row. A 404
/// on DELETE means "already gone" and counts as success.
/// - **A failed poll never wipes the list**: stale rows + explicit copy beat
/// a blank screen on one dropped packet.
@MainActor
@Observable
final class SessionListViewModel {
// MARK: - Row model
/// What the row leads with: the held-approval badge outranks the dot.
enum StatusIndicator: Equatable, Sendable {
case pendingApproval
case status(ClaudeStatus)
/// Mirrors public/tabs.ts:74-80 `claudeIcon`; for a held approval.
var glyph: String {
switch self {
case .pendingApproval: return ""
case .status(.working): return ""
case .status(.waiting): return ""
case .status(.idle): return ""
case .status(.stuck): return ""
case .status(.unknown): return ""
}
}
}
/// Immutable render snapshot of one session (rebuilt wholesale per fetch).
struct SessionRow: Equatable, Identifiable, Sendable {
let info: LiveSessionInfo
let isPendingApproval: Bool
let telemetry: TelemetryChips.Model?
var id: UUID { info.id }
var indicator: StatusIndicator {
isPendingApproval ? .pendingApproval : .status(info.status)
}
}
/// Navigation signal consumed by the T-iOS-15 wiring. `sessionId == nil`
/// = "+ New session" (`attach(null)` downstream). A fresh `id` per request
/// means repeated taps re-fire `onChange` observers.
struct OpenRequest: Equatable, Sendable, Identifiable {
let id: UUID
let host: HostRegistry.Host
let sessionId: UUID?
}
enum EmptyState: Equatable {
/// No hosts in the store pairing is the only next step.
case notPaired
/// Paired + fetched successfully, but nothing is running.
case noSessions
}
// MARK: - Observable state
private(set) var hosts: [HostRegistry.Host] = []
private(set) var activeHost: HostRegistry.Host?
private(set) var rows: [SessionRow] = []
/// Last poll failed (stale rows stay visible). Cleared by the next success.
private(set) var fetchErrorMessage: String?
/// Last kill failed (row already rolled back).
private(set) var killErrorMessage: String?
/// Host store read failed explicit, never a silent empty list.
private(set) var hostsErrorMessage: String?
private(set) var openRequest: OpenRequest?
var emptyState: EmptyState? {
if hasAttemptedHostLoad && hosts.isEmpty { return .notPaired }
if hasLoadedOnce && rows.isEmpty && fetchErrorMessage == nil { return .noSessions }
return nil
}
// MARK: - Dependencies & internal state (not observed)
@ObservationIgnored private let hostStore: any HostStore
@ObservationIgnored private let http: any HTTPTransport
@ObservationIgnored private let clock: any Clock<Duration>
/// Injected time source for telemetry staleness (ms since epoch).
@ObservationIgnored private let nowMs: @Sendable () -> Int
@ObservationIgnored private var pollTask: Task<Void, Never>?
@ObservationIgnored private var latestFetched: [LiveSessionInfo] = []
@ObservationIgnored private var hiddenKilledIds: Set<UUID> = []
@ObservationIgnored private var pendingSessionIds: Set<UUID> = []
@ObservationIgnored private var hasAttemptedHostLoad = false
@ObservationIgnored private var hasLoadedOnce = false
private var apiClient: APIClient? {
activeHost.map { APIClient(endpoint: $0.endpoint, http: http) }
}
init(
hostStore: any HostStore,
http: any HTTPTransport,
clock: any Clock<Duration>,
nowMs: @escaping @Sendable () -> Int = SessionListViewModel.currentTimeMs
) {
self.hostStore = hostStore
self.http = http
self.clock = clock
self.nowMs = nowMs
}
// MARK: - Visibility lifecycle (poll task owner)
/// Screen became visible: load hosts, then poll every `listPollInterval`.
/// Idempotent a second call while polling is a no-op.
func appeared() {
guard pollTask == nil else { return }
pollTask = Task { [weak self] in
await self?.runPollLoop()
}
}
/// Screen left: cancel the poll task (its parked sleep throws
/// `CancellationError` and the loop exits no leaked timer).
func disappeared() {
pollTask?.cancel()
pollTask = nil
releaseFetchWaiters()
}
private func runPollLoop() async {
await reloadHosts()
while !Task.isCancelled {
await refreshOnce()
do {
try await clock.sleep(for: Tunables.listPollInterval, tolerance: nil)
} catch {
return // cancelled while parked the only way sleep throws
}
}
}
// MARK: - Hosts (multi-host header hook)
/// (Re)read the paired hosts. Also called by the T-iOS-15 wiring after the
/// pairing sheet adds one. Keeps `activeHost` if it still exists (picking
/// up renames), else falls back to the first host.
func reloadHosts() async {
do {
hosts = try await hostStore.loadAll()
hostsErrorMessage = nil
} catch {
hosts = []
hostsErrorMessage = SessionListCopy.hostsLoadFailed
}
hasAttemptedHostLoad = true
activeHost = hosts.first(where: { $0.id == activeHost?.id }) ?? hosts.first
}
/// Switch the list to another paired host: reset per-host state and fetch
/// immediately (the poll loop keeps its own cadence).
func selectHost(id: UUID) async {
guard let host = hosts.first(where: { $0.id == id }),
host.id != activeHost?.id else { return }
activeHost = host
latestFetched = []
hiddenKilledIds = []
pendingSessionIds = []
hasLoadedOnce = false
fetchErrorMessage = nil
killErrorMessage = nil
rebuildRows()
await refreshOnce()
}
// MARK: - Fetch (poll tick + pull-to-refresh share one path)
/// Manual refresh (pull-to-refresh).
func refresh() async {
await refreshOnce()
}
private func refreshOnce() async {
defer {
completedFetchCount += 1
resumeFetchWaiters()
}
guard let client = apiClient else { return }
do {
let sessions = try await client.liveSessions()
let fetchedIds = Set(sessions.map(\.id))
latestFetched = sessions
// Prune overlays for sessions the server no longer reports.
hiddenKilledIds = hiddenKilledIds.intersection(fetchedIds)
pendingSessionIds = pendingSessionIds.intersection(fetchedIds)
fetchErrorMessage = nil
hasLoadedOnce = true
} catch {
// Keep the stale rows a blank list on one dropped poll is worse.
fetchErrorMessage = SessionListCopy.fetchFailed(Self.errorDetail(error))
}
rebuildRows()
}
// MARK: - Pending overlay (fed by the WS status side-channel, T-iOS-15)
func setPendingApproval(sessionId: UUID, pending: Bool) {
pendingSessionIds = pending
? pendingSessionIds.union([sessionId])
: pendingSessionIds.subtracting([sessionId])
rebuildRows()
}
// MARK: - Swipe-to-kill (optimistic + rollback)
func kill(sessionId: UUID) async {
guard let client = apiClient,
latestFetched.contains(where: { $0.id == sessionId }) else { return }
killErrorMessage = nil
hiddenKilledIds = hiddenKilledIds.union([sessionId]) // optimistic removal
rebuildRows()
do {
try await client.killSession(id: sessionId)
} catch APIClientError.sessionNotFound {
// Already gone (exited/reaped/killed elsewhere) removal stands.
} catch {
hiddenKilledIds = hiddenKilledIds.subtracting([sessionId]) // rollback
rebuildRows()
killErrorMessage = SessionListCopy.killFailed(Self.errorDetail(error))
}
}
// MARK: - Navigation signals
/// "+ New session" `sessionId: nil` (server spawns a fresh PTY).
func requestNewSession() {
guard let activeHost else { return }
openRequest = OpenRequest(id: UUID(), host: activeHost, sessionId: nil)
}
/// Open a listed session. Unknown ids are refused at the boundary.
func openSession(id: UUID) {
guard let activeHost, rows.contains(where: { $0.id == id }) else { return }
openRequest = OpenRequest(id: UUID(), host: activeHost, sessionId: id)
}
// MARK: - Row derivation (immutable rebuild, single owner)
private func rebuildRows() {
let visible = latestFetched.filter { !hiddenKilledIds.contains($0.id) }
let now = nowMs()
rows = Self.groupingExitedLast(visible).map { info in
SessionRow(
info: info,
isPendingApproval: pendingSessionIds.contains(info.id),
telemetry: TelemetryChips.Model(telemetry: info.telemetry, nowMs: now)
)
}
}
/// Keep the server's order (newest-first, src/session/manager.ts:194) but
/// group `exited:true` at the bottom order preserved inside each group.
static func groupingExitedLast(_ sessions: [LiveSessionInfo]) -> [LiveSessionInfo] {
sessions.filter { !$0.exited } + sessions.filter(\.exited)
}
// MARK: - Error copy helpers
/// `APIClientError` already carries user-facing copy; transport-level
/// errors fall back to their localized description.
private static func errorDetail(_ error: any Error) -> String {
(error as? APIClientError)?.message ?? error.localizedDescription
}
private nonisolated static let millisecondsPerSecond = 1_000.0
nonisolated static func currentTimeMs() -> Int {
Int(Date().timeIntervalSince1970 * millisecondsPerSecond)
}
// MARK: - Deterministic test barriers (same pattern as TerminalViewModel)
/// Completed fetch attempts (successful or not, including no-host ticks).
@ObservationIgnored private(set) var completedFetchCount = 0
private struct CountWaiter {
let target: Int
let continuation: CheckedContinuation<Void, Never>
}
@ObservationIgnored private var fetchWaiters: [CountWaiter] = []
/// Suspends until at least `count` fetches have completed.
func waitUntilFetches(count target: Int) async {
await withCheckedContinuation { continuation in
guard completedFetchCount < target else {
continuation.resume()
return
}
fetchWaiters = fetchWaiters + [CountWaiter(target: target, continuation: continuation)]
}
}
private func resumeFetchWaiters() {
let satisfied = fetchWaiters.filter { $0.target <= completedFetchCount }
fetchWaiters = fetchWaiters.filter { $0.target > completedFetchCount }
for waiter in satisfied {
waiter.continuation.resume()
}
}
private func releaseFetchWaiters() {
let all = fetchWaiters
fetchWaiters = []
for waiter in all {
waiter.continuation.resume()
}
}
}
/// User-facing session-list copy (plan §4: explicit errors, actionable ).
enum SessionListCopy {
static let hostsLoadFailed = "读取已配对主机失败,请关闭本页后重进。"
static func fetchFailed(_ detail: String) -> String {
"刷新会话列表失败:\(detail)"
}
static func killFailed(_ detail: String) -> String {
"结束会话失败:\(detail)"
}
}

View File

@@ -0,0 +1,301 @@
import Foundation
import Observation
import SessionCore
import WireProtocol
/// Terminal screen state (T-iOS-11, plan §3.5): consumes the engine's
/// `SessionEvent` stream on the MainActor and turns it into UI state output
/// forwarded to SwiftTerm, connection banner, non-retryable failure copy and
/// the read-only exit state. All outbound traffic (key bar, hardware key
/// commands, SwiftTerm delegate) funnels through here into ONE ordered queue.
///
/// Testability / stream-sharing decision (documented per task brief):
/// `engine.events` is a single-consumer `AsyncStream`, and GateViewModel
/// (T-iOS-14) must eventually observe `.gate`/`.digest` from the SAME stream.
/// So the events stream is injected SEPARATELY from the engine: today callers
/// pass `engine.events` verbatim (tests do exactly that, over
/// `TestSupport.FakeTransport`); the T-iOS-15 wiring may pass a fan-out branch
/// instead without touching this class.
///
/// Swift 6 strict concurrency: the class is `@MainActor`, the terminal sink is
/// `@MainActor`-typed `feed()` off the main actor cannot compile.
@MainActor
@Observable
final class TerminalViewModel {
// MARK: - UI state model
/// Connection banner state (mirrors the web client's status line:
/// public/terminal-session.ts `SessionStatus`).
enum ConnectionBanner: Equatable {
case none
case connecting
/// Retry `attempt` fires after `next` (ReconnectMachine ladder 1s30s).
case reconnecting(attempt: Int, next: Duration)
}
/// Which terminal the user is looking at: a live one, a dead-for-good one
/// (non-retryable failure), or a finished one (read-only).
enum TerminalPhase: Equatable {
case live
/// Non-retryable terminal failure actionable copy instead of a spinner.
case failed(message: String)
/// The shell exited; the terminal stays readable but accepts no input.
case exited(code: Int, reason: String?)
}
/// Actionable copy for `.failed(.replayTooLarge)` (plan §3.2 / §3.2.1
/// coupling warning): reconnecting would deterministically fail forever,
/// so the user must change a knob, not wait.
static let replayTooLargeMessage =
"服务器 scrollback 超过客户端上限,请调低 SCROLLBACK_BYTES 或调高客户端上限"
private(set) var banner: ConnectionBanner = .none
private(set) var phase: TerminalPhase = .live
/// Server-adopted session id (ALWAYS the server-issued one persisting it
/// per host is the T-iOS-15 wiring's job via `LastSessionStore`).
private(set) var sessionId: UUID?
/// Read-only = no input reaches the PTY (exit / terminal failure). Resize
/// is NOT gated here the engine owns terminal-state dropping.
var isReadOnly: Bool { phase != .live }
/// Single render input for `ReconnectBanner`: terminal phases win over
/// transient connection states.
var bannerModel: ReconnectBanner.Model? {
switch phase {
case .failed(let message):
return .failed(message: message)
case .exited(let code, let reason):
return .exited(code: code, reason: reason)
case .live:
break
}
switch banner {
case .none:
return nil
case .connecting:
return .connecting
case .reconnecting(let attempt, let next):
return .reconnecting(attempt: attempt, retryIn: next)
}
}
// MARK: - Dependencies & plumbing (not observed)
@ObservationIgnored private let engine: SessionEngine
@ObservationIgnored private let events: AsyncStream<SessionEvent>
@ObservationIgnored private var consumeTask: Task<Void, Never>?
/// Where output bytes go (SwiftTerm's `feed(text:)`). `@MainActor`-typed:
/// feeding off the main actor is a compile error.
@ObservationIgnored private var terminalSink: (@MainActor (String) -> Void)?
/// Output that arrived before the SwiftTerm view existed; flushed in order
/// the moment the sink attaches (replay must never be dropped).
@ObservationIgnored private var pendingOutput: [String] = []
/// Ordered outbound queue: UIKit callbacks are synchronous, `engine.send`
/// is async one pump task preserves submission order (two quick key taps
/// must never race each other onto the wire).
@ObservationIgnored private var sendQueue: [ClientMessage] = []
@ObservationIgnored private var isPumping = false
// MARK: - Test-visible diagnostics & deterministic barriers (internal)
/// Events applied so far `waitUntilProcessed` barrier counter.
@ObservationIgnored private(set) var processedEventCount = 0
/// Sends handed to the engine so far `waitUntilForwarded` barrier counter.
@ObservationIgnored private(set) var forwardedSendCount = 0
/// Input dropped because the terminal is read-only (exit/failed).
@ObservationIgnored private(set) var droppedReadOnlyInputCount = 0
/// Test tap, called after each event is applied (state already coherent).
@ObservationIgnored var onEventApplied: (@MainActor (SessionEvent) -> Void)?
private struct CountWaiter {
let target: Int
let continuation: CheckedContinuation<Void, Never>
}
@ObservationIgnored private var eventWaiters: [CountWaiter] = []
@ObservationIgnored private var sendWaiters: [CountWaiter] = []
// MARK: - Lifecycle
/// - Parameters:
/// - engine: send-side dependency (`send` only `open`/`close` belong to
/// the T-iOS-15 wiring that constructs the engine).
/// - events: the event stream to consume; pass `engine.events` unless a
/// fan-out branch is needed (see type doc).
init(engine: SessionEngine, events: AsyncStream<SessionEvent>) {
self.engine = engine
self.events = events
}
/// Begin consuming events. Idempotent a second call is a no-op (the
/// stream has exactly one consumer).
func start() {
guard consumeTask == nil else { return }
consumeTask = Task { [weak self] in
guard let events = self?.events else { return }
for await event in events {
guard let self else { return }
self.apply(event)
}
self?.releaseAllWaiters() // stream over never leave a test hanging
}
}
/// Stop consuming (screen torn down). Does NOT close the engine detach
/// vs. keep-running is the T-iOS-15 lifecycle owner's call.
func stop() {
consumeTask?.cancel()
consumeTask = nil
releaseAllWaiters()
}
// MARK: - Terminal output sink
/// Attach the SwiftTerm feed target. Buffered output (anything that
/// arrived before the view existed) flushes immediately, in order.
func attachTerminalSink(_ sink: @escaping @MainActor (String) -> Void) {
terminalSink = sink
let buffered = pendingOutput
pendingOutput = []
for chunk in buffered {
sink(chunk)
}
}
// MARK: - Outbound (KeyBar / UIKeyCommand / SwiftTerm delegate)
/// Key-bar or hardware key press: bytes resolved through `KeyByteMap`
/// (the single source of truth plan §7 T-iOS-11).
func send(key: KeyByteMap.Key) {
sendInput(KeyByteMap.bytes(for: key))
}
/// Raw input bytes, verbatim (invariant #9 no content filtering).
/// Dropped (and counted) while the terminal is read-only.
func sendInput(_ data: String) {
guard !isReadOnly else {
droppedReadOnlyInputCount += 1
return
}
enqueueSend(.input(data: data))
}
/// Terminal geometry changed (SwiftTerm `sizeChanged`). Always forwarded
/// the engine validates bounds and owns terminal-state dropping.
func sendResize(cols: Int, rows: Int) {
enqueueSend(.resize(cols: cols, rows: rows))
}
// MARK: - Event application (single consumer, MainActor)
private func apply(_ event: SessionEvent) {
switch event {
case .connection(let state):
applyConnection(state)
case .adopted(let id):
sessionId = id // ALWAYS adopt the server-issued id
case .output(let data):
deliverOutput(data)
case .exited(let code, let reason):
phase = .exited(code: code, reason: reason)
case .gate, .telemetry, .digest:
break // GateViewModel's domain (T-iOS-14; wired in T-iOS-15)
}
processedEventCount += 1
onEventApplied?(event)
resumeEventWaiters()
}
private func applyConnection(_ state: ConnectionState) {
switch state {
case .connecting:
banner = .connecting
case .connected:
banner = .none
case .reconnecting(let attempt, let next):
banner = .reconnecting(attempt: attempt, next: next)
case .closed:
banner = .none // deliberate end; exit/failure phase (if any) stays
case .failed(.replayTooLarge):
banner = .none
phase = .failed(message: Self.replayTooLargeMessage)
}
}
private func deliverOutput(_ data: String) {
guard let terminalSink else {
pendingOutput = pendingOutput + [data]
return
}
terminalSink(data)
}
// MARK: - Ordered send pump
private func enqueueSend(_ message: ClientMessage) {
sendQueue = sendQueue + [message]
guard !isPumping else { return }
isPumping = true
Task { await self.pumpSendQueue() }
}
private func pumpSendQueue() async {
while let next = sendQueue.first {
sendQueue = Array(sendQueue.dropFirst())
await engine.send(next)
forwardedSendCount += 1
resumeSendWaiters()
}
isPumping = false
}
// MARK: - Deterministic test barriers (no polling, no real sleeps)
/// Suspends until at least `eventCount` events have been applied.
func waitUntilProcessed(eventCount target: Int) async {
await withCheckedContinuation { continuation in
guard processedEventCount < target else {
continuation.resume()
return
}
eventWaiters = eventWaiters + [CountWaiter(target: target, continuation: continuation)]
}
}
/// Suspends until at least `sendCount` messages were handed to the engine.
func waitUntilForwarded(sendCount target: Int) async {
await withCheckedContinuation { continuation in
guard forwardedSendCount < target else {
continuation.resume()
return
}
sendWaiters = sendWaiters + [CountWaiter(target: target, continuation: continuation)]
}
}
private func resumeEventWaiters() {
let satisfied = eventWaiters.filter { $0.target <= processedEventCount }
eventWaiters = eventWaiters.filter { $0.target > processedEventCount }
for waiter in satisfied {
waiter.continuation.resume()
}
}
private func resumeSendWaiters() {
let satisfied = sendWaiters.filter { $0.target <= forwardedSendCount }
sendWaiters = sendWaiters.filter { $0.target > forwardedSendCount }
for waiter in satisfied {
waiter.continuation.resume()
}
}
private func releaseAllWaiters() {
let all = eventWaiters + sendWaiters
eventWaiters = []
sendWaiters = []
for waiter in all {
waiter.continuation.resume()
}
}
}