Show connection progress at app startup instead of flashing screens

This commit is contained in:
Ian Gulliver
2026-10-20 14:20:35 -07:00
parent da7f952855
commit a2571763b4
3 changed files with 80 additions and 26 deletions
+3 -3
View File
@@ -10,7 +10,7 @@ The app joins the tailnet as its own node and reaches byre's HTTPS origin on byr
## Tailnet
`Tailnet.swift` runs one node per app install with libtailscale, through the C API of TailscaleKit (`tailscale_new` and the rest, from the umbrella header): hostname `byre-app-<slug of the Mac's name>` (the slug as the server's, see "Tailnet" in `docs/operations.md`), not ephemeral, its state in `tsnet` in `run.fc.byre.mac` under Application Support. It starts at launch (`tailnetNode`, which exits the app if libtailscale can't start) and opens the node's loopback SOCKS5 proxy (`tailscale_loopback`). `API` sets that proxy, with user `tsnet` and the proxy credential, as the `proxyConfigurations` of its `URLSession`, so REST, the SSE streams (`EventStream`), the command channel (`Remote`) and terminals (`Terminal`) all go over the tailnet; only `GET /api/tailnet` to the local service's loopback address uses `URLSession.shared`. `Tailnet` polls the node's status (`tailscale_status_json`) every second, and every 2 s reads `GET /api/tailnet` at the local service's loopback address (the `loopback` `byre check` prints, found once at launch). Until the app's node is `Running`, and while the local service's node is `NeedsLogin`, the window shows only the sign-in screen: a row per node (the app's, and the local service's when one answers), each **Signed in**, or **Sign in to Tailscale**, which opens that node's `AuthURL` in the browser. Servers are added without typing in two ways. When the local service's node runs with an `origin`, that origin is saved as a server (a `ServerRecord`, so iCloud carries it to every Mac on the account). Every 10 s, the app also takes each online tailnet peer owned by its node's user whose MagicDNS name starts with `byre-` but not `byre-app-`, and saves it when `GET /api/admin/status` answers there. Either way a forgotten server comes back the next time it is found. Preview forwards dial through the node too (see "Previews" in `docs/operations.md`).
`Tailnet.swift` runs one node per app install with libtailscale, through the C API of TailscaleKit (`tailscale_new` and the rest, from the umbrella header): hostname `byre-app-<slug of the Mac's name>` (the slug as the server's, see "Tailnet" in `docs/operations.md`), not ephemeral, its state in `tsnet` in `run.fc.byre.mac` under Application Support. It starts at launch (`tailnetNode`, which exits the app if libtailscale can't start) and opens the node's loopback SOCKS5 proxy (`tailscale_loopback`). `API` sets that proxy, with user `tsnet` and the proxy credential, as the `proxyConfigurations` of its `URLSession`, so REST, the SSE streams (`EventStream`), the command channel (`Remote`) and terminals (`Terminal`) all go over the tailnet; only `GET /api/tailnet` to the local service's loopback address uses `URLSession.shared`. `Tailnet` polls the node's status (`tailscale_status_json`) every second, and every 2 s reads `GET /api/tailnet` at the local service's loopback address (the `loopback` `byre check` prints, found once at launch). Until the app's node is `Running`, the window shows a spinner with "Starting Tailscale…"; while the app's node is `NeedsLogin` or `NeedsMachineAuth`, or the local service's node is `NeedsLogin`, it shows only the sign-in screen instead: a row per node (the app's, and the local service's when one answers), each **Signed in**, or **Sign in to Tailscale**, which opens that node's `AuthURL` in the browser. Servers are added without typing in two ways. When the local service's node runs with an `origin`, that origin is saved as a server (a `ServerRecord`, so iCloud carries it to every Mac on the account). Once the app's node runs, and every 10 s after, the app also takes each online tailnet peer owned by its node's user whose MagicDNS name starts with `byre-` but not `byre-app-`, and saves it when `GET /api/admin/status` answers there within 5 s, probing all of them at once. Either way a forgotten server comes back the next time it is found. Preview forwards dial through the node too (see "Previews" in `docs/operations.md`).
`mac/bundle.sh` builds TailscaleKit from `github.com/tailscale/libtailscale` at the commit pinned in the script (`libtailscale=`): it clones it into `~/Library/Caches/byre/build/libtailscale-<commit>`, runs its `make -C swift macos` (Go's `c-archive` build, then `xcodebuild` of the framework, unsigned) and wraps the framework with `xcodebuild -create-xcframework`, once per commit, under the build lock. It copies that into the shared build directory's `mac/Frameworks/TailscaleKit.xcframework`, which `mac/Package.swift` names as a binary target, and bundles and signs the framework in `Contents/Frameworks` like Sparkle's. To move to a newer libtailscale, change the pinned commit.
@@ -81,7 +81,7 @@ API calls go through the generated `Client` over `URLSessionTransport`. A middle
`EventStream` is a hand-written SSE client over `URLSession.bytes(for:)`. It splits lines itself, because `AsyncBytes.lines` drops the blank lines that end SSE events, and parses off the main actor, handing each frame to it. It handles `id`, `event: ping`, `event: ready` and `data`: it tracks the last seq, reconnects from it after a stale threshold (40 s, checked every 5 s) and a retry delay (2 s), when the network comes back (`NWPathMonitor`), and when the app becomes active with a stale stream. An event whose data doesn't decode is logged and skipped. There are two streams, global (after the bootstrap `last_event_seq`) and lead (`?lead=true`, after the last event of the lead's first page), and only the global one drives the connection dot.
Startup: `GET /api/admin/status`, then me, projects, inbox, lead sessions and summary reads in parallel, then drafts, focus, the lead stream, the window, the global stream. A failure before the window shows replaces it with `byre failed to start: <error>` and the whole startup is tried again every 2 s until it succeeds, so a server restarting (after an update replaces its binary, for one) heals by itself; Forget Server leaves that screen. `handleEvent` calls `notifyInbox` on `inbox.created`, `notifyTurn` on `turn.ended`, and `notifyTask` on the task events listed under "Notifications" in `docs/operations.md`.
Startup waits for the app's tailnet node to run, then: `GET /api/admin/status`, then me, projects, inbox, lead sessions and summary reads in parallel, then drafts, focus, the lead stream, the window, the global stream. Until the window shows, a spinner reads "Connecting to <server>…". A failure adds `Retrying: <error>` below it (explained as Connect explains one) and the whole startup is tried again every 2 s until it succeeds, so a server restarting (after an update replaces its binary, for one) heals by itself; Forget Server leaves that screen. `handleEvent` calls `notifyInbox` on `inbox.created`, `notifyTurn` on `turn.ended`, and `notifyTask` on the task events listed under "Notifications" in `docs/operations.md`.
The app logs through `os.Logger` with subsystem `run.fc.byre.mac`: `log show --last 10m --predicate 'subsystem == "run.fc.byre.mac"'` prints it.
@@ -160,7 +160,7 @@ The app menu has About, Check for Updates…, Forget Server (for the server the
## Connection
Once the app's node runs (see "Tailnet"), on first launch and from Add Server…, the window shows one field, Server URL (an `https` origin with no path, a byre node's `ts.net` origin), Connect, and Run byre on this Mac. Run byre on this Mac runs the bundle's `byre check`, then, unless the service is already loaded, `Contents/Helpers/byre install`, both through the user's login shell (`pw_shell -l -c 'exec "$BYRE_HELPER" install'`, which sh, zsh, bash and fish all accept), since `byre install` copies its `PATH` into the service and the app's own `PATH` from launchd finds none of `claude`, `codex`, `agy` or `npx`. It then polls `GET /api/tailnet` at the check's `loopback` address every 500 ms, failing if nothing answers for 10 s, and waits as long as the service's node takes to run (while it needs signing in, the window shows the sign-in screen, see "Tailnet"); a node that runs with no `origin` (the tailnet has no HTTPS certificates) stops it with how to turn them on and restart the service, which the Server tab shows too; once the node runs it takes its `origin`, polls `GET /api/admin/status` there for up to 15 s while the app's node learns of the new one, then connects to it as Connect does. Connect calls `GET /api/admin/status` and explains a failure: an untrusted certificate, an unreachable server ("Is byre running there?"), 401 (byre couldn't identify the app's node), 403 (a tagged node); anything else shows the error's own text. Certificate validation is never relaxed. On success the origin, normalized to a lower-case host with any port, is saved as a `ServerRecord` (see "Persistence") with the first task colour no other saved server uses, startup runs, and the window switches to that server; later launches start against every saved server directly. Connecting to a server whose startup failed replaces its failed connection with a new one, keeping its record and colour. Connecting to a saved server switches to it, so each server has one `Store`; worktree images (`ImageCache`) and review patches (keyed by origin) are cached per server. Each finished CloudKit import (`NSPersistentCloudKitContainer.eventChangedNotification`) reloads the saved servers: it starts a connection for each new one and stops the connection of each one forgotten on another Mac, and when the window shows the connection screen with an empty field it takes the first new one, so on a new Mac the address another Mac saved connects without typing. Forget Server deletes the current server's `ServerRecord` (on every Mac, through iCloud), stops its connection and shows the connection screen with the old origin in the field.
Once the app's node runs (see "Tailnet") and its first search of the tailnet for servers has finished (until then a spinner reads "Looking for byre servers on the tailnet…"), on first launch with no server found and from Add Server…, the window shows one field, Server URL (an `https` origin with no path, a byre node's `ts.net` origin), Connect, and Run byre on this Mac. Run byre on this Mac runs the bundle's `byre check`, then, unless the service is already loaded, `Contents/Helpers/byre install`, both through the user's login shell (`pw_shell -l -c 'exec "$BYRE_HELPER" install'`, which sh, zsh, bash and fish all accept), since `byre install` copies its `PATH` into the service and the app's own `PATH` from launchd finds none of `claude`, `codex`, `agy` or `npx`. It then polls `GET /api/tailnet` at the check's `loopback` address every 500 ms, failing if nothing answers for 10 s, and waits as long as the service's node takes to run (while it needs signing in, the window shows the sign-in screen, see "Tailnet"); a node that runs with no `origin` (the tailnet has no HTTPS certificates) stops it with how to turn them on and restart the service, which the Server tab shows too; once the node runs it takes its `origin`, polls `GET /api/admin/status` there for up to 15 s while the app's node learns of the new one, then connects to it as Connect does. Connect calls `GET /api/admin/status` and explains a failure: an untrusted certificate, an unreachable server ("Is byre running there?"), 401 (byre couldn't identify the app's node), 403 (a tagged node); anything else shows the error's own text. Certificate validation is never relaxed. On success the origin, normalized to a lower-case host with any port, is saved as a `ServerRecord` (see "Persistence") with the first task colour no other saved server uses, startup runs, and the window switches to that server; later launches start against every saved server directly. Connecting to a server whose startup failed replaces its failed connection with a new one, keeping its record and colour. Connecting to a saved server switches to it, so each server has one `Store`; worktree images (`ImageCache`) and review patches (keyed by origin) are cached per server. Each finished CloudKit import (`NSPersistentCloudKitContainer.eventChangedNotification`) reloads the saved servers: it starts a connection for each new one and stops the connection of each one forgotten on another Mac, and when the window shows the connection screen with an empty field it takes the first new one, so on a new Mac the address another Mac saved connects without typing. Forget Server deletes the current server's `ServerRecord` (on every Mac, through iCloud), stops its connection and shows the connection screen with the old origin in the field.
## Updates
+32 -12
View File
@@ -198,6 +198,9 @@ final class Connection {
private func start() async {
let old = store
while !stopped, !Tailnet.shared.running {
try? await Task.sleep(for: .milliseconds(500))
}
while !stopped, !(await attempt(old)) {
try? await Task.sleep(for: .seconds(2))
}
@@ -251,7 +254,7 @@ final class Connection {
} catch {
await store.stop()
if !stopped {
phase = .failed("byre failed to start: \(errorText(error))")
phase = .failed(explain(error, origin))
}
return false
}
@@ -437,15 +440,27 @@ struct ConnectView: View {
}
}
struct FatalView: View {
let message: String
struct ConnectingView: View {
let step: String
var problem: String?
var body: some View {
Text(message)
.foregroundStyle(Palette.danger)
.textSelection(.enabled)
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 10) {
ProgressView()
.controlSize(.small)
Text(step)
}
if let problem {
Text("Retrying: \(problem)")
.foregroundStyle(Palette.muted)
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
}
}
.frame(width: 460, alignment: .leading)
.padding(.vertical, 24)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
@@ -477,20 +492,25 @@ struct ServerWindow: View {
@ViewBuilder
private var content: some View {
if !Tailnet.shared.signedIn {
if Tailnet.shared.needsLogin {
TailnetLoginView()
} else if !Tailnet.shared.running {
ConnectingView(step: "Starting Tailscale…")
} else if let connection {
let step = "Connecting to \(serverName(connection.origin.absoluteString))…"
switch connection.phase {
case .starting:
Color.clear
case .failed(let message):
FatalView(message: message)
ConnectingView(step: step)
case .failed(let problem):
ConnectingView(step: step, problem: problem)
case .running(let store):
MainView()
.environment(store)
.environment(connection.overlays)
.id(ObjectIdentifier(store))
}
} else if !Tailnet.shared.searched {
ConnectingView(step: "Looking for byre servers on the tailnet…")
} else {
ConnectView(form: form) { connected in
form.serverText = ""
+45 -11
View File
@@ -130,14 +130,15 @@ final class Tailnet {
private(set) var state = "Starting"
private(set) var authURL: URL?
private(set) var service: TailnetInfo?
private(set) var searched = false
@ObservationIgnored private var servers: [URL] = []
var running: Bool {
state == "Running"
}
var signedIn: Bool {
running && service?.state != "NeedsLogin"
var needsLogin: Bool {
state == "NeedsLogin" || state == "NeedsMachineAuth" || service?.state == "NeedsLogin"
}
private init() {
@@ -181,19 +182,52 @@ final class Tailnet {
private func discover() async {
while true {
if running {
for origin in servers where !Servers.shared.origins.contains(origin.absoluteString) {
let api = API(origin: origin)
if (try? await api.client.getStatus().ok) != nil {
log.notice("found \(origin.absoluteString, privacy: .public) on the tailnet")
Servers.shared.add(origin)
}
api.session.finishTasksAndInvalidate()
}
guard running else {
try? await Task.sleep(for: .milliseconds(500))
continue
}
let candidates = servers.filter { !Servers.shared.origins.contains($0.absoluteString) }
let found = await withTaskGroup(of: URL?.self) { group in
for origin in candidates {
group.addTask {
await Self.probe(origin) ? origin : nil
}
}
var found: [URL] = []
for await origin in group {
if let origin {
found.append(origin)
}
}
return found
}
for origin in found {
log.notice("found \(origin.absoluteString, privacy: .public) on the tailnet")
Servers.shared.add(origin)
}
searched = true
try? await Task.sleep(for: .seconds(10))
}
}
private nonisolated static func probe(_ origin: URL) async -> Bool {
let api = API(origin: origin)
defer {
api.session.invalidateAndCancel()
}
return await withTaskGroup(of: Bool.self) { group in
group.addTask {
(try? await api.client.getStatus().ok) != nil
}
group.addTask {
try? await Task.sleep(for: .seconds(5))
return false
}
let ok = await group.next() ?? false
group.cancelAll()
return ok
}
}
}
struct TailnetLoginView: View {