feat(ios): rebuild onboarding and device access

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:49 -07:00
1 parent c9679c3ec4
commit 80b89ac44a
10 files changed
+1958 -203

No files matched your search

@@ -0,0 +1,248 @@
import Foundation
struct ConnectionDetails: Equatable, Sendable {
var endpoint: String
var pairingCode: String?
}
enum ConnectionDetailsError: LocalizedError, Equatable {
case empty
case invalidAddress
case unsupportedScheme
var errorDescription: String? {
switch self {
case .empty:
"Paste a T3 pairing link or enter your server address."
case .invalidAddress:
"That connection link does not include a valid server address."
case .unsupportedScheme:
"Use an HTTP or HTTPS T3 server address."
}
}
}
/// Parses the pairing links emitted by local, shared, and hosted T3 environments.
enum ConnectionDetailsParser {
private static let tokenNames = ["token", "pairing_token", "pairingToken", "code"]
private static let endpointNames = ["host", "endpoint", "server", "url"]
private static let wrappedPairingURLNames = ["pairingUrl", "pairing_url"]
static func parse(_ input: String) throws -> ConnectionDetails {
let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { throw ConnectionDetailsError.empty }
let candidate = trimmed.lowercased().hasPrefix("t3code:")
? trimmed
: (firstURL(in: trimmed) ?? trimmed)
let loweredCandidate = candidate.lowercased()
if candidate.contains("://")
|| loweredCandidate.hasPrefix("t3code:")
|| loweredCandidate.hasPrefix("t3:") {
return try parseURL(candidate)
}
let pieces = candidate
.split(whereSeparator: \.isWhitespace)
.map(String.init)
guard let address = pieces.first else { throw ConnectionDetailsError.empty }
let code = pieces.dropFirst().first(where: { !$0.isEmpty })
return ConnectionDetails(
endpoint: try normalizedEndpoint(address),
pairingCode: normalizedCode(code)
)
}
static func normalizedEndpoint(_ input: String) throws -> String {
let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { throw ConnectionDetailsError.empty }
let value: String
if trimmed.contains("://") {
value = trimmed
} else {
let address = bracketBareIPv6(trimmed)
value = "\(EndpointNetworkScope.isLocalHost(trimmed) ? "http" : "https")://\(address)"
}
guard var components = URLComponents(string: value),
let scheme = components.scheme?.lowercased()
else {
throw ConnectionDetailsError.invalidAddress
}
switch scheme {
case "http", "https":
break
case "ws":
components.scheme = "http"
case "wss":
components.scheme = "https"
default:
throw ConnectionDetailsError.unsupportedScheme
}
guard let host = components.host, !host.isEmpty else {
throw ConnectionDetailsError.invalidAddress
}
components.path = ""
components.query = nil
components.fragment = nil
guard var normalized = components.url?.absoluteString else {
throw ConnectionDetailsError.invalidAddress
}
while normalized.hasSuffix("/") {
normalized.removeLast()
}
return normalized
}
private static func parseURL(_ input: String) throws -> ConnectionDetails {
guard let components = URLComponents(string: input),
let scheme = components.scheme?.lowercased()
else {
throw ConnectionDetailsError.invalidAddress
}
let fragmentItems = URLComponents(string: "?\(components.fragment ?? "")")?.queryItems ?? []
let queryItems = components.queryItems ?? []
let allItems = queryItems + fragmentItems
let token = firstValue(named: tokenNames, in: allItems)
if ["t3", "t3code"].contains(scheme) {
if let wrappedPairingURL = firstValue(named: wrappedPairingURLNames, in: allItems) {
var wrapped = try parse(wrappedPairingURL)
if wrapped.pairingCode == nil {
wrapped.pairingCode = normalizedCode(token)
}
return wrapped
}
guard let target = firstValue(named: endpointNames, in: allItems) else {
throw ConnectionDetailsError.invalidAddress
}
return ConnectionDetails(
endpoint: try normalizedEndpoint(target),
pairingCode: normalizedCode(token)
)
}
guard ["http", "https", "ws", "wss"].contains(scheme) else {
throw ConnectionDetailsError.unsupportedScheme
}
let advertisedHost = firstValue(named: endpointNames, in: queryItems)
return ConnectionDetails(
endpoint: try normalizedEndpoint(advertisedHost ?? input),
pairingCode: normalizedCode(token)
)
}
private static func firstValue(named names: [String], in items: [URLQueryItem]) -> String? {
items.first { item in
names.contains { $0.caseInsensitiveCompare(item.name) == .orderedSame }
}?.value
}
private static func normalizedCode(_ input: String?) -> String? {
let value = input?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return value.isEmpty ? nil : value
}
private static func firstURL(in input: String) -> String? {
guard let expression = try? NSRegularExpression(
pattern: #"(?i)(?:(?:https?|wss?|t3)://|t3code:(?://)?)[^\s<>"']+"#
) else {
return nil
}
let range = NSRange(input.startIndex..., in: input)
guard let match = expression.firstMatch(in: input, range: range),
let swiftRange = Range(match.range, in: input)
else {
return nil
}
return String(input[swiftRange])
}
private static func bracketBareIPv6(_ value: String) -> String {
guard value.contains(":"),
!value.hasPrefix("["),
value.filter({ $0 == ":" }).count > 1
else {
return value
}
return "[\(value)]"
}
}
enum EndpointNetworkScope {
static func isLocal(_ endpoint: String) -> Bool {
guard let host = URLComponents(string: endpoint)?.host else { return false }
return isLocalHost(host)
}
static func isLocalHost(_ rawHost: String) -> Bool {
let host = hostWithoutPort(rawHost).lowercased()
if host == "localhost" || host.hasSuffix(".local") || host == "::1" {
return true
}
let octets = host.split(separator: ".").compactMap { Int($0) }
if octets.count == 4, octets.allSatisfy({ 0 ... 255 ~= $0 }) {
return octets[0] == 10
|| octets[0] == 127
|| (octets[0] == 169 && octets[1] == 254)
|| (octets[0] == 172 && 16 ... 31 ~= octets[1])
|| (octets[0] == 192 && octets[1] == 168)
}
guard host.contains(":"),
let firstHextetText = host.split(separator: ":", omittingEmptySubsequences: true).first,
let firstHextet = UInt16(firstHextetText, radix: 16)
else {
return false
}
return firstHextet & 0xffc0 == 0xfe80
|| firstHextet & 0xfe00 == 0xfc00
}
private static func hostWithoutPort(_ rawHost: String) -> String {
let value = rawHost.trimmingCharacters(in: .whitespacesAndNewlines)
if value.hasPrefix("["),
let closingBracket = value.firstIndex(of: "]") {
return String(value[value.index(after: value.startIndex) ..< closingBracket])
}
if value.filter({ $0 == ":" }).count == 1,
let colon = value.lastIndex(of: ":"),
value[value.index(after: colon)...].allSatisfy(\.isNumber) {
return String(value[..<colon])
}
return value
}
}
enum ConnectionErrorCopy {
static func message(for rawMessage: String?) -> String {
let message = rawMessage?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased() ?? ""
if message.isEmpty || message == "cancelled" || message == "canceled" {
return "The connection stopped before it finished. Make sure T3 Code is running, then try again."
}
if message.contains("expired") || message.contains("invalid_credential")
|| message.contains("invalid credential") || message.contains("401") {
return "That pairing code is invalid or has expired. Create a new code on the host and try again."
}
if message.contains("timed out") || message.contains("timeout") {
return "The server took too long to respond. Check the address and that both devices are online."
}
if message.contains("offline") || message.contains("network")
|| message.contains("could not connect") || message.contains("not connected") {
return "This iPhone could not reach the server. Check the address and network, then try again."
}
return "T3 Code could not complete pairing. Check the server address and use a fresh pairing code."
}
}
@@ -1,160 +1,612 @@
import SwiftUI
import UIKit
public struct ConnectionOnboardingView: View {
@Bindable var model: FeatureRootModel
@State private var endpoint = ""
@State private var pairingToken = ""
@State private var isPairing = false
@SwiftUI.Environment(\.scenePhase) private var scenePhase
@Bindable private var model: FeatureRootModel
public init(model: FeatureRootModel) {
private let readinessChecker: any ConnectionReadinessChecking
private let onConnected: @MainActor () -> Void
private let onCancel: (@MainActor () -> Void)?
@State private var stage = ConnectionStage.welcome
@State private var endpoint = ""
@State private var pairingCode = ""
@State private var errorMessage: String?
@State private var showsPermissionAction = false
@State private var showingScanner = false
@State private var entryHeading = "Connect manually"
@FocusState private var focusedField: ConnectionField?
public init(
model: FeatureRootModel,
onConnected: @escaping @MainActor () -> Void = {},
onCancel: (@MainActor () -> Void)? = nil
) {
self.model = model
readinessChecker = LocalNetworkAccessChecker()
self.onConnected = onConnected
self.onCancel = onCancel
}
init(
model: FeatureRootModel,
readinessChecker: any ConnectionReadinessChecking,
onConnected: @escaping @MainActor () -> Void = {},
onCancel: (@MainActor () -> Void)? = nil
) {
self.model = model
self.readinessChecker = readinessChecker
self.onConnected = onConnected
self.onCancel = onCancel
}
public var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 28) {
VStack(alignment: .leading, spacing: 8) {
Image(systemName: "chevron.left.forwardslash.chevron.right")
.font(.system(size: 34, weight: .bold))
Text("T3 Code")
.font(.largeTitle.bold())
Text("Connect this iPhone to a T3 environment.")
.font(.body)
.foregroundStyle(.secondary)
Group {
switch stage {
case .welcome:
welcomeView
case .details:
detailsView
case .checking, .connecting:
progressView
case .success:
successView
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.animation(.snappy(duration: 0.24), value: stage)
}
.preferredColorScheme(.dark)
.toolbar {
if stage == .welcome, let onCancel {
ToolbarItem(placement: .cancellationAction) {
Button("Close", action: onCancel)
}
}
}
.fullScreenCover(isPresented: $showingScanner) {
QRCodeScannerView(
onScan: { value in
showingScanner = false
applyConnectionString(
value,
heading: "Confirm connection",
connectAutomatically: true
)
},
onCancel: {
showingScanner = false
},
onPaste: {
showingScanner = false
pasteConnectionLink()
}
)
}
.onOpenURL { url in
applyConnectionString(url.absoluteString, heading: "Confirm connection")
}
.onChange(of: scenePhase) { _, newPhase in
if newPhase == .active, showsPermissionAction {
showsPermissionAction = false
errorMessage = nil
}
}
}
private var welcomeView: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
Spacer(minLength: 48)
Text("T3")
.font(.system(size: 34, weight: .black, design: .rounded))
.foregroundStyle(Color(red: 0.02, green: 0.74, blue: 0.5))
.accessibilityLabel("T3 Code")
Text("Your agents,\nwherever you are.")
.font(.system(size: 38, weight: .bold, design: .default))
.tracking(-1.1)
.padding(.top, 24)
Text("Connect securely to T3 Code running on your computer.")
.font(.body)
.foregroundStyle(.secondary)
.padding(.top, 12)
Button {
showingScanner = true
} label: {
Label("Scan QR code", systemImage: "qrcode.viewfinder")
.frame(maxWidth: .infinity)
}
.buttonStyle(ConnectionPrimaryButtonStyle())
.padding(.top, 36)
.accessibilityHint("Opens the camera")
VStack(spacing: 0) {
connectionAction(
title: "Paste connection link",
subtitle: "Copy it from T3 Code on your computer",
systemImage: "doc.on.clipboard"
) {
pasteConnectionLink()
}
VStack(alignment: .leading, spacing: 12) {
Text("SERVER")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
Divider().overlay(Color.white.opacity(0.09))
TextField("https://your-server.example", text: $endpoint)
.textInputAutocapitalization(.never)
.keyboardType(.URL)
.autocorrectionDisabled()
.featureInput()
.accessibilityLabel("Server address")
SecureField("Pairing token (optional)", text: $pairingToken)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.featureInput()
Button {
pair()
} label: {
HStack {
if isPairing {
ProgressView().controlSize(.small)
}
Text(isPairing ? "Connecting…" : "Connect")
}
.frame(maxWidth: .infinity)
}
.buttonStyle(FeaturePrimaryButtonStyle())
.disabled(normalizedEndpoint == nil || isPairing)
}
if !model.snapshot.environments.isEmpty {
VStack(alignment: .leading, spacing: 8) {
Text("KNOWN ENVIRONMENTS")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
ForEach(model.snapshot.environments) { environment in
Button {
endpoint = environment.endpoint
} label: {
HStack(spacing: 12) {
Image(systemName: "server.rack")
.foregroundStyle(.secondary)
VStack(alignment: .leading, spacing: 2) {
Text(environment.name)
.foregroundStyle(.primary)
Text(environment.endpoint)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
Spacer()
Image(systemName: "chevron.right")
.font(.caption)
.foregroundStyle(.tertiary)
}
.contentShape(Rectangle())
.padding(.vertical, 8)
}
.buttonStyle(.plain)
}
}
}
VStack(alignment: .leading, spacing: 6) {
Label("How to pair", systemImage: "info.circle")
.font(.subheadline.weight(.semibold))
Text("Open T3 Code on the host, copy its mobile pairing link, then paste the server and one-time token above.")
.font(.footnote)
.foregroundStyle(.secondary)
connectionAction(
title: "Enter details manually",
subtitle: "Use the server address and pairing code",
systemImage: "keyboard"
) {
entryHeading = "Connect manually"
errorMessage = nil
stage = .details
}
}
.padding(.top, 12)
knownEnvironments
}
.padding(.horizontal, 24)
.padding(.bottom, 40)
.frame(maxWidth: 520)
.frame(maxWidth: .infinity)
}
.scrollDismissesKeyboard(.interactively)
}
@ViewBuilder
private var knownEnvironments: some View {
if !model.snapshot.environments.isEmpty {
VStack(alignment: .leading, spacing: 0) {
Text("KNOWN SERVERS")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
.padding(.top, 34)
.padding(.bottom, 8)
ForEach(model.snapshot.environments) { environment in
Button {
connect(
.activate(
id: environment.id,
endpoint: environment.endpoint
)
)
} label: {
HStack(spacing: 12) {
Image(systemName: "desktopcomputer")
.font(.body)
.foregroundStyle(.secondary)
.frame(width: 24)
VStack(alignment: .leading, spacing: 2) {
Text(environment.name)
.foregroundStyle(.primary)
Text(environment.endpoint)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
Spacer()
Image(systemName: "arrow.right")
.font(.caption.weight(.semibold))
.foregroundStyle(.tertiary)
}
.contentShape(Rectangle())
.padding(.vertical, 12)
}
.buttonStyle(.plain)
.accessibilityHint("Reconnects to this server")
if environment.id != model.snapshot.environments.last?.id {
Divider().overlay(Color.white.opacity(0.09))
}
}
.padding(24)
.frame(maxWidth: 560)
.frame(maxWidth: .infinity)
}
.scrollDismissesKeyboard(.interactively)
.background(Color.black)
.navigationTitle("Connect")
.navigationBarTitleDisplayMode(.inline)
}
}
private var normalizedEndpoint: String? {
let value = endpoint.trimmingCharacters(in: .whitespacesAndNewlines)
guard let components = URLComponents(string: value),
let scheme = components.scheme?.lowercased(),
["http", "https"].contains(scheme),
components.host != nil else {
return nil
private var detailsView: some View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
VStack(alignment: .leading, spacing: 8) {
Text(entryHeading)
.font(.largeTitle.bold())
.tracking(-0.6)
Text("Both values are shown in T3 Code when you create a mobile connection.")
.font(.subheadline)
.foregroundStyle(.secondary)
}
VStack(alignment: .leading, spacing: 8) {
Text("SERVER ADDRESS")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
TextField("http://192.168.1.5:3773", text: $endpoint)
.textInputAutocapitalization(.never)
.keyboardType(.URL)
.autocorrectionDisabled()
.focused($focusedField, equals: .endpoint)
.connectionInput()
.accessibilityLabel("Server address")
.onChange(of: endpoint) { _, value in
autofillIfPairingLink(value)
}
}
VStack(alignment: .leading, spacing: 8) {
Text("PAIRING CODE")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary)
TextField("12-character code", text: $pairingCode)
.textInputAutocapitalization(.never)
.textContentType(.oneTimeCode)
.autocorrectionDisabled()
.focused($focusedField, equals: .pairingCode)
.connectionInput()
.accessibilityLabel("Pairing code")
}
Button {
pasteConnectionLink()
} label: {
Label("Paste a connection link instead", systemImage: "doc.on.clipboard")
.font(.subheadline.weight(.semibold))
}
.buttonStyle(.plain)
if let errorMessage {
connectionError(message: errorMessage)
}
Button {
submitDetails()
} label: {
Text("Connect")
.frame(maxWidth: .infinity)
}
.buttonStyle(ConnectionPrimaryButtonStyle())
.disabled(!canSubmit)
.opacity(canSubmit ? 1 : 0.45)
}
.padding(.horizontal, 24)
.padding(.top, 24)
.padding(.bottom, 40)
.frame(maxWidth: 520)
.frame(maxWidth: .infinity)
}
.scrollDismissesKeyboard(.interactively)
.navigationTitle("Connect")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button {
errorMessage = nil
showsPermissionAction = false
focusedField = nil
stage = .welcome
} label: {
Label("Back", systemImage: "chevron.left")
}
}
}
return value
}
private func pair() {
guard let endpoint = normalizedEndpoint else { return }
let trimmedToken = pairingToken.trimmingCharacters(in: .whitespacesAndNewlines)
isPairing = true
Task {
_ = await model.pair(
endpoint: endpoint,
token: trimmedToken.isEmpty ? nil : trimmedToken
private var progressView: some View {
VStack(alignment: .leading, spacing: 34) {
Spacer()
Text(stage == .checking ? "Finding your T3" : "Connecting securely")
.font(.largeTitle.bold())
.tracking(-0.7)
VStack(alignment: .leading, spacing: 20) {
progressRow(
title: "Server details",
state: .complete
)
progressRow(
title: EndpointNetworkScope.isLocal(endpoint)
? "Local network access"
: "Network access",
state: stage == .checking ? .active : .complete
)
progressRow(
title: "Secure pairing",
state: stage == .connecting ? .active : .waiting
)
}
Spacer()
Text("Keep T3 Code open on your computer.")
.font(.footnote)
.foregroundStyle(.secondary)
}
.padding(.horizontal, 32)
.padding(.vertical, 28)
.frame(maxWidth: 520)
.accessibilityElement(children: .contain)
}
private var successView: some View {
VStack(spacing: 18) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 54))
.foregroundStyle(.green)
Text("You're connected")
.font(.title.bold())
Text("Loading your projects and threads.")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.accessibilityElement(children: .combine)
}
private func connectionAction(
title: String,
subtitle: String,
systemImage: String,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
HStack(spacing: 14) {
Image(systemName: systemImage)
.font(.system(size: 18, weight: .medium))
.frame(width: 28)
VStack(alignment: .leading, spacing: 3) {
Text(title)
.font(.body.weight(.semibold))
Text(subtitle)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Image(systemName: "chevron.right")
.font(.caption.weight(.semibold))
.foregroundStyle(.tertiary)
}
.foregroundStyle(.primary)
.contentShape(Rectangle())
.padding(.vertical, 14)
}
.buttonStyle(.plain)
}
private func connectionError(message: String) -> some View {
VStack(alignment: .leading, spacing: 10) {
Label(message, systemImage: showsPermissionAction ? "network.slash" : "exclamationmark.circle")
.font(.subheadline)
.foregroundStyle(Color(red: 1, green: 0.58, blue: 0.2))
if showsPermissionAction {
Button("Open Settings") {
guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(url)
}
.font(.subheadline.weight(.semibold))
}
}
.accessibilityElement(children: .combine)
}
private func progressRow(title: String, state: ProgressRowState) -> some View {
HStack(spacing: 14) {
Group {
switch state {
case .complete:
Image(systemName: "checkmark.circle.fill")
.foregroundStyle(.green)
case .active:
ProgressView()
.controlSize(.small)
case .waiting:
Image(systemName: "circle")
.foregroundStyle(.tertiary)
}
}
.frame(width: 22)
Text(title)
.font(.body.weight(state == .active ? .semibold : .regular))
.foregroundStyle(state == .waiting ? .secondary : .primary)
}
}
private var canSubmit: Bool {
!endpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
&& !pairingCode.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
@MainActor
private func submitDetails() {
do {
let normalized = try ConnectionDetailsParser.normalizedEndpoint(endpoint)
endpoint = normalized
errorMessage = nil
showsPermissionAction = false
focusedField = nil
connect(
.pair(
endpoint: normalized,
code: pairingCode.trimmingCharacters(in: .whitespacesAndNewlines)
)
)
isPairing = false
} catch {
errorMessage = error.localizedDescription
}
}
@MainActor
private func pasteConnectionLink() {
guard let value = UIPasteboard.general.string, !value.isEmpty else {
entryHeading = "Connect manually"
stage = .details
errorMessage = "Copy a T3 pairing link first, or enter the details below."
focusedField = .endpoint
return
}
applyConnectionString(value, heading: "Confirm connection")
}
@MainActor
private func applyConnectionString(
_ value: String,
heading: String,
connectAutomatically: Bool = false
) {
do {
let details = try ConnectionDetailsParser.parse(value)
endpoint = details.endpoint
if let code = details.pairingCode {
pairingCode = code
}
entryHeading = heading
errorMessage = details.pairingCode == nil
? "The link did not include a pairing code. Enter it below."
: nil
showsPermissionAction = false
if connectAutomatically, let code = details.pairingCode {
focusedField = nil
connect(.pair(endpoint: details.endpoint, code: code))
} else {
stage = .details
focusedField = details.pairingCode == nil ? .pairingCode : nil
}
} catch {
entryHeading = "Connect manually"
errorMessage = error.localizedDescription
stage = .details
focusedField = .endpoint
}
}
@MainActor
private func autofillIfPairingLink(_ value: String) {
let lowered = value.lowercased()
guard lowered.contains("token=")
|| lowered.hasPrefix("t3:")
|| lowered.hasPrefix("t3code:")
|| lowered.contains("pairingurl=")
|| lowered.contains("pairing_url="),
let details = try? ConnectionDetailsParser.parse(value),
let code = details.pairingCode
else {
return
}
endpoint = details.endpoint
pairingCode = code
errorMessage = nil
focusedField = nil
}
@MainActor
private func connect(_ action: ConnectionAction) {
endpoint = action.endpoint
errorMessage = nil
showsPermissionAction = false
stage = .checking
Task {
let readiness = await readinessChecker.check(endpoint: action.endpoint)
switch readiness {
case .ready:
stage = .connecting
case .localNetworkDenied:
errorMessage = "Allow Local Network access so this iPhone can find T3 Code on your computer."
showsPermissionAction = true
stage = .details
return
case .unreachable:
errorMessage = "This iPhone cannot reach that server. Confirm the address and that both devices are on the same network."
stage = .details
return
}
model.errorMessage = nil
let didConnect: Bool
switch action {
case let .pair(endpoint, code):
didConnect = await model.pair(endpoint: endpoint, token: code)
case let .activate(id, _):
await model.activateEnvironment(id)
didConnect = model.snapshot.connection.state == .connected
}
if didConnect {
stage = .success
onConnected()
} else {
let rawError = model.errorMessage
model.errorMessage = nil
errorMessage = ConnectionErrorCopy.message(for: rawError)
stage = .details
}
}
}
}
private enum ConnectionStage: Equatable {
case welcome
case details
case checking
case connecting
case success
}
private enum ConnectionField: Hashable {
case endpoint
case pairingCode
}
private enum ProgressRowState {
case complete
case active
case waiting
}
private enum ConnectionAction {
case pair(endpoint: String, code: String)
case activate(id: String, endpoint: String)
var endpoint: String {
switch self {
case let .pair(endpoint, _), let .activate(_, endpoint):
endpoint
}
}
}
private extension View {
func featureInput() -> some View {
func connectionInput() -> some View {
self
.padding(.horizontal, 12)
.frame(minHeight: 46)
.background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 10))
.overlay {
RoundedRectangle(cornerRadius: 10)
.stroke(Color.white.opacity(0.12), lineWidth: 1)
.font(.body.monospaced())
.padding(.horizontal, 14)
.frame(minHeight: 50)
.background(Color.white.opacity(0.07))
.overlay(alignment: .bottom) {
Rectangle()
.fill(Color.white.opacity(0.18))
.frame(height: 1)
}
}
}
struct FeaturePrimaryButtonStyle: ButtonStyle {
private struct ConnectionPrimaryButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.body.weight(.semibold))
.foregroundStyle(.black)
.padding(.horizontal, 16)
.frame(minHeight: 46)
.background(configuration.isPressed ? Color.white.opacity(0.75) : .white)
.clipShape(RoundedRectangle(cornerRadius: 10))
.frame(minHeight: 52)
.background(configuration.isPressed ? Color.white.opacity(0.76) : .white)
.clipShape(RoundedRectangle(cornerRadius: 12))
}
}
@@ -0,0 +1,112 @@
import Foundation
import Network
enum ConnectionReadiness: Equatable, Sendable {
case ready
case localNetworkDenied
case unreachable
}
protocol ConnectionReadinessChecking: Sendable {
func check(endpoint: String) async -> ConnectionReadiness
}
struct LocalNetworkAccessChecker: ConnectionReadinessChecking {
func check(endpoint: String) async -> ConnectionReadiness {
guard EndpointNetworkScope.isLocal(endpoint) else { return .ready }
guard let components = URLComponents(string: endpoint),
let hostname = components.host
else {
return .unreachable
}
let portNumber = components.port
?? (components.scheme?.lowercased() == "https" ? 443 : 80)
guard
let rawPort = UInt16(exactly: portNumber),
let port = NWEndpoint.Port(rawValue: rawPort)
else {
return .unreachable
}
return await withCheckedContinuation { continuation in
let connection = NWConnection(
host: NWEndpoint.Host(hostname),
port: port,
using: .tcp
)
let completion = ConnectionProbeCompletion(
connection: connection,
continuation: continuation
)
connection.stateUpdateHandler = { state in
switch state {
case .ready:
completion.finish(.ready)
case .waiting(let error), .failed(let error):
if connection.currentPath?.unsatisfiedReason == .localNetworkDenied
|| error.indicatesPermissionDenied {
completion.finish(.localNetworkDenied)
} else if case .failed = state {
completion.finish(.unreachable)
}
case .cancelled:
completion.finish(.unreachable)
default:
break
}
}
connection.start(queue: .global(qos: .userInitiated))
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 6) {
if connection.currentPath?.unsatisfiedReason == .localNetworkDenied {
completion.finish(.localNetworkDenied)
} else {
completion.finish(.unreachable)
}
}
}
}
}
private final class ConnectionProbeCompletion: @unchecked Sendable {
private let lock = NSLock()
private var didFinish = false
private let connection: NWConnection
private var continuation: CheckedContinuation<ConnectionReadiness, Never>?
init(
connection: NWConnection,
continuation: CheckedContinuation<ConnectionReadiness, Never>
) {
self.connection = connection
self.continuation = continuation
}
func finish(_ result: ConnectionReadiness) {
lock.lock()
guard !didFinish else {
lock.unlock()
return
}
didFinish = true
let continuation = continuation
self.continuation = nil
lock.unlock()
connection.stateUpdateHandler = nil
connection.cancel()
continuation?.resume(returning: result)
}
}
private extension NWError {
var indicatesPermissionDenied: Bool {
switch self {
case .posix(.EACCES), .posix(.EPERM):
true
default:
false
}
}
}
@@ -0,0 +1,296 @@
@preconcurrency import AVFoundation
import SwiftUI
import UIKit
struct QRCodeScannerView: View {
let onScan: (String) -> Void
let onCancel: () -> Void
let onPaste: () -> Void
@State private var availability: QRScannerAvailability = .checking
var body: some View {
ZStack {
Color.black.ignoresSafeArea()
QRScannerCameraView(
availability: $availability,
onScan: onScan
)
.ignoresSafeArea()
LinearGradient(
colors: [.black.opacity(0.7), .clear, .black.opacity(0.8)],
startPoint: .top,
endPoint: .bottom
)
.ignoresSafeArea()
.allowsHitTesting(false)
VStack(spacing: 0) {
HStack {
Button("Cancel", action: onCancel)
.font(.body.weight(.semibold))
Spacer()
Text("Scan QR code")
.font(.headline)
Spacer()
Button("Cancel", action: onCancel)
.hidden()
}
.padding(.horizontal, 20)
.frame(height: 56)
Spacer()
if availability == .ready {
scannerFrame
Text("Point your camera at the QR code shown by T3 Code.")
.font(.subheadline)
.foregroundStyle(.white.opacity(0.72))
.multilineTextAlignment(.center)
.padding(.top, 28)
} else {
unavailableContent
}
Spacer()
Button {
onPaste()
} label: {
Label("Paste connection link", systemImage: "doc.on.clipboard")
.font(.body.weight(.semibold))
.frame(maxWidth: .infinity)
.frame(minHeight: 50)
}
.buttonStyle(.bordered)
.tint(.white)
.padding(.horizontal, 28)
.padding(.bottom, 24)
}
}
.preferredColorScheme(.dark)
}
private var scannerFrame: some View {
RoundedRectangle(cornerRadius: 24)
.stroke(Color.white.opacity(0.9), lineWidth: 3)
.frame(width: 252, height: 252)
.overlay(alignment: .topLeading) {
Image(systemName: "viewfinder")
.resizable()
.frame(width: 282, height: 282)
.offset(x: -15, y: -15)
.foregroundStyle(.white)
}
.accessibilityHidden(true)
}
@ViewBuilder
private var unavailableContent: some View {
switch availability {
case .checking:
ProgressView()
.controlSize(.large)
.accessibilityLabel("Checking camera")
case .ready:
EmptyView()
case .denied:
VStack(spacing: 14) {
Image(systemName: "camera.fill")
.font(.system(size: 34))
Text("Camera access is off")
.font(.title3.bold())
Text("Allow camera access in Settings to scan a pairing code.")
.font(.subheadline)
.foregroundStyle(.white.opacity(0.65))
.multilineTextAlignment(.center)
Button("Open Settings") {
guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(url)
}
.buttonStyle(.borderedProminent)
.tint(.white)
.foregroundStyle(.black)
}
.padding(.horizontal, 36)
case .unavailable:
VStack(spacing: 14) {
Image(systemName: "camera.slash.fill")
.font(.system(size: 34))
Text("Camera unavailable")
.font(.title3.bold())
Text("Paste the connection link instead.")
.font(.subheadline)
.foregroundStyle(.white.opacity(0.65))
}
}
}
}
private enum QRScannerAvailability: Equatable {
case checking
case ready
case denied
case unavailable
}
private struct QRScannerCameraView: UIViewControllerRepresentable {
@Binding var availability: QRScannerAvailability
let onScan: (String) -> Void
func makeCoordinator() -> Coordinator {
Coordinator(availability: $availability, onScan: onScan)
}
func makeUIViewController(context: Context) -> QRScannerViewController {
let controller = QRScannerViewController()
context.coordinator.attach(to: controller)
return controller
}
func updateUIViewController(_ controller: QRScannerViewController, context: Context) {}
static func dismantleUIViewController(
_ controller: QRScannerViewController,
coordinator: Coordinator
) {
controller.stop()
}
@MainActor
final class Coordinator: NSObject, AVCaptureMetadataOutputObjectsDelegate {
private var availability: Binding<QRScannerAvailability>
private let onScan: (String) -> Void
private weak var controller: QRScannerViewController?
private var didScan = false
init(
availability: Binding<QRScannerAvailability>,
onScan: @escaping (String) -> Void
) {
self.availability = availability
self.onScan = onScan
}
func attach(to controller: QRScannerViewController) {
self.controller = controller
controller.prepare(delegate: self) { [weak self] nextAvailability in
self?.availability.wrappedValue = nextAvailability
}
}
nonisolated func metadataOutput(
_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection
) {
guard let value = (metadataObjects.first as? AVMetadataMachineReadableCodeObject)?
.stringValue
else {
return
}
Task { @MainActor [weak self] in
guard let self, !didScan else { return }
didScan = true
controller?.stop()
UINotificationFeedbackGenerator().notificationOccurred(.success)
onScan(value)
}
}
}
}
@MainActor
private final class QRScannerViewController: UIViewController {
private let captureSession = AVCaptureSession()
private let sessionQueue = DispatchQueue(label: "codes.t3.swift-ios.qr-scanner")
private var previewLayer: AVCaptureVideoPreviewLayer?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer?.frame = view.bounds
}
func prepare(
delegate: AVCaptureMetadataOutputObjectsDelegate,
availabilityChanged: @escaping (QRScannerAvailability) -> Void
) {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
configure(delegate: delegate, availabilityChanged: availabilityChanged)
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
Task { @MainActor in
guard let self else { return }
if granted {
self.configure(
delegate: delegate,
availabilityChanged: availabilityChanged
)
} else {
availabilityChanged(.denied)
}
}
}
case .denied, .restricted:
availabilityChanged(.denied)
@unknown default:
availabilityChanged(.unavailable)
}
}
func stop() {
let session = captureSession
sessionQueue.async {
if session.isRunning {
session.stopRunning()
}
}
}
private func configure(
delegate: AVCaptureMetadataOutputObjectsDelegate,
availabilityChanged: @escaping (QRScannerAvailability) -> Void
) {
guard let camera = AVCaptureDevice.default(for: .video),
let input = try? AVCaptureDeviceInput(device: camera),
captureSession.canAddInput(input)
else {
availabilityChanged(.unavailable)
return
}
let output = AVCaptureMetadataOutput()
guard captureSession.canAddOutput(output) else {
availabilityChanged(.unavailable)
return
}
captureSession.beginConfiguration()
captureSession.sessionPreset = .high
captureSession.addInput(input)
captureSession.addOutput(output)
output.setMetadataObjectsDelegate(delegate, queue: .main)
output.metadataObjectTypes = [.qr]
captureSession.commitConfiguration()
let preview = AVCaptureVideoPreviewLayer(session: captureSession)
preview.videoGravity = .resizeAspectFill
preview.frame = view.bounds
view.layer.insertSublayer(preview, at: 0)
previewLayer = preview
availabilityChanged(.ready)
let session = captureSession
sessionQueue.async {
session.startRunning()
}
}
}
@@ -0,0 +1,253 @@
import SwiftUI
public struct DevicesView: View {
private let manager: any FeatureDeviceManaging
@State private var sessions: [FeatureDeviceSession] = []
@State private var isLoading = true
@State private var isRevoking = false
@State private var errorMessage: String?
@State private var revokeTarget: FeatureDeviceSession?
@State private var showingRevokeOthers = false
public init(manager: any FeatureDeviceManaging) {
self.manager = manager
}
public var body: some View {
Group {
if isLoading, sessions.isEmpty {
VStack(spacing: 12) {
ProgressView()
Text("Loading devices")
.font(.footnote)
.foregroundStyle(.secondary)
}
} else if sessions.isEmpty {
ContentUnavailableView {
Label("No devices found", systemImage: "laptopcomputer.and.iphone")
} description: {
Text("Device sessions will appear here when this server supports access management.")
}
} else {
deviceList
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black)
.navigationTitle("Devices")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
if !otherSessions.isEmpty {
ToolbarItem(placement: .primaryAction) {
Menu {
Button(role: .destructive) {
showingRevokeOthers = true
} label: {
Label("Remove all other devices", systemImage: "rectangle.stack.badge.minus")
}
} label: {
Image(systemName: "ellipsis.circle")
}
.disabled(isRevoking)
.accessibilityLabel("Device actions")
}
}
}
.task {
await reload()
}
.alert(
"Remove this device?",
isPresented: Binding(
get: { revokeTarget != nil },
set: { if !$0 { revokeTarget = nil } }
),
presenting: revokeTarget
) { device in
Button("Remove access", role: .destructive) {
Task { await revoke(device) }
}
Button("Cancel", role: .cancel) {}
} message: { device in
Text("\(device.displayName) will need a new pairing code to reconnect.")
}
.confirmationDialog(
"Remove all other devices?",
isPresented: $showingRevokeOthers,
titleVisibility: .visible
) {
Button("Remove \(otherSessions.count) devices", role: .destructive) {
Task { await revokeOthers() }
}
Button("Cancel", role: .cancel) {}
} message: {
Text("Every other phone, tablet, browser, and desktop will be signed out.")
}
}
private var deviceList: some View {
List {
if let currentSession {
Section("THIS DEVICE") {
DeviceSessionRow(session: currentSession)
}
}
if !otherSessions.isEmpty {
Section("OTHER DEVICES") {
ForEach(otherSessions) { session in
DeviceSessionRow(session: session)
.contentShape(Rectangle())
.swipeActions {
Button("Remove", role: .destructive) {
revokeTarget = session
}
}
.contextMenu {
Button(role: .destructive) {
revokeTarget = session
} label: {
Label("Remove access", systemImage: "trash")
}
}
}
}
}
if let errorMessage {
Section {
VStack(alignment: .leading, spacing: 10) {
Label(errorMessage, systemImage: "exclamationmark.circle")
.font(.subheadline)
.foregroundStyle(.orange)
Button("Try again") {
Task { await reload() }
}
.font(.subheadline.weight(.semibold))
}
.padding(.vertical, 4)
}
}
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
.background(Color.black)
.refreshable {
await reload()
}
.overlay(alignment: .top) {
if isRevoking {
ProgressView()
.padding(.top, 12)
.accessibilityLabel("Updating device access")
}
}
}
private var currentSession: FeatureDeviceSession? {
sessions.first(where: \.isCurrent)
}
private var otherSessions: [FeatureDeviceSession] {
sessions.filter { !$0.isCurrent }
}
@MainActor
private func reload() async {
isLoading = true
defer { isLoading = false }
do {
sessions = FeatureDeviceSession.sortedForDisplay(
try await manager.loadDeviceSessions()
)
errorMessage = nil
} catch {
errorMessage = DeviceManagementErrorCopy.message(for: error)
}
}
@MainActor
private func revoke(_ session: FeatureDeviceSession) async {
isRevoking = true
defer {
isRevoking = false
revokeTarget = nil
}
do {
try await manager.revokeDeviceSession(id: session.id)
sessions.removeAll { $0.id == session.id }
errorMessage = nil
} catch {
errorMessage = DeviceManagementErrorCopy.message(for: error)
}
}
@MainActor
private func revokeOthers() async {
isRevoking = true
defer { isRevoking = false }
do {
try await manager.revokeOtherDeviceSessions()
sessions.removeAll { !$0.isCurrent }
errorMessage = nil
} catch {
errorMessage = DeviceManagementErrorCopy.message(for: error)
}
}
}
private struct DeviceSessionRow: View {
let session: FeatureDeviceSession
var body: some View {
HStack(alignment: .top, spacing: 13) {
Image(systemName: session.deviceType.systemImage)
.font(.system(size: 19, weight: .medium))
.foregroundStyle(session.isCurrent ? .green : .secondary)
.frame(width: 26, height: 26)
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
Text(session.displayName)
.font(.body.weight(.semibold))
if session.isCurrent {
Text("Current")
.font(.caption)
.foregroundStyle(.green)
} else if session.isConnected {
Text("Online")
.font(.caption)
.foregroundStyle(.green)
}
}
if !session.platformDescription.isEmpty {
Text(session.platformDescription)
.font(.caption)
.foregroundStyle(.secondary)
}
Text(lastSeenDescription)
.font(.caption)
.foregroundStyle(.tertiary)
if let ipAddress = session.ipAddress, !ipAddress.isEmpty {
Text(ipAddress)
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
}
}
Spacer(minLength: 8)
}
.padding(.vertical, 6)
.accessibilityElement(children: .combine)
}
private var lastSeenDescription: String {
if session.isConnected {
return "Active now"
}
return "Last seen \(session.lastSeenAt.formatted(.relative(presentation: .named)))"
}
}
@@ -0,0 +1,141 @@
import Foundation
public enum FeatureDeviceType: String, Sendable, Equatable, Codable {
case desktop
case mobile
case tablet
case bot
case unknown
var displayName: String {
switch self {
case .desktop: "Desktop"
case .mobile: "Phone"
case .tablet: "Tablet"
case .bot: "Automation"
case .unknown: "Device"
}
}
var systemImage: String {
switch self {
case .desktop: "desktopcomputer"
case .mobile: "iphone"
case .tablet: "ipad"
case .bot: "gearshape.2"
case .unknown: "network"
}
}
}
public struct FeatureDeviceSession: Identifiable, Sendable, Equatable, Codable {
public var id: String { sessionID }
public let sessionID: String
public var label: String?
public var deviceType: FeatureDeviceType
public var operatingSystem: String?
public var browser: String?
public var ipAddress: String?
public var issuedAt: Date
public var expiresAt: Date
public var lastConnectedAt: Date?
public var isConnected: Bool
public var isCurrent: Bool
public init(
sessionID: String,
label: String? = nil,
deviceType: FeatureDeviceType = .unknown,
operatingSystem: String? = nil,
browser: String? = nil,
ipAddress: String? = nil,
issuedAt: Date,
expiresAt: Date,
lastConnectedAt: Date? = nil,
isConnected: Bool = false,
isCurrent: Bool = false
) {
self.sessionID = sessionID
self.label = label
self.deviceType = deviceType
self.operatingSystem = operatingSystem
self.browser = browser
self.ipAddress = ipAddress
self.issuedAt = issuedAt
self.expiresAt = expiresAt
self.lastConnectedAt = lastConnectedAt
self.isConnected = isConnected
self.isCurrent = isCurrent
}
var displayName: String {
let value = label?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !value.isEmpty {
return value
}
return isCurrent ? "This device" : deviceType.displayName
}
var platformDescription: String {
[operatingSystem, browser]
.compactMap { value in
let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return trimmed.isEmpty ? nil : trimmed
}
.joined(separator: " · ")
}
var lastSeenAt: Date {
lastConnectedAt ?? issuedAt
}
static func sortedForDisplay(_ sessions: [Self]) -> [Self] {
sessions.sorted { left, right in
if left.isCurrent != right.isCurrent {
return left.isCurrent
}
if left.isConnected != right.isConnected {
return left.isConnected
}
return left.lastSeenAt > right.lastSeenAt
}
}
}
/// The app adapter can opt into access management without making it a requirement
/// for environments that do not grant the access:read/access:write scopes.
@MainActor
public protocol FeatureDeviceManaging: AnyObject {
func loadDeviceSessions() async throws -> [FeatureDeviceSession]
func revokeDeviceSession(id: String) async throws
func revokeOtherDeviceSessions() async throws
}
@MainActor
final class EmptyFeatureDeviceManager: FeatureDeviceManaging {
static let shared = EmptyFeatureDeviceManager()
private init() {}
func loadDeviceSessions() async throws -> [FeatureDeviceSession] {
[]
}
func revokeDeviceSession(id: String) async throws {}
func revokeOtherDeviceSessions() async throws {}
}
enum DeviceManagementErrorCopy {
static func message(for error: Error) -> String {
let value = error.localizedDescription.lowercased()
if value.contains("scope") || value.contains("403") || value.contains("forbidden") {
return "This connection does not have permission to manage devices."
}
if value.contains("offline") || value.contains("network")
|| value.contains("not connected") || value.contains("timed out") {
return "Device access could not be updated. Check your connection and try again."
}
return "Device access could not be updated. Try again in a moment."
}
}
@@ -2,10 +2,12 @@ import SwiftUI
public struct SettingsView: View {
@SwiftUI.Environment(\.dismiss) private var dismiss
@Bindable var model: FeatureRootModel
@Bindable private var model: FeatureRootModel
@State private var settings: FeatureSettings
@State private var isSaving = false
@State private var showingDisconnect = false
@State private var showingAddEnvironment = false
@State private var removalTarget: FeatureEnvironment?
public init(model: FeatureRootModel) {
self.model = model
@@ -15,86 +17,10 @@ public struct SettingsView: View {
public var body: some View {
NavigationStack {
Form {
Section("Appearance") {
Picker("Theme", selection: $settings.appearance) {
Text("System").tag(FeatureAppearance.system)
Text("Dark").tag(FeatureAppearance.dark)
}
Toggle("Haptics", isOn: $settings.hapticsEnabled)
Toggle("Notifications", isOn: $settings.notificationsEnabled)
}
Section("Default agent") {
ProviderModelPicker(
providers: model.snapshot.providers,
selection: $settings.defaultSelection
)
if let provider = selectedProvider, let selectedModel {
LabeledContent("Provider", value: provider.name)
if let detail = selectedModel.detail {
Text(detail)
.font(.footnote)
.foregroundStyle(.secondary)
}
}
}
Section("Environment") {
LabeledContent(
"Status",
value: model.snapshot.connection.state == .connected ? "Connected" : "Offline"
)
if let endpoint = model.snapshot.connection.endpoint {
LabeledContent("Server") {
Text(endpoint)
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
ForEach(model.snapshot.environments) { environment in
Button {
Task { await model.activateEnvironment(environment.id) }
} label: {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(environment.name)
.foregroundStyle(.primary)
Text(environment.endpoint)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
if environment.isActive {
Image(systemName: "checkmark.circle.fill")
.foregroundStyle(.green)
}
}
}
.swipeActions {
Button(role: .destructive) {
Task { await model.removeEnvironment(environment.id) }
} label: {
Label("Remove", systemImage: "trash")
}
}
.contextMenu {
Button(role: .destructive) {
Task { await model.removeEnvironment(environment.id) }
} label: {
Label("Remove Environment", systemImage: "trash")
}
}
}
Button("Disconnect", role: .destructive) {
showingDisconnect = true
}
}
Section("About") {
LabeledContent("App", value: "T3 Code for iOS")
LabeledContent("Platform", value: "Native SwiftUI")
Link("Open source", destination: URL(string: "https://github.com/pingdotgg/t3code")!)
}
connectionSection
agentSection
preferencesSection
aboutSection
}
.scrollContentBackground(.hidden)
.background(Color.black)
@@ -112,7 +38,7 @@ public struct SettingsView: View {
}
}
.confirmationDialog(
"Disconnect from this environment?",
"Disconnect from this server?",
isPresented: $showingDisconnect,
titleVisibility: .visible
) {
@@ -123,10 +49,160 @@ public struct SettingsView: View {
}
}
Button("Cancel", role: .cancel) {}
} message: {
Text("Your saved server and credentials will stay on this iPhone.")
}
.alert(
"Remove saved server?",
isPresented: Binding(
get: { removalTarget != nil },
set: { if !$0 { removalTarget = nil } }
),
presenting: removalTarget
) { environment in
Button("Remove", role: .destructive) {
Task {
await model.removeEnvironment(environment.id)
removalTarget = nil
}
}
Button("Cancel", role: .cancel) {}
} message: { environment in
Text("\(environment.name) will need a new pairing code to be added again.")
}
.sheet(isPresented: $showingAddEnvironment) {
ConnectionOnboardingView(
model: model,
onConnected: {
showingAddEnvironment = false
},
onCancel: {
showingAddEnvironment = false
}
)
}
}
}
private var connectionSection: some View {
Section("Connections") {
HStack(spacing: 12) {
Image(systemName: connectionSymbol)
.foregroundStyle(connectionColor)
.frame(width: 22)
VStack(alignment: .leading, spacing: 2) {
Text(model.snapshot.connection.environmentName ?? "T3 server")
.font(.body.weight(.semibold))
Text(connectionDescription)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
Spacer()
Text(connectionStatus)
.font(.caption.weight(.semibold))
.foregroundStyle(connectionColor)
}
.accessibilityElement(children: .combine)
NavigationLink {
DevicesView(manager: deviceManager)
} label: {
Label("Devices and sessions", systemImage: "laptopcomputer.and.iphone")
}
ForEach(model.snapshot.environments) { environment in
Button {
guard !environment.isActive else { return }
Task { await model.activateEnvironment(environment.id) }
} label: {
HStack(spacing: 12) {
Image(systemName: "desktopcomputer")
.foregroundStyle(.secondary)
.frame(width: 22)
VStack(alignment: .leading, spacing: 2) {
Text(environment.name)
.foregroundStyle(.primary)
Text(environment.endpoint)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
Spacer()
if environment.isActive {
Image(systemName: "checkmark")
.font(.subheadline.weight(.bold))
.foregroundStyle(.green)
.accessibilityLabel("Active")
}
}
}
.swipeActions {
Button("Remove", role: .destructive) {
removalTarget = environment
}
}
.contextMenu {
Button(role: .destructive) {
removalTarget = environment
} label: {
Label("Remove saved server", systemImage: "trash")
}
}
}
Button {
showingAddEnvironment = true
} label: {
Label("Add another server", systemImage: "plus")
}
Button("Disconnect", role: .destructive) {
showingDisconnect = true
}
}
}
private var agentSection: some View {
Section("Default agent") {
ProviderModelPicker(
providers: model.snapshot.providers,
selection: $settings.defaultSelection
)
if let provider = selectedProvider, let selectedModel {
LabeledContent("Provider", value: provider.name)
if let detail = selectedModel.detail {
Text(detail)
.font(.footnote)
.foregroundStyle(.secondary)
}
}
}
}
private var preferencesSection: some View {
Section("Preferences") {
Picker("Theme", selection: $settings.appearance) {
Text("System").tag(FeatureAppearance.system)
Text("Dark").tag(FeatureAppearance.dark)
}
Toggle("Haptics", isOn: $settings.hapticsEnabled)
Toggle("Notifications", isOn: $settings.notificationsEnabled)
}
}
private var aboutSection: some View {
Section("About") {
LabeledContent("App", value: "T3 Code for iOS")
LabeledContent("Platform", value: "Native SwiftUI")
Link("Open source", destination: URL(string: "https://github.com/pingdotgg/t3code")!)
}
}
private var deviceManager: any FeatureDeviceManaging {
(model.client as? any FeatureDeviceManaging) ?? EmptyFeatureDeviceManager.shared
}
private var selectedProvider: FeatureProvider? {
guard let selection = settings.defaultSelection else { return nil }
return model.snapshot.providers.first { $0.id == selection.providerID }
@@ -137,6 +213,28 @@ public struct SettingsView: View {
return selectedProvider?.models.first { $0.id == selection.modelID }
}
private var connectionStatus: String {
switch model.snapshot.connection.state {
case .connected: "Online"
case .connecting: "Connecting"
case .reconnecting: "Reconnecting"
case .disconnected: "Offline"
}
}
private var connectionSymbol: String {
model.snapshot.connection.state == .connected ? "checkmark.circle.fill" : "network.slash"
}
private var connectionColor: Color {
model.snapshot.connection.state == .connected ? .green : .secondary
}
private var connectionDescription: String {
model.snapshot.connection.endpoint ?? "No active server"
}
@MainActor
private func save() {
isSaving = true
Task {
@@ -348,6 +348,7 @@
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES;
INFOPLIST_KEY_NSCameraUsageDescription = "Scan a T3 Code pairing QR code to connect this device.";
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Allow T3 Code to connect to T3 Code servers on your local network or tailnet.";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
@@ -383,6 +384,7 @@
INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
INFOPLIST_KEY_NSAppTransportSecurity_NSAllowsArbitraryLoads = YES;
INFOPLIST_KEY_NSCameraUsageDescription = "Scan a T3 Code pairing QR code to connect this device.";
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Allow T3 Code to connect to T3 Code servers on your local network or tailnet.";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
@@ -0,0 +1,99 @@
import Testing
@testable import T3Code
@Suite("Connection details")
struct ConnectionDetailsTests {
@Test
func parsesRawPairingURL() throws {
let details = try ConnectionDetailsParser.parse(
"http://192.168.1.42:3773/pair#token=PAIRCODE"
)
#expect(details.endpoint == "http://192.168.1.42:3773")
#expect(details.pairingCode == "PAIRCODE")
}
@Test
func parsesHostedPairingURL() throws {
let details = try ConnectionDetailsParser.parse(
"https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.tailnet.ts.net%2F#token=PAIRCODE"
)
#expect(details.endpoint == "https://desktop.tailnet.ts.net")
#expect(details.pairingCode == "PAIRCODE")
}
@Test(arguments: [
"t3code://pair?pairingUrl=https%3A%2F%2Fremote.example.com%2Fpair%23token%3Dpairing-token",
"t3code:?pairingUrl=https%3A%2F%2Fremote.example.com%2Fpair%23token%3Dpairing-token",
])
func unwrapsMobileQRCode(_ payload: String) throws {
let details = try ConnectionDetailsParser.parse(payload)
#expect(details.endpoint == "https://remote.example.com")
#expect(details.pairingCode == "pairing-token")
}
@Test
func extractsPairingURLFromSurroundingText() throws {
let details = try ConnectionDetailsParser.parse(
"Pairing URL: http://10.0.0.8:18773/pair#token=ABC123\nOpen this on your phone."
)
#expect(details.endpoint == "http://10.0.0.8:18773")
#expect(details.pairingCode == "ABC123")
}
@Test
func splitsManualAddressAndCode() throws {
let details = try ConnectionDetailsParser.parse("192.168.20.2:3773 ABC123")
#expect(details.endpoint == "http://192.168.20.2:3773")
#expect(details.pairingCode == "ABC123")
}
@Test
func mapsCancellationToUsefulCopy() {
let message = ConnectionErrorCopy.message(for: "cancelled")
#expect(!message.lowercased().contains("cancelled"))
#expect(message.contains("Make sure T3 Code is running"))
}
}
@Suite("Local endpoint detection")
struct LocalEndpointDetectionTests {
@Test(arguments: [
"localhost",
"studio.local",
"127.0.0.1",
"10.20.30.40",
"172.20.10.2",
"192.168.213.171",
"[::1]",
"::1",
"[fe80::aede:48ff:fe00:1122]:3773",
"fd12:3456:789a::1",
"fc00::1",
])
func recognizesLocalHosts(_ host: String) {
#expect(EndpointNetworkScope.isLocalHost(host))
}
@Test(arguments: [
"8.8.8.8",
"172.32.0.1",
"example.com",
"2001:4860:4860::8888",
])
func rejectsPublicHosts(_ host: String) {
#expect(!EndpointNetworkScope.isLocalHost(host))
}
@Test
func bracketsBareIPv6DuringNormalization() throws {
let endpoint = try ConnectionDetailsParser.normalizedEndpoint("::1")
#expect(endpoint == "http://[::1]")
}
}
@@ -0,0 +1,54 @@
import Foundation
import Testing
@testable import T3Code
@Suite("Device management")
struct DeviceManagementTests {
@Test
func sortsCurrentThenOnlineThenRecent() {
let now = Date()
let current = session(
id: "current",
at: now.addingTimeInterval(-300),
isCurrent: true
)
let online = session(
id: "online",
at: now.addingTimeInterval(-600),
isConnected: true
)
let recent = session(id: "recent", at: now.addingTimeInterval(-60))
let older = session(id: "older", at: now.addingTimeInterval(-3_600))
let sorted = FeatureDeviceSession.sortedForDisplay([older, recent, online, current])
#expect(sorted.map(\.id) == ["current", "online", "recent", "older"])
}
@Test
func usesSafeFallbackLabels() {
let current = session(id: "current", at: .now, isCurrent: true)
let desktop = session(id: "desktop", at: .now, deviceType: .desktop)
#expect(current.displayName == "This device")
#expect(desktop.displayName == "Desktop")
}
private func session(
id: String,
at date: Date,
deviceType: FeatureDeviceType = .mobile,
isConnected: Bool = false,
isCurrent: Bool = false
) -> FeatureDeviceSession {
FeatureDeviceSession(
sessionID: id,
deviceType: deviceType,
issuedAt: date.addingTimeInterval(-100),
expiresAt: date.addingTimeInterval(86_400),
lastConnectedAt: date,
isConnected: isConnected,
isCurrent: isCurrent
)
}
}